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 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591 16592 16593 16594 16595 16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612 16613 16614 16615 16616 16617 16618 16619 16620 16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643 16644 16645 16646 16647 16648 16649 16650 16651 16652 16653 16654 16655 16656 16657 16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746 16747 16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791 16792 16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816 16817 16818 16819 16820 16821 16822 16823 16824 16825 16826 16827 16828 16829 16830 16831 16832 16833 16834 16835 16836 16837 16838 16839 16840 16841 16842 16843 16844 16845 16846 16847 16848 16849 16850 16851 16852 16853 16854 16855 16856 16857 16858 16859 16860 16861 16862 16863 16864 16865 16866 16867 16868 16869 16870 16871 16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891 16892 16893 16894 16895 16896 16897 16898 16899 16900 16901 16902 16903 16904 16905 16906 16907 16908 16909 16910 16911 16912 16913 16914 16915 16916 16917 16918 16919 16920 16921 16922 16923 16924 16925 16926 16927 16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942 16943 16944 16945 16946 16947 16948 16949 16950 16951 16952 16953 16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964 16965 16966 16967 16968 16969 16970 16971 16972 16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985 16986 16987 16988 16989 16990 16991 16992 16993 16994 16995 16996 16997 16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126 17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185 17186 17187 17188 17189 17190 17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573 17574 17575 17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591 17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625 17626 17627 17628 17629 17630 17631 17632 17633 17634 17635 17636 17637 17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658 17659 17660 17661 17662 17663 17664 17665 17666 17667 17668 17669 17670 17671 17672 17673 17674 17675 17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699 17700 17701 17702 17703 17704 17705 17706 17707 17708 17709 17710 17711 17712 17713 17714 17715 17716 17717 17718 17719 17720 17721 17722 17723 17724 17725 17726 17727 17728 17729 17730 17731 17732 17733 17734 17735 17736 17737 17738 17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749 17750 17751 17752 17753 17754 17755 17756 17757 17758 17759 17760 17761 17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788 17789 17790 17791 17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806 17807 17808 17809 17810 17811 17812 17813 17814 17815 17816 17817 17818 17819 17820 17821 17822 17823 17824 17825 17826 17827 17828 17829 17830 17831 17832 17833 17834 17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846 17847 17848 17849 17850 17851 17852 17853 17854 17855 17856 17857 17858 17859 17860 17861 17862 17863 17864 17865 17866 17867 17868 17869 17870 17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891 17892 17893 17894 17895 17896 17897 17898 17899 17900 17901 17902 17903 17904 17905 17906 17907 17908 17909 17910 17911 17912 17913 17914 17915 17916 17917 17918 17919 17920 17921 17922 17923 17924 17925 17926 17927 17928 17929 17930 17931 17932 17933 17934 17935 17936 17937 17938 17939 17940 17941 17942 17943 17944 17945 17946 17947 17948 17949 17950 17951 17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969 17970 17971 17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982 17983 17984 17985 17986 17987 17988 17989 17990 17991 17992 17993 17994 17995 17996 17997 17998 17999 18000 18001 18002 18003 18004 18005 18006 18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018 18019 18020 18021 18022 18023 18024 18025 18026 18027 18028 18029 18030 18031 18032 18033 18034 18035 18036 18037 18038 18039 18040 18041 18042 18043 18044 18045 18046 18047 18048 18049 18050 18051 18052 18053 18054 18055 18056 18057 18058 18059 18060 18061 18062 18063 18064 18065 18066 18067 18068 18069 18070 18071 18072 18073 18074 18075 18076 18077 18078 18079 18080 18081 18082 18083 18084 18085 18086 18087 18088 18089 18090 18091 18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131 18132 18133 18134 18135 18136 18137 18138 18139 18140 18141 18142 18143 18144 18145 18146 18147 18148 18149 18150 18151 18152 18153 18154 18155 18156 18157 18158 18159 18160 18161 18162 18163 18164 18165 18166 18167 18168 18169 18170 18171 18172 18173 18174 18175 18176 18177 18178 18179 18180 18181 18182 18183 18184 18185 18186 18187 18188 18189 18190 18191 18192 18193 18194 18195 18196 18197 18198 18199 18200 18201 18202 18203 18204 18205 18206 18207 18208 18209 18210 18211 18212 18213 18214 18215 18216 18217 18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228 18229 18230 18231 18232 18233 18234 18235 18236 18237 18238 18239 18240 18241 18242 18243 18244 18245 18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290 18291 18292 18293 18294 18295 18296 18297 18298 18299 18300 18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319 18320 18321 18322 18323 18324 18325 18326 18327 18328 18329 18330 18331 18332 18333 18334 18335 18336 18337 18338 18339 18340 18341 18342 18343 18344 18345 18346 18347 18348 18349 18350 18351 18352 18353 18354 18355 18356 18357 18358 18359 18360 18361 18362 18363 18364 18365 18366 18367 18368 18369 18370 18371 18372 18373 18374 18375 18376 18377 18378 18379 18380 18381 18382 18383 18384 18385 18386 18387 18388 18389 18390 18391 18392 18393 18394 18395 18396 18397 18398 18399 18400 18401 18402 18403 18404 18405 18406 18407 18408 18409 18410 18411 18412 18413 18414 18415 18416 18417 18418 18419 18420 18421 18422 18423 18424 18425 18426 18427 18428 18429 18430 18431 18432 18433 18434 18435 18436 18437 18438 18439 18440 18441 18442 18443 18444 18445 18446 18447 18448 18449 18450 18451 18452 18453 18454 18455 18456 18457 18458 18459 18460 18461 18462 18463 18464 18465 18466 18467 18468 18469 18470 18471 18472 18473 18474 18475 18476 18477 18478 18479 18480 18481 18482 18483 18484 18485 18486 18487 18488 18489 18490 18491 18492 18493 18494 18495 18496 18497 18498 18499 18500 18501 18502 18503 18504 18505 18506 18507 18508 18509 18510 18511 18512 18513 18514 18515 18516 18517 18518 18519 18520 18521 18522 18523 18524 18525 18526 18527 18528 18529 18530 18531 18532 18533 18534 18535 18536 18537 18538 18539 18540 18541 18542 18543 18544 18545 18546 18547 18548 18549 18550 18551 18552 18553 18554 18555 18556 18557 18558 18559 18560 18561 18562 18563 18564 18565 18566 18567 18568 18569 18570 18571 18572 18573 18574 18575 18576 18577 18578 18579 18580 18581 18582 18583 18584 18585 18586 18587 18588 18589 18590 18591 18592 18593 18594 18595 18596 18597 18598 18599 18600 18601 18602 18603 18604 18605 18606 18607 18608 18609 18610 18611 18612 18613 18614 18615 18616 18617 18618 18619 18620 18621 18622 18623 18624 18625 18626 18627 18628 18629 18630 18631 18632 18633 18634 18635 18636 18637 18638 18639 18640 18641 18642 18643 18644 18645 18646 18647 18648 18649 18650 18651 18652 18653 18654 18655 18656 18657 18658 18659 18660 18661 18662 18663 18664 18665 18666 18667 18668 18669 18670 18671 18672 18673 18674 18675 18676 18677 18678 18679 18680 18681 18682 18683 18684 18685 18686 18687 18688 18689 18690 18691 18692 18693 18694 18695 18696 18697 18698 18699 18700 18701 18702 18703 18704 18705 18706 18707 18708 18709 18710 18711 18712 18713 18714 18715 18716 18717 18718 18719 18720 18721 18722 18723 18724 18725 18726 18727 18728 18729 18730 18731 18732 18733 18734 18735 18736 18737 18738 18739 18740 18741 18742 18743 18744 18745 18746 18747 18748 18749 18750 18751 18752 18753 18754 18755 18756 18757 18758 18759 18760 18761 18762 18763 18764 18765 18766 18767 18768 18769 18770 18771 18772 18773 18774 18775 18776 18777 18778 18779 18780 18781 18782 18783 18784 18785 18786 18787 18788 18789 18790 18791 18792 18793 18794 18795 18796 18797 18798 18799 18800 18801 18802 18803 18804 18805 18806 18807 18808 18809 18810 18811 18812 18813 18814 18815 18816 18817 18818 18819 18820 18821 18822 18823 18824 18825 18826 18827 18828 18829 18830 18831 18832 18833 18834 18835 18836 18837 18838 18839 18840 18841 18842 18843 18844 18845 18846 18847 18848 18849 18850 18851 18852 18853 18854 18855 18856 18857 18858 18859 18860 18861 18862 18863 18864 18865 18866 18867 18868 18869 18870 18871 18872 18873 18874 18875 18876 18877 18878 18879 18880 18881 18882 18883 18884 18885 18886 18887 18888 18889 18890 18891 18892 18893 18894 18895 18896 18897 18898 18899 18900 18901 18902 18903 18904 18905 18906 18907 18908 18909 18910 18911 18912 18913 18914 18915 18916 18917 18918 18919 18920 18921 18922 18923 18924 18925 18926 18927 18928 18929 18930 18931 18932 18933 18934 18935 18936 18937 18938 18939 18940 18941 18942 18943 18944 18945 18946 18947 18948 18949 18950 18951 18952 18953 18954 18955 18956 18957 18958 18959 18960 18961 18962 18963 18964 18965 18966 18967 18968 18969 18970 18971 18972 18973 18974 18975 18976 18977 18978 18979 18980 18981 18982 18983 18984 18985 18986 18987 18988 18989 18990 18991 18992 18993 18994 18995 18996 18997 18998 18999 19000 19001 19002 19003 19004 19005 19006 19007 19008 19009 19010 19011 19012 19013 19014 19015 19016 19017 19018 19019 19020 19021 19022 19023 19024 19025 19026 19027 19028 19029 19030 19031 19032 19033 19034 19035 19036 19037 19038 19039 19040 19041 19042 19043 19044 19045 19046 19047 19048 19049 19050 19051 19052 19053 19054 19055 19056 19057 19058 19059 19060 19061 19062 19063 19064 19065 19066 19067 19068 19069 19070 19071 19072 19073 19074 19075 19076 19077 19078 19079 19080 19081 19082 19083 19084 19085 19086 19087 19088 19089 19090 19091 19092 19093 19094 19095 19096 19097 19098 19099 19100 19101 19102 19103 19104 19105 19106 19107 19108 19109 19110 19111 19112 19113 19114 19115 19116 19117 19118 19119 19120 19121 19122 19123 19124 19125 19126 19127 19128 19129 19130 19131 19132 19133 19134 19135 19136 19137 19138 19139 19140 19141 19142 19143 19144 19145 19146 19147 19148 19149 19150 19151 19152 19153 19154 19155 19156 19157 19158 19159 19160 19161 19162 19163 19164 19165 19166 19167 19168 19169 19170 19171 19172 19173 19174 19175 19176 19177 19178 19179 19180 19181 19182 19183 19184 19185 19186 19187 19188 19189 19190 19191 19192 19193 19194 19195 19196 19197 19198 19199 19200 19201 19202 19203 19204 19205 19206 19207 19208 19209 19210 19211 19212 19213 19214 19215 19216 19217 19218 19219 19220 19221 19222 19223 19224 19225 19226 19227 19228 19229 19230 19231 19232 19233 19234 19235 19236 19237 19238 19239 19240 19241 19242 19243 19244 19245 19246 19247 19248 19249 19250 19251 19252 19253 19254 19255 19256 19257 19258 19259 19260 19261 19262 19263 19264 19265 19266 19267 19268 19269 19270 19271 19272 19273 19274 19275 19276 19277 19278 19279 19280 19281 19282 19283 19284 19285 19286 19287 19288 19289 19290 19291 19292 19293 19294 19295 19296 19297 19298 19299 19300 19301 19302 19303 19304 19305 19306 19307 19308 19309 19310 19311 19312 19313 19314 19315 19316 19317 19318 19319 19320 19321 19322 19323 19324 19325 19326 19327 19328 19329 19330 19331 19332 19333 19334 19335 19336 19337 19338 19339 19340 19341 19342 19343 19344 19345 19346 19347 19348 19349 19350 19351 19352 19353 19354 19355 19356 19357 19358 19359 19360 19361 19362 19363 19364 19365 19366 19367 19368 19369 19370 19371 19372 19373 19374 19375 19376 19377 19378 19379 19380 19381 19382 19383 19384 19385 19386 19387 19388 19389 19390 19391 19392 19393 19394 19395 19396 19397 19398 19399 19400 19401 19402 19403 19404 19405 19406 19407 19408 19409 19410 19411 19412 19413 19414 19415 19416 19417 19418 19419 19420 19421 19422 19423 19424 19425 19426 19427 19428 19429 19430 19431 19432 19433 19434 19435 19436 19437 19438 19439 19440 19441 19442 19443 19444 19445 19446 19447 19448 19449 19450 19451 19452 19453 19454 19455 19456 19457 19458 19459 19460 19461 19462 19463 19464 19465 19466 19467 19468 19469 19470 19471 19472 19473 19474 19475 19476 19477 19478 19479 19480 19481 19482 19483 19484 19485 19486 19487 19488 19489 19490 19491 19492 19493 19494 19495 19496 19497 19498 19499 19500 19501 19502 19503 19504 19505 19506 19507 19508 19509 19510 19511 19512 19513 19514 19515 19516 19517 19518 19519 19520 19521 19522 19523 19524 19525 19526 19527 19528 19529 19530 19531 19532 19533 19534 19535 19536 19537 19538 19539 19540 19541 19542 19543 19544 19545 19546 19547 19548 19549 19550 19551 19552 19553 19554 19555 19556 19557 19558 19559 19560 19561 19562 19563 19564 19565 19566 19567 19568 19569 19570 19571 19572 19573 19574 19575 19576 19577 19578 19579 19580 19581 19582 19583 19584 19585 19586 19587 19588 19589 19590 19591 19592 19593 19594 19595 19596 19597 19598 19599 19600 19601 19602 19603 19604 19605 19606 19607 19608 19609 19610 19611 19612 19613 19614 19615 19616 19617 19618 19619 19620 19621 19622 19623 19624 19625 19626 19627 19628 19629 19630 19631 19632 19633 19634 19635 19636 19637 19638 19639 19640 19641 19642 19643 19644 19645 19646 19647 19648 19649 19650 19651 19652 19653 19654 19655 19656 19657 19658 19659 19660 19661 19662 19663 19664 19665 19666 19667 19668 19669 19670 19671 19672 19673 19674 19675 19676 19677 19678 19679 19680 19681 19682 19683 19684 19685 19686 19687 19688 19689 19690 19691 19692 19693 19694 19695 19696 19697 19698 19699 19700 19701 19702 19703 19704 19705 19706 19707 19708 19709 19710 19711 19712 19713 19714 19715 19716 19717 19718 19719 19720 19721 19722 19723 19724 19725 19726 19727 19728 19729 19730 19731 19732 19733 19734 19735 19736 19737 19738 19739 19740 19741 19742 19743 19744 19745 19746 19747 19748 19749 19750 19751 19752 19753 19754 19755 19756 19757 19758 19759 19760 19761 19762 19763 19764 19765 19766 19767 19768 19769 19770 19771 19772 19773 19774 19775 19776 19777 19778 19779 19780 19781 19782 19783 19784 19785 19786 19787 19788 19789 19790 19791 19792 19793 19794 19795 19796 19797 19798 19799 19800 19801 19802 19803 19804 19805 19806 19807 19808 19809 19810 19811 19812 19813 19814 19815 19816 19817 19818 19819 19820 19821 19822 19823 19824 19825 19826 19827 19828 19829 19830 19831 19832 19833 19834 19835 19836 19837 19838 19839 19840 19841 19842 19843 19844 19845 19846 19847 19848 19849 19850 19851 19852 19853 19854 19855 19856 19857 19858 19859 19860 19861 19862 19863 19864 19865 19866 19867 19868 19869 19870 19871 19872 19873 19874 19875 19876 19877 19878 19879 19880 19881 19882 19883 19884 19885 19886 19887 19888 19889 19890 19891 19892 19893 19894 19895 19896 19897 19898 19899 19900 19901 19902 19903 19904 19905 19906 19907 19908 19909 19910 19911 19912 19913 19914 19915 19916 19917 19918 19919 19920 19921 19922 19923 19924 19925 19926 19927 19928 19929 19930 19931 19932 19933 19934 19935 19936 19937 19938 19939 19940 19941 19942 19943 19944 19945 19946 19947 19948 19949 19950 19951 19952 19953 19954 19955 19956 19957 19958 19959 19960 19961 19962 19963 19964 19965 19966 19967 19968 19969 19970 19971 19972 19973 19974 19975 19976 19977 19978 19979 19980 19981 19982 19983 19984 19985 19986 19987 19988 19989 19990 19991 19992 19993 19994 19995 19996 19997 19998 19999 20000 20001 20002 20003 20004 20005 20006 20007 20008 20009 20010 20011 20012 20013 20014 20015 20016 20017 20018 20019 20020 20021 20022 20023 20024 20025 20026 20027 20028 20029 20030 20031 20032 20033 20034 20035 20036 20037 20038 20039 20040 20041 20042 20043 20044 20045 20046 20047 20048 20049 20050 20051 20052 20053 20054 20055 20056 20057 20058 20059 20060 20061 20062 20063 20064 20065 20066 20067 20068 20069 20070 20071 20072 20073 20074 20075 20076 20077 20078 20079 20080 20081 20082 20083 20084 20085 20086 20087 20088 20089 20090 20091 20092 20093 20094 20095 20096 20097 20098 20099 20100 20101 20102 20103 20104 20105 20106 20107 20108 20109 20110 20111 20112 20113 20114 20115 20116 20117 20118 20119 20120 20121 20122 20123 20124 20125 20126 20127 20128 20129 20130 20131 20132 20133 20134 20135 20136 20137 20138 20139 20140 20141 20142 20143 20144 20145 20146 20147 20148 20149 20150 20151 20152 20153 20154 20155 20156 20157 20158 20159 20160 20161 20162 20163 20164 20165 20166 20167 20168 20169 20170 20171 20172 20173 20174 20175 20176 20177 20178 20179 20180 20181 20182 20183 20184 20185 20186 20187 20188 20189 20190 20191 20192 20193 20194 20195 20196 20197 20198 20199 20200 20201 20202 20203 20204 20205 20206 20207 20208 20209 20210 20211 20212 20213 20214 20215 20216 20217 20218 20219 20220 20221 20222 20223 20224 20225 20226 20227 20228 20229 20230 20231 20232 20233 20234 20235 20236 20237 20238 20239 20240 20241 20242 20243 20244 20245 20246 20247 20248 20249 20250 20251 20252 20253 20254 20255 20256 20257 20258 20259 20260 20261 20262 20263 20264 20265 20266 20267 20268 20269 20270 20271 20272 20273 20274 20275 20276 20277 20278 20279 20280 20281 20282 20283 20284 20285 20286 20287 20288 20289 20290 20291 20292 20293 20294 20295 20296 20297 20298 20299 20300 20301 20302 20303 20304 20305 20306 20307 20308 20309 20310 20311 20312 20313 20314 20315 20316 20317 20318 20319 20320 20321 20322 20323 20324 20325 20326 20327 20328 20329 20330 20331 20332 20333 20334 20335 20336 20337 20338 20339 20340 20341 20342 20343 20344 20345 20346 20347 20348 20349 20350 20351 20352 20353 20354 20355 20356 20357 20358 20359 20360 20361 20362 20363 20364 20365 20366 20367 20368 20369 20370 20371 20372 20373 20374 20375 20376 20377 20378 20379 20380 20381 20382 20383 20384 20385 20386 20387 20388 20389 20390 20391 20392 20393 20394 20395 20396 20397 20398 20399 20400 20401 20402 20403 20404 20405 20406 20407 20408 20409 20410 20411 20412 20413 20414 20415 20416 20417 20418 20419 20420 20421 20422 20423 20424 20425 20426 20427 20428 20429 20430 20431 20432 20433 20434 20435 20436 20437 20438 20439 20440 20441 20442 20443 20444 20445 20446 20447 20448 20449 20450 20451 20452 20453 20454 20455 20456 20457 20458 20459 20460 20461 20462 20463 20464 20465 20466 20467 20468 20469 20470 20471 20472 20473 20474 20475 20476 20477 20478 20479 20480 20481 20482 20483 20484 20485 20486 20487 20488 20489 20490 20491 20492 20493 20494 20495 20496 20497 20498 20499 20500 20501 20502 20503 20504 20505 20506 20507 20508 20509 20510 20511 20512 20513 20514 20515 20516 20517 20518 20519 20520 20521 20522 20523 20524 20525 20526 20527 20528 20529 20530 20531 20532 20533 20534 20535 20536 20537 20538 20539 20540 20541 20542 20543 20544 20545 20546 20547 20548 20549 20550 20551 20552 20553 20554 20555 20556 20557 20558 20559 20560 20561 20562 20563 20564 20565 20566 20567 20568 20569 20570 20571 20572 20573 20574 20575 20576 20577 20578 20579 20580 20581 20582 20583 20584 20585 20586 20587 20588 20589 20590 20591 20592 20593 20594 20595 20596 20597 20598 20599 20600 20601 20602 20603 20604 20605 20606 20607 20608 20609 20610 20611 20612 20613 20614 20615 20616 20617 20618 20619 20620 20621 20622 20623 20624 20625 20626 20627 20628 20629 20630 20631 20632 20633 20634 20635 20636 20637 20638 20639 20640 20641 20642 20643 20644 20645 20646 20647 20648 20649 20650 20651 20652 20653 20654 20655 20656 20657 20658 20659 20660 20661 20662 20663 20664 20665 20666 20667 20668 20669 20670 20671 20672 20673 20674 20675 20676 20677 20678 20679 20680 20681 20682 20683 20684 20685 20686 20687 20688 20689 20690 20691 20692 20693 20694 20695 20696 20697 20698 20699 20700 20701 20702 20703 20704 20705 20706 20707 20708 20709 20710 20711 20712 20713 20714 20715 20716 20717 20718 20719 20720 20721 20722 20723 20724 20725 20726 20727 20728 20729 20730 20731 20732 20733 20734 20735 20736 20737 20738 20739 20740 20741 20742 20743 20744 20745 20746 20747 20748 20749 20750 20751 20752 20753 20754 20755 20756 20757 20758 20759 20760 20761 20762 20763 20764 20765 20766 20767 20768 20769 20770 20771 20772 20773 20774 20775 20776 20777 20778 20779 20780 20781 20782 20783 20784 20785 20786 20787 20788 20789 20790 20791 20792 20793 20794 20795 20796 20797 20798 20799 20800 20801 20802 20803 20804 20805 20806 20807 20808 20809 20810 20811 20812 20813 20814 20815 20816 20817 20818 20819 20820 20821 20822 20823 20824 20825 20826 20827 20828 20829 20830 20831 20832 20833 20834 20835 20836 20837 20838 20839 20840 20841 20842 20843 20844 20845 20846 20847 20848 20849 20850 20851 20852 20853 20854 20855 20856 20857 20858 20859 20860 20861 20862 20863 20864 20865 20866 20867 20868 20869 20870 20871 20872 20873 20874 20875 20876 20877 20878 20879 20880 20881 20882 20883 20884 20885 20886 20887 20888 20889 20890 20891 20892 20893 20894 20895 20896 20897 20898 20899 20900 20901 20902 20903 20904 20905 20906 20907 20908 20909 20910 20911 20912 20913 20914 20915 20916 20917 20918 20919 20920 20921 20922 20923 20924 20925 20926 20927 20928 20929 20930 20931 20932 20933 20934 20935 20936 20937 20938 20939 20940 20941 20942 20943 20944 20945 20946 20947 20948 20949 20950 20951 20952 20953 20954 20955 20956 20957 20958 20959 20960 20961 20962 20963 20964 20965 20966 20967 20968 20969 20970 20971 20972 20973 20974 20975 20976 20977 20978 20979 20980 20981 20982 20983 20984 20985 20986 20987 20988 20989 20990 20991 20992 20993 20994 20995 20996 20997 20998 20999 21000 21001 21002 21003 21004 21005 21006 21007 21008 21009 21010 21011 21012 21013 21014 21015 21016 21017 21018 21019 21020 21021 21022 21023 21024 21025 21026 21027 21028 21029 21030 21031 21032 21033 21034 21035 21036 21037 21038 21039 21040 21041 21042 21043 21044 21045 21046 21047 21048 21049 21050 21051 21052 21053 21054 21055 21056 21057 21058 21059 21060 21061 21062 21063 21064 21065 21066 21067 21068 21069 21070 21071 21072 21073 21074 21075 21076 21077 21078 21079 21080 21081 21082 21083 21084 21085 21086 21087 21088 21089 21090 21091 21092 21093 21094 21095 21096 21097 21098 21099 21100 21101 21102 21103 21104 21105 21106 21107 21108 21109 21110 21111 21112 21113 21114 21115 21116 21117 21118 21119 21120 21121 21122 21123 21124 21125 21126 21127 21128 21129 21130 21131 21132 21133 21134 21135 21136 21137 21138 21139 21140 21141 21142 21143 21144 21145 21146 21147 21148 21149 21150 21151 21152 21153 21154 21155 21156 21157 21158 21159 21160 21161 21162 21163 21164 21165 21166 21167 21168 21169 21170 21171 21172 21173 21174 21175 21176 21177 21178 21179 21180 21181 21182 21183 21184 21185 21186 21187 21188 21189 21190 21191 21192 21193 21194 21195 21196 21197 21198 21199 21200 21201 21202 21203 21204 21205 21206 21207 21208 21209 21210 21211 21212 21213 21214 21215 21216 21217 21218 21219 21220 21221 21222 21223 21224 21225 21226 21227 21228 21229 21230 21231 21232 21233 21234 21235 21236 21237 21238 21239 21240 21241 21242 21243 21244 21245 21246 21247 21248 21249 21250 21251 21252 21253 21254 21255 21256 21257 21258 21259 21260 21261 21262 21263 21264 21265 21266 21267 21268 21269 21270 21271 21272 21273 21274 21275 21276 21277 21278 21279 21280 21281 21282 21283 21284 21285 21286 21287 21288 21289 21290 21291 21292 21293 21294 21295 21296 21297 21298 21299 21300 21301 21302 21303 21304 21305 21306 21307 21308 21309 21310 21311 21312 21313 21314 21315 21316 21317 21318 21319 21320 21321 21322 21323 21324 21325 21326 21327 21328 21329 21330 21331 21332 21333 21334 21335 21336 21337 21338 21339 21340 21341 21342 21343 21344 21345 21346 21347 21348 21349 21350 21351 21352 21353 21354 21355 21356 21357 21358 21359 21360 21361 21362 21363 21364 21365 21366 21367 21368 21369 21370 21371 21372 21373 21374 21375 21376 21377 21378 21379 21380 21381 21382 21383 21384 21385 21386 21387 21388 21389 21390 21391 21392 21393 21394 21395 21396 21397 21398 21399 21400 21401 21402 21403 21404 21405 21406 21407 21408 21409 21410 21411 21412 21413 21414 21415 21416 21417 21418 21419 21420 21421 21422 21423 21424 21425 21426 21427 21428 21429 21430 21431 21432 21433 21434 21435 21436 21437 21438 21439 21440 21441 21442 21443 21444 21445 21446 21447 21448 21449 21450 21451 21452 21453 21454 21455 21456 21457 21458 21459 21460 21461 21462 21463 21464 21465 21466 21467 21468 21469 21470 21471 21472 21473 21474 21475 21476 21477 21478 21479 21480 21481 21482 21483 21484 21485 21486 21487 21488 21489 21490 21491 21492 21493 21494 21495 21496 21497 21498 21499 21500 21501 21502 21503 21504 21505 21506 21507 21508 21509 21510 21511 21512 21513 21514 21515 21516 21517 21518 21519 21520 21521 21522 21523 21524 21525 21526 21527 21528 21529 21530 21531 21532 21533 21534 21535 21536 21537 21538 21539 21540 21541 21542 21543 21544 21545 21546 21547 21548 21549 21550 21551 21552 21553 21554 21555 21556 21557 21558 21559 21560 21561 21562 21563 21564 21565 21566 21567 21568 21569 21570 21571 21572 21573 21574 21575 21576 21577 21578 21579 21580 21581 21582 21583 21584 21585 21586 21587 21588 21589 21590 21591 21592 21593 21594 21595 21596 21597 21598 21599 21600 21601 21602 21603 21604 21605 21606 21607 21608 21609 21610 21611 21612 21613 21614 21615 21616 21617 21618 21619 21620 21621 21622 21623 21624 21625 21626 21627 21628 21629 21630 21631 21632 21633 21634 21635 21636 21637 21638 21639 21640 21641 21642 21643 21644 21645 21646 21647 21648 21649 21650 21651 21652 21653 21654 21655 21656 21657 21658 21659 21660 21661 21662 21663 21664 21665 21666 21667 21668 21669 21670 21671 21672 21673 21674 21675 21676 21677 21678 21679 21680 21681 21682 21683 21684 21685 21686 21687 21688 21689 21690 21691 21692 21693 21694 21695 21696 21697 21698 21699 21700 21701 21702 21703 21704 21705 21706 21707 21708 21709 21710 21711 21712 21713 21714 21715 21716 21717 21718 21719 21720 21721 21722 21723 21724 21725 21726 21727 21728 21729 21730 21731 21732 21733 21734 21735 21736 21737 21738 21739 21740 21741 21742 21743 21744 21745 21746 21747 21748 21749 21750 21751 21752 21753 21754 21755 21756 21757 21758 21759 21760 21761 21762 21763 21764 21765 21766 21767 21768 21769 21770 21771 21772 21773 21774 21775 21776 21777 21778 21779 21780 21781 21782 21783 21784 21785 21786 21787 21788 21789 21790 21791 21792 21793 21794 21795 21796 21797 21798 21799 21800 21801 21802 21803 21804 21805 21806 21807 21808 21809 21810 21811 21812 21813 21814 21815 21816 21817 21818 21819 21820 21821 21822 21823 21824 21825 21826 21827 21828 21829 21830 21831 21832 21833 21834 21835 21836 21837 21838 21839 21840 21841 21842 21843 21844 21845 21846 21847 21848 21849 21850 21851 21852 21853 21854 21855 21856 21857 21858 21859 21860 21861 21862 21863 21864 21865 21866 21867 21868 21869 21870 21871 21872 21873 21874 21875 21876 21877 21878 21879 21880 21881 21882 21883 21884 21885 21886 21887 21888 21889 21890 21891 21892 21893 21894 21895 21896 21897 21898 21899 21900 21901 21902 21903 21904 21905 21906 21907 21908 21909 21910 21911 21912 21913 21914 21915 21916 21917 21918 21919 21920 21921 21922 21923 21924 21925 21926 21927 21928 21929 21930 21931 21932 21933 21934 21935 21936 21937 21938 21939 21940 21941 21942 21943 21944 21945 21946 21947 21948 21949 21950 21951 21952 21953 21954 21955 21956 21957 21958 21959 21960 21961 21962 21963 21964 21965 21966 21967 21968 21969 21970 21971 21972 21973 21974 21975 21976 21977 21978 21979 21980 21981 21982 21983 21984 21985 21986 21987 21988 21989 21990 21991 21992 21993 21994 21995 21996 21997 21998 21999 22000 22001 22002 22003 22004 22005 22006 22007 22008 22009 22010 22011 22012 22013 22014 22015 22016 22017 22018 22019 22020 22021 22022 22023 22024 22025 22026 22027 22028 22029 22030 22031 22032 22033 22034 22035 22036 22037 22038 22039 22040 22041 22042 22043 22044 22045 22046 22047 22048 22049 22050 22051 22052 22053 22054 22055 22056 22057 22058 22059 22060 22061 22062 22063 22064 22065 22066 22067 22068 22069 22070 22071 22072 22073 22074 22075 22076 22077 22078 22079 22080 22081 22082 22083 22084 22085 22086 22087 22088 22089 22090 22091 22092 22093 22094 22095 22096 22097 22098 22099 22100 22101 22102 22103 22104 22105 22106 22107 22108 22109 22110 22111 22112 22113 22114 22115 22116 22117 22118 22119 22120 22121 22122 22123 22124 22125 22126 22127 22128 22129 22130 22131 22132 22133 22134 22135 22136 22137 22138 22139 22140 22141 22142 22143 22144 22145 22146 22147 22148 22149 22150 22151 22152 22153 22154 22155 22156 22157 22158 22159 22160 22161 22162 22163 22164 22165 22166 22167 22168 22169 22170 22171 22172 22173 22174 22175 22176 22177 22178 22179 22180 22181 22182 22183 22184 22185 22186 22187 22188 22189 22190 22191 22192 22193 22194 22195 22196 22197 22198 22199 22200 22201 22202 22203 22204 22205 22206 22207 22208 22209 22210 22211 22212 22213 22214 22215 22216 22217 22218 22219 22220 22221 22222 22223 22224 22225 22226 22227 22228 22229 22230 22231 22232 22233 22234 22235 22236 22237 22238 22239 22240 22241 22242 22243 22244 22245 22246 22247 22248 22249 22250 22251 22252 22253 22254 22255 22256 22257 22258 22259 22260 22261 22262 22263 22264 22265 22266 22267 22268 22269 22270 22271 22272 22273 22274 22275 22276 22277 22278 22279 22280 22281 22282 22283 22284 22285 22286 22287 22288 22289 22290 22291 22292 22293 22294 22295 22296 22297 22298 22299 22300 22301 22302 22303 22304 22305 22306 22307 22308 22309 22310 22311 22312 22313 22314 22315 22316 22317 22318 22319 22320 22321 22322 22323 22324 22325 22326 22327 22328 22329 22330 22331 22332 22333 22334 22335 22336 22337 22338 22339 22340 22341 22342 22343 22344 22345 22346 22347 22348 22349 22350 22351 22352 22353 22354 22355 22356 22357 22358 22359 22360 22361 22362 22363 22364 22365 22366 22367 22368 22369 22370 22371 22372 22373 22374 22375 22376 22377 22378 22379 22380 22381 22382 22383 22384 22385 22386 22387 22388 22389 22390 22391 22392 22393 22394 22395 22396 22397 22398 22399 22400 22401 22402 22403 22404 22405 22406 22407 22408 22409 22410 22411 22412 22413 22414 22415 22416 22417 22418 22419 22420 22421 22422 22423 22424 22425 22426 22427 22428 22429 22430 22431 22432 22433 22434 22435 22436 22437 22438 22439 22440 22441 22442 22443 22444 22445 22446 22447 22448 22449 22450 22451 22452 22453 22454 22455 22456 22457 22458 22459 22460 22461 22462 22463 22464 22465 22466 22467 22468 22469 22470 22471 22472 22473 22474 22475 22476 22477 22478 22479 22480 22481 22482 22483 22484 22485 22486 22487 22488 22489 22490 22491 22492 22493 22494 22495 22496 22497 22498 22499 22500 22501 22502 22503 22504 22505 22506 22507 22508 22509 22510 22511 22512 22513 22514 22515 22516 22517 22518 22519 22520 22521 22522 22523 22524 22525 22526 22527 22528 22529 22530 22531 22532 22533 22534 22535 22536 22537 22538 22539 22540 22541 22542 22543 22544 22545 22546 22547 22548 22549 22550 22551 22552 22553 22554 22555 22556 22557 22558 22559 22560 22561 22562 22563 22564 22565 22566 22567 22568 22569 22570 22571 22572 22573 22574 22575 22576 22577 22578 22579 22580 22581 22582 22583 22584 22585 22586 22587 22588 22589 22590 22591 22592 22593 22594 22595 22596 22597 22598 22599 22600 22601 22602 22603 22604 22605 22606 22607 22608 22609 22610 22611 22612 22613 22614 22615 22616 22617 22618 22619 22620 22621 22622 22623 22624 22625 22626 22627 22628 22629 22630 22631 22632 22633 22634 22635 22636 22637 22638 22639 22640 22641 22642 22643 22644 22645 22646 22647 22648 22649 22650 22651 22652 22653 22654 22655 22656 22657 22658 22659 22660 22661 22662 22663 22664 22665 22666 22667 22668 22669 22670 22671 22672 22673 22674 22675 22676 22677 22678 22679 22680 22681 22682 22683 22684 22685 22686 22687 22688 22689 22690 22691 22692 22693 22694 22695 22696 22697 22698 22699 22700 22701 22702 22703 22704 22705 22706 22707 22708 22709 22710 22711 22712 22713 22714 22715 22716 22717 22718 22719 22720 22721 22722 22723 22724 22725 22726 22727 22728 22729 22730 22731 22732 22733 22734 22735 22736 22737 22738 22739 22740 22741 22742 22743 22744 22745 22746 22747 22748 22749 22750 22751 22752 22753 22754 22755 22756 22757 22758 22759 22760 22761 22762 22763 22764 22765 22766 22767 22768 22769 22770 22771 22772 22773 22774 22775 22776 22777 22778 22779 22780 22781 22782 22783 22784 22785 22786 22787 22788 22789 22790 22791 22792 22793 22794 22795 22796 22797 22798 22799 22800 22801 22802 22803 22804 22805 22806 22807 22808 22809 22810 22811 22812 22813 22814 22815 22816 22817 22818 22819 22820 22821 22822 22823 22824 22825 22826 22827 22828 22829 22830 22831 22832 22833 22834 22835 22836 22837 22838 22839 22840 22841 22842 22843 22844 22845 22846 22847 22848 22849 22850 22851 22852 22853 22854 22855 22856 22857 22858 22859 22860 22861 22862 22863 22864 22865 22866 22867 22868 22869 22870 22871 22872 22873 22874 22875 22876 22877 22878 22879 22880 22881 22882 22883 22884 22885 22886 22887 22888 22889 22890 22891 22892 22893 22894 22895 22896 22897 22898 22899 22900 22901 22902 22903 22904 22905 22906 22907 22908 22909 22910 22911 22912 22913 22914 22915 22916 22917 22918 22919 22920 22921 22922 22923 22924 22925 22926 22927 22928 22929 22930 22931 22932 22933 22934 22935 22936 22937 22938 22939 22940 22941 22942 22943 22944 22945 22946 22947 22948 22949 22950 22951 22952 22953 22954 22955 22956 22957 22958 22959 22960 22961 22962 22963 22964 22965 22966 22967 22968 22969 22970 22971 22972 22973 22974 22975 22976 22977 22978 22979 22980 22981 22982 22983 22984 22985 22986 22987 22988 22989 22990 22991 22992 22993 22994 22995 22996 22997 22998 22999 23000 23001 23002 23003 23004 23005 23006 23007 23008 23009 23010 23011 23012 23013 23014 23015 23016 23017 23018 23019 23020 23021 23022 23023 23024 23025 23026 23027 23028 23029 23030 23031 23032 23033 23034 23035 23036 23037 23038 23039 23040 23041 23042 23043 23044 23045 23046 23047 23048 23049 23050 23051 23052 23053 23054 23055 23056 23057 23058 23059 23060 23061 23062 23063 23064 23065 23066 23067 23068 23069 23070 23071 23072 23073 23074 23075 23076 23077 23078 23079 23080 23081 23082 23083 23084 23085 23086 23087 23088 23089 23090 23091 23092 23093 23094 23095 23096 23097 23098 23099 23100 23101 23102 23103 23104 23105 23106 23107 23108 23109 23110 23111 23112 23113 23114 23115 23116 23117 23118 23119 23120 23121 23122 23123 23124 23125 23126 23127 23128 23129 23130 23131 23132 23133 23134 23135 23136 23137 23138 23139 23140 23141 23142 23143 23144 23145 23146 23147 23148 23149 23150 23151 23152 23153 23154 23155 23156 23157 23158 23159 23160 23161 23162 23163 23164 23165 23166 23167 23168 23169 23170 23171 23172 23173 23174 23175 23176 23177 23178 23179 23180 23181 23182 23183 23184 23185 23186 23187 23188 23189 23190 23191 23192 23193 23194 23195 23196 23197 23198 23199 23200 23201 23202 23203 23204 23205 23206 23207 23208 23209 23210 23211 23212 23213 23214 23215 23216 23217 23218 23219 23220 23221 23222 23223 23224 23225 23226 23227 23228 23229 23230 23231 23232 23233 23234 23235 23236 23237 23238 23239 23240 23241 23242 23243 23244 23245 23246 23247 23248 23249 23250 23251 23252 23253 23254 23255 23256 23257 23258 23259 23260 23261 23262 23263 23264 23265 23266 23267 23268 23269 23270 23271 23272 23273 23274 23275 23276 23277 23278 23279 23280 23281 23282 23283 23284 23285 23286 23287 23288 23289 23290 23291 23292 23293 23294 23295 23296 23297 23298 23299 23300 23301 23302 23303 23304 23305 23306 23307 23308 23309 23310 23311 23312 23313 23314 23315 23316 23317 23318 23319 23320 23321 23322 23323 23324 23325 23326 23327 23328 23329 23330 23331 23332 23333 23334 23335 23336 23337 23338 23339 23340 23341 23342 23343 23344 23345 23346 23347 23348 23349 23350 23351 23352 23353 23354 23355 23356 23357 23358 23359 23360 23361 23362 23363 23364 23365 23366 23367 23368 23369 23370 23371 23372 23373 23374 23375 23376 23377 23378 23379 23380 23381 23382 23383 23384 23385 23386 23387 23388 23389 23390 23391 23392 23393 23394 23395 23396 23397 23398 23399 23400 23401 23402 23403 23404 23405 23406 23407 23408 23409 23410 23411 23412 23413 23414 23415 23416 23417 23418 23419 23420 23421 23422 23423 23424 23425 23426 23427 23428 23429 23430 23431 23432 23433 23434 23435 23436 23437 23438 23439 23440 23441 23442 23443 23444 23445 23446 23447 23448 23449 23450 23451 23452 23453 23454 23455 23456 23457 23458 23459 23460 23461 23462 23463 23464 23465 23466 23467 23468 23469 23470 23471 23472 23473 23474 23475 23476 23477 23478 23479 23480 23481 23482 23483 23484 23485 23486 23487 23488 23489 23490 23491 23492 23493 23494 23495 23496 23497 23498 23499 23500 23501 23502 23503 23504 23505 23506 23507 23508 23509 23510 23511 23512 23513 23514 23515 23516 23517 23518 23519 23520 23521 23522 23523 23524 23525 23526 23527 23528 23529 23530 23531 23532 23533 23534 23535 23536 23537 23538 23539 23540 23541 23542 23543 23544 23545 23546 23547 23548 23549 23550 23551 23552 23553 23554 23555 23556 23557 23558 23559 23560 23561 23562 23563 23564 23565 23566 23567 23568 23569 23570 23571 23572 23573 23574 23575 23576 23577 23578 23579 23580 23581 23582 23583 23584 23585 23586 23587 23588 23589 23590 23591 23592 23593 23594 23595 23596 23597 23598 23599 23600 23601 23602 23603 23604 23605 23606 23607 23608 23609 23610 23611 23612 23613 23614 23615 23616 23617 23618 23619 23620 23621 23622 23623 23624 23625 23626 23627 23628 23629 23630 23631 23632 23633 23634 23635 23636 23637 23638 23639 23640 23641 23642 23643 23644 23645 23646 23647 23648 23649 23650 23651 23652 23653 23654 23655 23656 23657 23658 23659 23660 23661 23662 23663 23664 23665 23666 23667 23668 23669 23670 23671 23672 23673 23674 23675 23676 23677 23678 23679 23680 23681 23682 23683 23684 23685 23686 23687 23688 23689 23690 23691 23692 23693 23694 23695 23696 23697 23698 23699 23700 23701 23702 23703 23704 23705 23706 23707 23708 23709 23710 23711 23712 23713 23714 23715 23716 23717 23718 23719 23720 23721 23722 23723 23724 23725 23726 23727 23728 23729 23730 23731 23732 23733 23734 23735 23736 23737 23738 23739 23740 23741 23742 23743 23744 23745 23746 23747 23748 23749 23750 23751 23752 23753 23754 23755 23756 23757 23758 23759 23760 23761 23762 23763 23764 23765 23766 23767 23768 23769 23770 23771 23772 23773 23774 23775 23776 23777 23778 23779 23780 23781 23782 23783 23784 23785 23786 23787 23788 23789 23790 23791 23792 23793 23794 23795 23796 23797 23798 23799 23800 23801 23802 23803 23804 23805 23806 23807 23808 23809 23810 23811 23812 23813 23814 23815 23816 23817 23818 23819 23820 23821 23822 23823 23824 23825 23826 23827 23828 23829 23830 23831 23832 23833 23834 23835 23836 23837 23838 23839 23840 23841 23842 23843 23844 23845 23846 23847 23848 23849 23850 23851 23852 23853 23854 23855 23856 23857 23858 23859 23860 23861 23862 23863 23864 23865 23866 23867 23868 23869 23870 23871 23872 23873 23874 23875 23876 23877 23878 23879 23880 23881 23882 23883 23884 23885 23886 23887 23888 23889 23890 23891 23892 23893 23894 23895 23896 23897 23898 23899 23900 23901 23902 23903 23904 23905 23906 23907 23908 23909 23910 23911 23912 23913 23914 23915 23916 23917 23918 23919 23920 23921 23922 23923 23924 23925 23926 23927 23928 23929 23930 23931 23932 23933 23934 23935 23936 23937 23938 23939 23940 23941 23942 23943 23944 23945 23946 23947 23948 23949 23950 23951 23952 23953 23954 23955 23956 23957 23958 23959 23960 23961 23962 23963 23964 23965 23966 23967 23968 23969 23970 23971 23972 23973 23974 23975 23976 23977 23978 23979 23980 23981 23982 23983 23984 23985 23986 23987 23988 23989 23990 23991 23992 23993 23994 23995 23996 23997 23998 23999 24000 24001 24002 24003 24004 24005 24006 24007 24008 24009 24010 24011 24012 24013 24014 24015 24016 24017 24018 24019 24020 24021 24022 24023 24024 24025 24026 24027 24028 24029 24030 24031 24032 24033 24034 24035 24036 24037 24038 24039 24040 24041 24042 24043 24044 24045 24046 24047 24048 24049 24050 24051 24052 24053 24054 24055 24056 24057 24058 24059 24060 24061 24062 24063 24064 24065 24066 24067 24068 24069 24070 24071 24072 24073 24074 24075 24076 24077 24078 24079 24080 24081 24082 24083 24084 24085 24086 24087 24088 24089 24090 24091 24092 24093 24094 24095 24096 24097 24098 24099 24100 24101 24102 24103 24104 24105 24106 24107 24108 24109 24110 24111 24112 24113 24114 24115 24116 24117 24118 24119 24120 24121 24122 24123 24124 24125 24126 24127 24128 24129 24130 24131 24132 24133 24134 24135 24136 24137 24138 24139 24140 24141 24142 24143 24144 24145 24146 24147 24148 24149 24150 24151 24152 24153 24154 24155 24156 24157 24158 24159 24160 24161 24162 24163 24164 24165 24166 24167 24168 24169 24170 24171 24172 24173 24174 24175 24176 24177 24178 24179 24180 24181 24182 24183 24184 24185 24186 24187 24188 24189 24190 24191 24192 24193 24194 24195 24196 24197 24198 24199 24200 24201 24202 24203 24204 24205 24206 24207 24208 24209 24210 24211 24212 24213 24214 24215 24216 24217 24218 24219 24220 24221 24222 24223 24224 24225 24226 24227 24228 24229 24230 24231 24232 24233 24234 24235 24236 24237 24238 24239 24240 24241 24242 24243 24244 24245 24246 24247 24248 24249 24250 24251 24252 24253 24254 24255 24256 24257 24258 24259 24260 24261 24262 24263 24264 24265 24266 24267 24268 24269 24270 24271 24272 24273 24274 24275 24276 24277 24278 24279 24280 24281 24282 24283 24284 24285 24286 24287 24288 24289 24290 24291 24292 24293 24294 24295 24296 24297 24298 24299 24300 24301 24302 24303 24304 24305 24306 24307 24308 24309 24310 24311 24312 24313 24314 24315 24316 24317 24318 24319 24320 24321 24322 24323 24324 24325 24326 24327 24328 24329 24330 24331 24332 24333 24334 24335 24336 24337 24338 24339 24340 24341 24342 24343 24344 24345 24346 24347 24348 24349 24350 24351 24352 24353 24354 24355 24356 24357 24358 24359 24360 24361 24362 24363 24364 24365 24366 24367 24368 24369 24370 24371 24372 24373 24374 24375 24376 24377 24378 24379 24380 24381 24382 24383 24384 24385 24386 24387 24388 24389 24390 24391 24392 24393 24394 24395 24396 24397 24398 24399 24400 24401 24402 24403 24404 24405 24406 24407 24408 24409 24410 24411 24412 24413 24414 24415 24416 24417 24418 24419 24420 24421 24422 24423 24424 24425 24426 24427 24428 24429 24430 24431 24432 24433 24434 24435 24436 24437 24438 24439 24440 24441 24442 24443 24444 24445 24446 24447 24448 24449 24450 24451 24452 24453 24454 24455 24456 24457 24458 24459 24460 24461 24462 24463 24464 24465 24466 24467 24468 24469 24470 24471 24472 24473 24474 24475 24476 24477 24478 24479 24480 24481 24482 24483 24484 24485 24486 24487 24488 24489 24490 24491 24492 24493 24494 24495 24496 24497 24498 24499 24500 24501 24502 24503 24504 24505 24506 24507 24508 24509 24510 24511 24512 24513 24514 24515 24516 24517 24518 24519 24520 24521 24522 24523 24524 24525 24526 24527 24528 24529 24530 24531 24532 24533 24534 24535 24536 24537 24538 24539 24540 24541 24542 24543 24544 24545 24546 24547 24548 24549 24550 24551 24552 24553 24554 24555 24556 24557 24558 24559 24560 24561 24562 24563 24564 24565 24566 24567 24568 24569 24570 24571 24572 24573 24574 24575 24576 24577 24578 24579 24580 24581 24582 24583 24584 24585 24586 24587 24588 24589 24590 24591 24592 24593 24594 24595 24596 24597 24598 24599 24600 24601 24602 24603 24604 24605 24606 24607 24608 24609 24610 24611 24612 24613 24614 24615 24616 24617 24618 24619 24620 24621 24622 24623 24624 24625 24626 24627 24628 24629 24630 24631 24632 24633 24634 24635 24636 24637 24638 24639 24640 24641 24642 24643 24644 24645 24646 24647 24648 24649 24650 24651 24652 24653 24654 24655 24656 24657 24658 24659 24660 24661 24662 24663 24664 24665 24666 24667 24668 24669 24670 24671 24672 24673 24674 24675 24676 24677 24678 24679 24680 24681 24682 24683 24684 24685 24686 24687 24688 24689 24690 24691 24692 24693 24694 24695 24696 24697 24698 24699 24700 24701 24702 24703 24704 24705 24706 24707 24708 24709 24710 24711 24712 24713 24714 24715 24716 24717 24718 24719 24720 24721 24722 24723 24724 24725 24726 24727 24728 24729 24730 24731 24732 24733 24734 24735 24736 24737 24738 24739 24740 24741 24742 24743 24744 24745 24746 24747 24748 24749 24750 24751 24752 24753 24754 24755 24756 24757 24758 24759 24760 24761 24762 24763 24764 24765 24766 24767 24768 24769 24770 24771 24772 24773 24774 24775 24776 24777 24778 24779 24780 24781 24782 24783 24784 24785 24786 24787 24788 24789 24790 24791 24792 24793 24794 24795 24796 24797 24798 24799 24800 24801 24802 24803 24804 24805 24806 24807 24808 24809 24810 24811 24812 24813 24814 24815 24816 24817 24818 24819 24820 24821 24822 24823 24824 24825 24826 24827 24828 24829 24830 24831 24832 24833 24834 24835 24836 24837 24838 24839 24840 24841 24842 24843 24844 24845 24846 24847 24848 24849 24850 24851 24852 24853 24854 24855 24856 24857 24858 24859 24860 24861 24862 24863 24864 24865 24866 24867 24868 24869 24870 24871 24872 24873 24874 24875 24876 24877 24878 24879 24880 24881 24882 24883 24884 24885 24886 24887 24888 24889 24890 24891 24892 24893 24894 24895 24896 24897 24898 24899 24900 24901 24902 24903 24904 24905 24906 24907 24908 24909 24910 24911 24912 24913 24914 24915 24916 24917 24918 24919 24920 24921 24922 24923 24924 24925 24926 24927 24928 24929 24930 24931 24932 24933 24934 24935 24936 24937 24938 24939 24940 24941 24942 24943 24944 24945 24946 24947 24948 24949 24950 24951 24952 24953 24954 24955 24956 24957 24958 24959 24960 24961 24962 24963 24964 24965 24966 24967 24968 24969 24970 24971 24972 24973 24974 24975 24976 24977 24978 24979 24980 24981 24982 24983 24984 24985 24986 24987 24988 24989 24990 24991 24992 24993 24994 24995 24996 24997 24998 24999 25000 25001 25002 25003 25004 25005 25006 25007 25008 25009 25010 25011 25012 25013 25014 25015 25016 25017 25018 25019 25020 25021 25022 25023 25024 25025 25026 25027 25028 25029 25030 25031 25032 25033 25034 25035 25036 25037 25038 25039 25040 25041 25042 25043 25044 25045 25046 25047 25048 25049 25050 25051 25052 25053 25054 25055 25056 25057 25058 25059 25060 25061 25062 25063 25064 25065 25066 25067 25068 25069 25070 25071 25072 25073 25074 25075 25076 25077 25078 25079 25080 25081 25082 25083 25084 25085 25086 25087 25088 25089 25090 25091 25092 25093 25094 25095 25096 25097 25098 25099 25100 25101 25102 25103 25104 25105 25106 25107 25108 25109 25110 25111 25112 25113 25114 25115 25116 25117 25118 25119 25120 25121 25122 25123 25124 25125 25126 25127 25128 25129 25130 25131 25132 25133 25134 25135 25136 25137 25138 25139 25140 25141 25142 25143 25144 25145 25146 25147 25148 25149 25150 25151 25152 25153 25154 25155 25156 25157 25158 25159 25160 25161 25162 25163 25164 25165 25166 25167 25168 25169 25170 25171 25172 25173 25174 25175 25176 25177 25178 25179 25180 25181 25182 25183 25184 25185 25186 25187 25188 25189 25190 25191 25192 25193 25194 25195 25196 25197 25198 25199 25200 25201 25202 25203 25204 25205 25206 25207 25208 25209 25210 25211 25212 25213 25214 25215 25216 25217 25218 25219 25220 25221 25222 25223 25224 25225 25226 25227 25228 25229 25230 25231 25232 25233 25234 25235 25236 25237 25238 25239 25240 25241 25242 25243 25244 25245 25246 25247 25248 25249 25250 25251 25252 25253 25254 25255 25256 25257 25258 25259 25260 25261 25262 25263 25264 25265 25266 25267 25268 25269 25270 25271 25272 25273 25274 25275 25276 25277 25278 25279 25280 25281 25282 25283 25284 25285 25286 25287 25288 25289 25290 25291 25292 25293 25294 25295 25296 25297 25298 25299 25300 25301 25302 25303 25304 25305 25306 25307 25308 25309 25310 25311 25312 25313 25314 25315 25316 25317 25318 25319 25320 25321 25322 25323 25324 25325 25326 25327 25328 25329 25330 25331 25332 25333 25334 25335 25336 25337 25338 25339 25340 25341 25342 25343 25344 25345 25346 25347 25348 25349 25350 25351 25352 25353 25354 25355 25356 25357 25358 25359 25360 25361 25362 25363 25364 25365 25366 25367 25368 25369 25370 25371 25372 25373 25374 25375 25376 25377 25378 25379 25380 25381 25382 25383 25384 25385 25386 25387 25388 25389 25390 25391 25392 25393 25394 25395 25396 25397 25398 25399 25400 25401 25402 25403 25404 25405 25406 25407 25408 25409 25410 25411 25412 25413 25414 25415 25416 25417 25418 25419 25420 25421 25422 25423 25424 25425 25426 25427 25428 25429 25430 25431 25432 25433 25434 25435 25436 25437 25438 25439 25440 25441 25442 25443 25444 25445 25446 25447 25448 25449 25450 25451 25452 25453 25454 25455 25456 25457 25458 25459 25460 25461 25462 25463 25464 25465 25466 25467 25468 25469 25470 25471 25472 25473 25474 25475 25476 25477 25478 25479 25480 25481 25482 25483 25484 25485 25486 25487 25488 25489 25490 25491 25492 25493 25494 25495 25496 25497 25498 25499 25500 25501 25502 25503 25504 25505 25506 25507 25508 25509 25510 25511 25512 25513 25514 25515 25516 25517 25518 25519 25520 25521 25522 25523 25524 25525 25526 25527 25528 25529 25530 25531 25532 25533 25534 25535 25536 25537 25538 25539 25540 25541 25542 25543 25544 25545 25546 25547 25548 25549 25550 25551 25552 25553 25554 25555 25556 25557 25558 25559 25560 25561 25562 25563 25564 25565 25566 25567 25568 25569 25570 25571 25572 25573 25574 25575 25576 25577 25578 25579 25580 25581 25582 25583 25584 25585 25586 25587 25588 25589 25590 25591 25592 25593 25594 25595 25596 25597 25598 25599 25600 25601 25602 25603 25604 25605 25606 25607 25608 25609 25610 25611 25612 25613 25614 25615 25616 25617 25618 25619 25620 25621 25622 25623 25624 25625 25626 25627 25628 25629 25630 25631 25632 25633 25634 25635 25636 25637 25638 25639 25640 25641 25642 25643 25644 25645 25646 25647 25648 25649 25650 25651 25652 25653 25654 25655 25656 25657 25658 25659 25660 25661 25662 25663 25664 25665 25666 25667 25668 25669 25670 25671 25672 25673 25674 25675 25676 25677 25678 25679 25680 25681 25682 25683 25684 25685 25686 25687 25688 25689 25690 25691 25692 25693 25694 25695 25696 25697 25698 25699 25700 25701 25702 25703 25704 25705 25706 25707 25708 25709 25710 25711 25712 25713 25714 25715 25716 25717 25718 25719 25720 25721 25722 25723 25724 25725 25726 25727 25728 25729 25730 25731 25732 25733 25734 25735 25736 25737 25738 25739 25740 25741 25742 25743 25744 25745 25746 25747 25748 25749 25750 25751 25752 25753 25754 25755 25756 25757 25758 25759 25760 25761 25762 25763 25764 25765 25766 25767 25768 25769 25770 25771 25772 25773 25774 25775 25776 25777 25778 25779 25780 25781 25782 25783 25784 25785 25786 25787 25788 25789 25790 25791 25792 25793 25794 25795 25796 25797 25798 25799 25800 25801 25802 25803 25804 25805 25806 25807 25808 25809 25810 25811 25812 25813 25814 25815 25816 25817 25818 25819 25820 25821 25822 25823 25824 25825 25826 25827 25828 25829 25830 25831 25832 25833 25834 25835 25836 25837 25838 25839 25840 25841 25842 25843 25844 25845 25846 25847 25848 25849 25850 25851 25852 25853 25854 25855 25856 25857 25858 25859 25860 25861 25862 25863 25864 25865 25866 25867 25868 25869 25870 25871 25872 25873 25874 25875 25876 25877 25878 25879 25880 25881 25882 25883 25884 25885 25886 25887 25888 25889 25890 25891 25892 25893 25894 25895 25896 25897 25898 25899 25900 25901 25902 25903 25904 25905 25906 25907 25908 25909 25910 25911 25912 25913 25914 25915 25916 25917 25918 25919 25920 25921 25922 25923 25924 25925 25926 25927 25928 25929 25930 25931 25932 25933 25934 25935 25936 25937 25938 25939 25940 25941 25942 25943 25944 25945 25946 25947 25948 25949 25950 25951 25952 25953 25954 25955 25956 25957 25958 25959 25960 25961 25962 25963 25964 25965 25966 25967 25968 25969 25970 25971 25972 25973 25974 25975 25976 25977 25978 25979 25980 25981 25982 25983 25984 25985 25986 25987 25988 25989 25990 25991 25992 25993 25994 25995 25996 25997 25998 25999 26000 26001 26002 26003 26004 26005 26006 26007 26008 26009 26010 26011 26012 26013 26014 26015 26016 26017 26018 26019 26020 26021 26022 26023 26024 26025 26026 26027 26028 26029 26030 26031 26032 26033 26034 26035 26036 26037 26038 26039 26040 26041 26042 26043 26044 26045 26046 26047 26048 26049 26050 26051 26052 26053 26054 26055 26056 26057 26058 26059 26060 26061 26062 26063 26064 26065 26066 26067 26068 26069 26070 26071 26072 26073 26074 26075 26076 26077 26078 26079 26080 26081 26082 26083 26084 26085 26086 26087 26088 26089 26090 26091 26092 26093 26094 26095 26096 26097 26098 26099 26100 26101 26102 26103 26104 26105 26106 26107 26108 26109 26110 26111 26112 26113 26114 26115 26116 26117 26118 26119 26120 26121 26122 26123 26124 26125 26126 26127 26128 26129 26130 26131 26132 26133 26134 26135 26136 26137 26138 26139 26140 26141 26142 26143 26144 26145 26146 26147 26148 26149 26150 26151 26152 26153 26154 26155 26156 26157 26158 26159 26160 26161 26162 26163 26164 26165 26166 26167 26168 26169 26170 26171 26172 26173 26174 26175 26176 26177 26178 26179 26180 26181 26182 26183 26184 26185 26186 26187 26188 26189 26190 26191 26192 26193 26194 26195 26196 26197 26198 26199 26200 26201 26202 26203 26204 26205 26206 26207 26208 26209 26210 26211 26212 26213 26214 26215 26216 26217 26218 26219 26220 26221 26222 26223 26224 26225 26226 26227 26228 26229 26230 26231 26232 26233 26234 26235 26236 26237 26238 26239 26240 26241 26242 26243 26244 26245 26246 26247 26248 26249 26250 26251 26252 26253 26254 26255 26256 26257 26258 26259 26260 26261 26262 26263 26264 26265 26266 26267 26268 26269 26270 26271 26272 26273 26274 26275 26276 26277 26278 26279 26280 26281 26282 26283 26284 26285 26286 26287 26288 26289 26290 26291 26292 26293 26294 26295 26296 26297 26298 26299 26300 26301 26302 26303 26304 26305 26306 26307 26308 26309 26310 26311 26312 26313 26314 26315 26316 26317 26318 26319 26320 26321 26322 26323 26324 26325 26326 26327 26328 26329 26330 26331 26332 26333 26334 26335 26336 26337 26338 26339 26340 26341 26342 26343 26344 26345 26346 26347 26348 26349 26350 26351 26352 26353 26354 26355 26356 26357 26358 26359 26360 26361 26362 26363 26364 26365 26366 26367 26368 26369 26370 26371 26372 26373 26374 26375 26376 26377 26378 26379 26380 26381 26382 26383 26384 26385 26386 26387 26388 26389 26390 26391 26392 26393 26394 26395 26396 26397 26398 26399 26400 26401 26402 26403 26404 26405 26406 26407 26408 26409 26410 26411 26412 26413 26414 26415 26416 26417 26418 26419 26420 26421 26422 26423 26424 26425 26426 26427 26428 26429 26430 26431 26432 26433 26434 26435 26436 26437 26438 26439 26440 26441 26442 26443 26444 26445 26446 26447 26448 26449 26450 26451 26452 26453 26454 26455 26456 26457 26458 26459 26460 26461 26462 26463 26464 26465 26466 26467 26468 26469 26470 26471 26472 26473 26474 26475 26476 26477 26478 26479 26480 26481 26482 26483 26484 26485 26486 26487 26488 26489 26490 26491 26492 26493 26494 26495 26496 26497 26498 26499 26500 26501 26502 26503 26504 26505 26506 26507 26508 26509 26510 26511 26512 26513 26514 26515 26516 26517 26518 26519 26520 26521 26522 26523 26524 26525 26526 26527 26528 26529 26530 26531 26532 26533 26534 26535 26536 26537 26538 26539 26540 26541 26542 26543 26544 26545 26546 26547 26548 26549 26550 26551 26552 26553 26554 26555 26556 26557 26558 26559 26560 26561 26562 26563 26564 26565 26566 26567 26568 26569 26570 26571 26572 26573 26574 26575 26576 26577 26578 26579 26580 26581 26582 26583 26584 26585 26586 26587 26588 26589 26590 26591 26592 26593 26594 26595 26596 26597 26598 26599 26600 26601 26602 26603 26604 26605 26606 26607 26608 26609 26610 26611 26612 26613 26614 26615 26616 26617 26618 26619 26620 26621 26622 26623 26624 26625 26626 26627 26628 26629 26630 26631 26632 26633 26634 26635 26636 26637 26638 26639 26640 26641 26642 26643 26644 26645 26646 26647 26648 26649 26650 26651 26652 26653 26654 26655 26656 26657 26658 26659 26660 26661 26662 26663 26664 26665 26666 26667 26668 26669 26670 26671 26672 26673 26674 26675 26676 26677 26678 26679 26680 26681 26682 26683 26684 26685 26686 26687 26688 26689 26690 26691 26692 26693 26694 26695 26696 26697 26698 26699 26700 26701 26702 26703 26704 26705 26706 26707 26708 26709 26710 26711 26712 26713 26714 26715 26716 26717 26718 26719 26720 26721 26722 26723 26724 26725 26726 26727 26728 26729 26730 26731 26732 26733 26734 26735 26736 26737 26738 26739 26740 26741 26742 26743 26744 26745 26746 26747 26748 26749 26750 26751 26752 26753 26754 26755 26756 26757 26758 26759 26760 26761 26762 26763 26764 26765 26766 26767 26768 26769 26770 26771 26772 26773 26774 26775 26776 26777 26778 26779 26780 26781 26782 26783 26784 26785 26786 26787 26788 26789 26790 26791 26792 26793 26794 26795 26796 26797 26798 26799 26800 26801 26802 26803 26804 26805 26806 26807 26808 26809 26810 26811 26812 26813 26814 26815 26816 26817 26818 26819 26820 26821 26822 26823 26824 26825 26826 26827 26828 26829 26830 26831 26832 26833 26834 26835 26836 26837 26838 26839 26840 26841 26842 26843 26844 26845 26846 26847 26848 26849 26850 26851 26852 26853 26854 26855 26856 26857 26858 26859 26860 26861 26862 26863 26864 26865 26866 26867 26868 26869 26870 26871 26872 26873 26874 26875 26876 26877 26878 26879 26880 26881 26882 26883 26884 26885 26886 26887 26888 26889 26890 26891 26892 26893 26894 26895 26896 26897 26898 26899 26900 26901 26902 26903 26904 26905 26906 26907 26908 26909 26910 26911 26912 26913 26914 26915 26916 26917 26918 26919 26920 26921 26922 26923 26924 26925 26926 26927 26928 26929 26930 26931 26932 26933 26934 26935 26936 26937 26938 26939 26940 26941 26942 26943 26944 26945 26946 26947 26948 26949 26950 26951 26952 26953 26954 26955 26956 26957 26958 26959 26960 26961 26962 26963 26964 26965 26966 26967 26968 26969 26970 26971 26972 26973 26974 26975 26976 26977 26978 26979 26980 26981 26982 26983 26984 26985 26986 26987 26988 26989 26990 26991 26992 26993 26994 26995 26996 26997 26998 26999 27000 27001 27002 27003 27004 27005 27006 27007 27008 27009 27010 27011 27012 27013 27014 27015 27016 27017 27018 27019 27020 27021 27022 27023 27024 27025 27026 27027 27028 27029 27030 27031 27032 27033 27034 27035 27036 27037 27038 27039 27040 27041 27042 27043 27044 27045 27046 27047 27048 27049 27050 27051 27052 27053 27054 27055 27056 27057 27058 27059 27060 27061 27062 27063 27064 27065 27066 27067 27068 27069 27070 27071 27072 27073 27074 27075 27076 27077 27078 27079 27080 27081 27082 27083 27084 27085 27086 27087 27088 27089 27090 27091 27092 27093 27094 27095 27096 27097 27098 27099 27100 27101 27102 27103 27104 27105 27106 27107 27108 27109 27110 27111 27112 27113 27114 27115 27116 27117 27118 27119 27120 27121 27122 27123 27124 27125 27126 27127 27128 27129 27130 27131 27132 27133 27134 27135 27136 27137 27138 27139 27140 27141 27142 27143 27144 27145 27146 27147 27148 27149 27150 27151 27152 27153 27154 27155 27156 27157 27158 27159 27160 27161 27162 27163 27164 27165 27166 27167 27168 27169 27170 27171 27172 27173 27174 27175 27176 27177 27178 27179 27180 27181 27182 27183 27184 27185 27186 27187 27188 27189 27190 27191 27192 27193 27194 27195 27196 27197 27198 27199 27200 27201 27202 27203 27204 27205 27206 27207 27208 27209 27210 27211 27212 27213 27214 27215 27216 27217 27218 27219 27220 27221 27222 27223 27224 27225 27226 27227 27228 27229 27230 27231 27232 27233 27234 27235 27236 27237 27238 27239 27240 27241 27242 27243 27244 27245 27246 27247 27248 27249 27250 27251 27252 27253 27254 27255 27256 27257 27258 27259 27260 27261 27262 27263 27264 27265 27266 27267 27268 27269 27270 27271 27272 27273 27274 27275 27276 27277 27278 27279 27280 27281 27282 27283 27284 27285 27286 27287 27288 27289 27290 27291 27292 27293 27294 27295 27296 27297 27298 27299 27300 27301 27302 27303 27304 27305 27306 27307 27308 27309 27310 27311 27312 27313 27314 27315 27316 27317 27318 27319 27320 27321 27322 27323 27324 27325 27326 27327 27328 27329 27330 27331 27332 27333 27334 27335 27336 27337 27338 27339 27340 27341 27342 27343 27344 27345 27346 27347 27348 27349 27350 27351 27352 27353 27354 27355 27356 27357 27358 27359 27360 27361 27362 27363 27364 27365 27366 27367 27368 27369 27370 27371 27372 27373 27374 27375 27376 27377 27378 27379 27380 27381 27382 27383 27384 27385 27386 27387 27388 27389 27390 27391 27392 27393 27394 27395 27396 27397 27398 27399 27400 27401 27402 27403 27404 27405 27406 27407 27408 27409 27410 27411 27412 27413 27414 27415 27416 27417 27418 27419 27420 27421 27422 27423 27424 27425 27426 27427 27428 27429 27430 27431 27432 27433 27434 27435 27436 27437 27438 27439 27440 27441 27442 27443 27444 27445 27446 27447 27448 27449 27450 27451 27452 27453 27454 27455 27456 27457 27458 27459 27460 27461 27462 27463 27464 27465 27466 27467 27468 27469 27470 27471 27472 27473 27474 27475 27476 27477 27478 27479 27480 27481 27482 27483 27484 27485 27486 27487 27488 27489 27490 27491 27492 27493 27494 27495 27496 27497 27498 27499 27500 27501 27502 27503 27504 27505 27506 27507 27508 27509 27510 27511 27512 27513 27514 27515 27516 27517 27518 27519 27520 27521 27522 27523 27524 27525 27526 27527 27528 27529 27530 27531 27532 27533 27534 27535 27536 27537 27538 27539 27540 27541 27542 27543 27544 27545 27546 27547 27548 27549 27550 27551 27552 27553 27554 27555 27556 27557 27558 27559 27560 27561 27562 27563 27564 27565 27566 27567 27568 27569 27570 27571 27572 27573 27574 27575 27576 27577 27578 27579 27580 27581 27582 27583 27584 27585 27586 27587 27588 27589 27590 27591 27592 27593 27594 27595 27596 27597 27598 27599 27600 27601 27602 27603 27604 27605 27606 27607 27608 27609 27610 27611 27612 27613 27614 27615 27616 27617 27618 27619 27620 27621 27622 27623 27624 27625 27626 27627 27628 27629 27630 27631 27632 27633 27634 27635 27636 27637 27638 27639 27640 27641 27642 27643 27644 27645 27646 27647 27648 27649 27650 27651 27652 27653 27654 27655 27656 27657 27658 27659 27660 27661 27662 27663 27664 27665 27666 27667 27668 27669 27670 27671 27672 27673 27674 27675 27676 27677 27678 27679 27680 27681 27682 27683 27684 27685 27686 27687 27688 27689 27690 27691 27692 27693 27694 27695 27696 27697 27698 27699 27700 27701 27702 27703 27704 27705 27706 27707 27708 27709 27710 27711 27712 27713 27714 27715 27716 27717 27718 27719 27720 27721 27722 27723 27724 27725 27726 27727 27728 27729 27730 27731 27732 27733 27734 27735 27736 27737 27738 27739 27740 27741 27742 27743 27744 27745 27746 27747 27748 27749 27750 27751 27752 27753 27754 27755 27756 27757 27758 27759 27760 27761 27762 27763 27764 27765 27766 27767 27768 27769 27770 27771 27772 27773 27774 27775 27776 27777 27778 27779 27780 27781 27782 27783 27784 27785 27786 27787 27788 27789 27790 27791 27792 27793 27794 27795 27796 27797 27798 27799 27800 27801 27802 27803 27804 27805 27806 27807 27808 27809 27810 27811 27812 27813 27814 27815 27816 27817 27818 27819 27820 27821 27822 27823 27824 27825 27826 27827 27828 27829 27830 27831 27832 27833 27834 27835 27836 27837 27838 27839 27840 27841 27842 27843 27844 27845 27846 27847 27848 27849 27850 27851 27852 27853 27854 27855 27856 27857 27858 27859 27860 27861 27862 27863 27864 27865 27866 27867 27868 27869 27870 27871 27872 27873 27874 27875 27876 27877 27878 27879 27880 27881 27882 27883 27884 27885 27886 27887 27888 27889 27890 27891 27892 27893 27894 27895 27896 27897 27898 27899 27900 27901 27902 27903 27904 27905 27906 27907 27908 27909 27910 27911 27912 27913 27914 27915 27916 27917 27918 27919 27920 27921 27922 27923 27924 27925 27926 27927 27928 27929 27930 27931 27932 27933 27934 27935 27936 27937 27938 27939 27940 27941 27942 27943 27944 27945 27946 27947 27948 27949 27950 27951 27952 27953 27954 27955 27956 27957 27958 27959 27960 27961 27962 27963 27964 27965 27966 27967 27968 27969 27970 27971 27972 27973 27974 27975 27976 27977 27978 27979 27980 27981 27982 27983 27984 27985 27986 27987 27988 27989 27990 27991 27992 27993 27994 27995 27996 27997 27998 27999 28000 28001 28002 28003 28004 28005 28006 28007 28008 28009 28010 28011 28012 28013 28014 28015 28016 28017 28018 28019 28020 28021 28022 28023 28024 28025 28026 28027 28028 28029 28030 28031 28032 28033 28034 28035 28036 28037 28038 28039 28040 28041 28042 28043 28044 28045 28046 28047 28048 28049 28050 28051 28052 28053 28054 28055 28056 28057 28058 28059 28060 28061 28062 28063 28064 28065 28066 28067 28068 28069 28070 28071 28072 28073 28074 28075 28076 28077 28078 28079 28080 28081 28082 28083 28084 28085 28086 28087 28088 28089 28090 28091 28092 28093 28094 28095 28096 28097 28098 28099 28100 28101 28102 28103 28104 28105 28106 28107 28108 28109 28110 28111 28112 28113 28114 28115 28116 28117 28118 28119 28120 28121 28122 28123 28124 28125 28126 28127 28128 28129 28130 28131 28132 28133 28134 28135 28136 28137 28138 28139 28140 28141 28142 28143 28144 28145 28146 28147 28148 28149 28150 28151 28152 28153 28154 28155 28156 28157 28158 28159 28160 28161 28162 28163 28164 28165 28166 28167 28168 28169 28170 28171 28172 28173 28174 28175 28176 28177 28178 28179 28180 28181 28182 28183 28184 28185 28186 28187 28188 28189 28190 28191 28192 28193 28194 28195 28196 28197 28198 28199 28200 28201 28202 28203 28204 28205 28206 28207 28208 28209 28210 28211 28212 28213 28214 28215 28216 28217 28218 28219 28220 28221 28222 28223 28224 28225 28226 28227 28228 28229 28230 28231 28232 28233 28234 28235 28236 28237 28238 28239 28240 28241 28242 28243 28244 28245 28246 28247 28248 28249 28250 28251 28252 28253 28254 28255 28256 28257 28258 28259 28260 28261 28262 28263 28264 28265 28266 28267 28268 28269 28270 28271 28272 28273 28274 28275 28276 28277 28278 28279 28280 28281 28282 28283 28284 28285 28286 28287 28288 28289 28290 28291 28292 28293 28294 28295 28296 28297 28298 28299 28300 28301 28302 28303 28304 28305 28306 28307 28308 28309 28310 28311 28312 28313 28314 28315 28316 28317 28318 28319 28320 28321 28322 28323 28324 28325 28326 28327 28328 28329 28330 28331 28332 28333 28334 28335 28336 28337 28338 28339 28340 28341 28342 28343 28344 28345 28346 28347 28348 28349 28350 28351 28352 28353 28354 28355 28356 28357 28358 28359 28360 28361 28362 28363 28364 28365 28366 28367 28368 28369 28370 28371 28372 28373 28374 28375 28376 28377 28378 28379 28380 28381 28382 28383 28384 28385 28386 28387 28388 28389 28390 28391 28392 28393 28394 28395 28396 28397 28398 28399 28400 28401 28402 28403 28404 28405 28406 28407 28408 28409 28410 28411 28412 28413 28414 28415 28416 28417 28418 28419 28420 28421 28422 28423 28424 28425 28426 28427 28428 28429 28430 28431 28432 28433 28434 28435 28436 28437 28438 28439 28440 28441 28442 28443 28444 28445 28446 28447 28448 28449 28450 28451 28452 28453 28454 28455 28456 28457 28458 28459 28460 28461 28462 28463 28464 28465 28466 28467 28468 28469 28470 28471 28472 28473 28474 28475 28476 28477 28478 28479 28480 28481 28482 28483 28484 28485 28486 28487 28488 28489 28490 28491 28492 28493 28494 28495 28496 28497 28498 28499 28500 28501 28502 28503 28504 28505 28506 28507 28508 28509 28510 28511 28512 28513 28514 28515 28516 28517 28518 28519 28520 28521 28522 28523 28524 28525 28526 28527 28528 28529 28530 28531 28532 28533 28534 28535 28536 28537 28538 28539 28540 28541 28542 28543 28544 28545 28546 28547 28548 28549 28550 28551 28552 28553 28554 28555 28556 28557 28558 28559 28560 28561 28562 28563 28564 28565 28566 28567 28568 28569 28570 28571 28572 28573 28574 28575 28576 28577 28578 28579 28580 28581 28582 28583 28584 28585 28586 28587 28588 28589 28590 28591 28592 28593 28594 28595 28596 28597 28598 28599 28600 28601 28602 28603 28604 28605 28606 28607 28608 28609 28610 28611 28612 28613 28614 28615 28616 28617 28618 28619 28620 28621 28622 28623 28624 28625 28626 28627 28628 28629 28630 28631 28632 28633 28634 28635 28636 28637 28638 28639 28640 28641 28642 28643 28644 28645 28646 28647 28648 28649 28650 28651 28652 28653 28654 28655 28656 28657 28658 28659 28660 28661 28662 28663 28664 28665 28666 28667 28668 28669 28670 28671 28672 28673 28674 28675 28676 28677 28678 28679 28680 28681 28682 28683 28684 28685 28686 28687 28688 28689 28690 28691 28692 28693 28694 28695 28696 28697 28698 28699 28700 28701 28702 28703 28704 28705 28706 28707 28708 28709 28710 28711 28712 28713 28714 28715 28716 28717 28718 28719 28720 28721 28722 28723 28724 28725 28726 28727 28728 28729 28730 28731 28732 28733 28734 28735 28736 28737 28738 28739 28740 28741 28742 28743 28744 28745 28746 28747 28748 28749 28750 28751 28752 28753 28754 28755 28756 28757 28758 28759 28760 28761 28762 28763 28764 28765 28766 28767 28768 28769 28770 28771 28772 28773 28774 28775 28776 28777 28778 28779 28780 28781 28782 28783 28784 28785 28786 28787 28788 28789 28790 28791 28792 28793 28794 28795 28796 28797 28798 28799 28800 28801 28802 28803 28804 28805 28806 28807 28808 28809 28810 28811 28812 28813 28814 28815 28816 28817 28818 28819 28820 28821 28822 28823 28824 28825 28826 28827 28828 28829 28830 28831 28832 28833 28834 28835 28836 28837 28838 28839 28840 28841 28842 28843 28844 28845 28846 28847 28848 28849 28850 28851 28852 28853 28854 28855 28856 28857 28858 28859 28860 28861 28862 28863 28864 28865 28866 28867 28868 28869 28870 28871 28872 28873 28874 28875 28876 28877 28878 28879 28880 28881 28882 28883 28884 28885 28886 28887 28888 28889 28890 28891 28892 28893 28894 28895 28896 28897 28898 28899 28900 28901 28902 28903 28904 28905 28906 28907 28908 28909 28910 28911 28912 28913 28914 28915 28916 28917 28918 28919 28920 28921 28922 28923 28924 28925 28926 28927 28928 28929 28930 28931 28932 28933 28934 28935 28936 28937 28938 28939 28940 28941 28942 28943 28944 28945 28946 28947 28948 28949 28950 28951 28952 28953 28954 28955 28956 28957 28958 28959 28960 28961 28962 28963 28964 28965 28966 28967 28968 28969 28970 28971 28972 28973 28974 28975 28976 28977 28978 28979 28980 28981 28982 28983 28984 28985 28986 28987 28988 28989 28990 28991 28992 28993 28994 28995 28996 28997 28998 28999 29000 29001 29002 29003 29004 29005 29006 29007 29008 29009 29010 29011 29012 29013 29014 29015 29016 29017 29018 29019 29020 29021 29022 29023 29024 29025 29026 29027 29028 29029 29030 29031 29032 29033 29034 29035 29036 29037 29038 29039 29040 29041 29042 29043 29044 29045 29046 29047 29048 29049 29050 29051 29052 29053 29054 29055 29056 29057 29058 29059 29060 29061 29062 29063 29064 29065 29066 29067 29068 29069 29070 29071 29072 29073 29074 29075 29076 29077 29078 29079 29080 29081 29082 29083 29084 29085 29086 29087 29088 29089 29090 29091 29092 29093 29094 29095 29096 29097 29098 29099 29100 29101 29102 29103 29104 29105 29106 29107 29108 29109 29110 29111 29112 29113 29114 29115 29116 29117 29118 29119 29120 29121 29122 29123 29124 29125 29126 29127 29128 29129 29130 29131 29132 29133 29134 29135 29136 29137 29138 29139 29140 29141 29142 29143 29144 29145 29146 29147 29148 29149 29150 29151 29152 29153 29154 29155 29156 29157 29158 29159 29160 29161 29162 29163 29164 29165 29166 29167 29168 29169 29170 29171 29172 29173 29174 29175 29176 29177 29178 29179 29180 29181 29182 29183 29184 29185 29186 29187 29188 29189 29190 29191 29192 29193 29194 29195 29196 29197 29198 29199 29200 29201 29202 29203 29204 29205 29206 29207 29208 29209 29210 29211 29212 29213 29214 29215 29216 29217 29218 29219 29220 29221 29222 29223 29224 29225 29226 29227 29228 29229 29230 29231 29232 29233 29234 29235 29236 29237 29238 29239 29240 29241 29242 29243 29244 29245 29246 29247 29248 29249 29250 29251 29252 29253 29254 29255 29256 29257 29258 29259 29260 29261 29262 29263 29264 29265 29266 29267 29268 29269 29270 29271 29272 29273 29274 29275 29276 29277 29278 29279 29280 29281 29282 29283 29284 29285 29286 29287 29288 29289 29290 29291 29292 29293 29294 29295 29296 29297 29298 29299 29300 29301 29302 29303 29304 29305 29306 29307 29308 29309 29310 29311 29312 29313 29314 29315 29316 29317 29318 29319 29320 29321 29322 29323 29324 29325 29326 29327 29328 29329 29330 29331 29332 29333 29334 29335 29336 29337 29338 29339 29340 29341 29342 29343 29344 29345 29346 29347 29348 29349 29350 29351 29352 29353 29354 29355 29356 29357 29358 29359 29360 29361 29362 29363 29364 29365 29366 29367 29368 29369 29370 29371 29372 29373 29374 29375 29376 29377 29378 29379 29380 29381 29382 29383 29384 29385 29386 29387 29388 29389 29390 29391 29392 29393 29394 29395 29396 29397 29398 29399 29400 29401 29402 29403 29404 29405 29406 29407 29408 29409 29410 29411 29412 29413 29414 29415 29416 29417 29418 29419 29420 29421 29422 29423 29424 29425 29426 29427 29428 29429 29430 29431 29432 29433 29434 29435 29436 29437 29438 29439 29440 29441 29442 29443 29444 29445 29446 29447 29448 29449 29450 29451 29452 29453 29454 29455 29456 29457 29458 29459 29460 29461 29462 29463 29464 29465 29466 29467 29468 29469 29470 29471 29472 29473 29474 29475 29476 29477 29478 29479 29480 29481 29482 29483 29484 29485 29486 29487 29488 29489 29490 29491 29492 29493 29494 29495 29496 29497 29498 29499 29500 29501 29502 29503 29504 29505 29506 29507 29508 29509 29510 29511 29512 29513 29514 29515 29516 29517 29518 29519 29520 29521 29522 29523 29524 29525 29526 29527 29528 29529 29530 29531 29532 29533 29534 29535 29536 29537 29538 29539 29540 29541 29542 29543 29544 29545 29546 29547 29548 29549 29550 29551 29552 29553 29554 29555 29556 29557 29558 29559 29560 29561 29562 29563 29564 29565 29566 29567 29568 29569 29570 29571 29572 29573 29574 29575 29576 29577 29578 29579 29580 29581 29582 29583 29584 29585 29586 29587 29588 29589 29590 29591 29592 29593 29594 29595 29596 29597 29598 29599 29600 29601 29602 29603 29604 29605 29606 29607 29608 29609 29610 29611 29612 29613 29614 29615 29616 29617 29618 29619 29620 29621 29622 29623 29624 29625 29626 29627 29628 29629 29630 29631 29632 29633 29634 29635 29636 29637 29638 29639 29640 29641 29642 29643 29644 29645 29646 29647 29648 29649 29650 29651 29652 29653 29654 29655 29656 29657 29658 29659 29660 29661 29662 29663 29664 29665 29666 29667 29668 29669 29670 29671 29672 29673 29674 29675 29676 29677 29678 29679 29680 29681 29682 29683 29684 29685 29686 29687 29688 29689 29690 29691 29692 29693 29694 29695 29696 29697 29698 29699 29700 29701 29702 29703 29704 29705 29706 29707 29708 29709 29710 29711 29712 29713 29714 29715 29716 29717 29718 29719 29720 29721 29722 29723 29724 29725 29726 29727 29728 29729 29730 29731 29732 29733 29734 29735 29736 29737 29738 29739 29740 29741 29742 29743 29744 29745 29746 29747 29748 29749 29750 29751 29752 29753 29754 29755 29756 29757 29758 29759 29760 29761 29762 29763 29764 29765 29766 29767 29768 29769 29770 29771 29772 29773 29774 29775 29776 29777 29778 29779 29780 29781 29782 29783 29784 29785 29786 29787 29788 29789 29790 29791 29792 29793 29794 29795 29796 29797 29798 29799 29800 29801 29802 29803 29804 29805 29806 29807 29808 29809 29810 29811 29812 29813 29814 29815 29816 29817 29818 29819 29820 29821 29822 29823 29824 29825 29826 29827 29828 29829 29830 29831 29832 29833 29834 29835 29836 29837 29838 29839 29840 29841 29842 29843 29844 29845 29846 29847 29848 29849 29850 29851 29852 29853 29854 29855 29856 29857 29858 29859 29860 29861 29862 29863 29864 29865 29866 29867 29868 29869 29870 29871 29872 29873 29874 29875 29876 29877 29878 29879 29880 29881 29882 29883 29884 29885 29886 29887 29888 29889 29890 29891 29892 29893 29894 29895 29896 29897 29898 29899 29900 29901 29902 29903 29904 29905 29906 29907 29908 29909 29910 29911 29912 29913 29914 29915 29916 29917 29918 29919 29920 29921 29922 29923 29924 29925 29926 29927 29928 29929 29930 29931 29932 29933 29934 29935 29936 29937 29938 29939 29940 29941 29942 29943 29944 29945 29946 29947 29948 29949 29950 29951 29952 29953 29954 29955 29956 29957 29958 29959 29960 29961 29962 29963 29964 29965 29966 29967 29968 29969 29970 29971 29972 29973 29974 29975 29976 29977 29978 29979 29980 29981 29982 29983 29984 29985 29986 29987 29988 29989 29990 29991 29992 29993 29994 29995 29996 29997 29998 29999 30000 30001 30002 30003 30004 30005 30006 30007 30008 30009 30010 30011 30012 30013 30014 30015 30016 30017 30018 30019 30020 30021 30022 30023 30024 30025 30026 30027 30028 30029 30030 30031 30032 30033 30034 30035 30036 30037 30038 30039 30040 30041 30042 30043 30044 30045 30046 30047 30048 30049 30050 30051 30052 30053 30054 30055 30056 30057 30058 30059 30060 30061 30062 30063 30064 30065 30066 30067 30068 30069 30070 30071 30072 30073 30074 30075 30076 30077 30078 30079 30080 30081 30082 30083 30084 30085 30086 30087 30088 30089 30090 30091 30092 30093 30094 30095 30096 30097 30098 30099 30100 30101 30102 30103 30104 30105 30106 30107 30108 30109 30110 30111 30112 30113 30114 30115 30116 30117 30118 30119 30120 30121 30122 30123 30124 30125 30126 30127 30128 30129 30130 30131 30132 30133 30134 30135 30136 30137 30138 30139 30140 30141 30142 30143 30144 30145 30146 30147 30148 30149 30150 30151 30152 30153 30154 30155 30156 30157 30158 30159 30160 30161 30162 30163 30164 30165 30166 30167 30168 30169 30170 30171 30172 30173 30174 30175 30176 30177 30178 30179 30180 30181 30182 30183 30184 30185 30186 30187 30188 30189 30190 30191 30192 30193 30194 30195 30196 30197 30198 30199 30200 30201 30202 30203 30204 30205 30206 30207 30208 30209 30210 30211 30212 30213 30214 30215 30216 30217 30218 30219 30220 30221 30222 30223 30224 30225 30226 30227 30228 30229 30230 30231 30232 30233 30234 30235 30236 30237 30238 30239 30240 30241 30242 30243 30244 30245 30246 30247 30248 30249 30250 30251 30252 30253 30254 30255 30256 30257 30258 30259 30260 30261 30262 30263 30264 30265 30266 30267 30268 30269 30270 30271 30272 30273 30274 30275 30276 30277 30278 30279 30280 30281 30282 30283 30284 30285 30286 30287 30288 30289 30290 30291 30292 30293 30294 30295 30296 30297 30298 30299 30300 30301 30302 30303 30304 30305 30306 30307 30308 30309 30310 30311 30312 30313 30314 30315 30316 30317 30318 30319 30320 30321 30322 30323 30324 30325 30326 30327 30328 30329 30330 30331 30332 30333 30334 30335 30336 30337 30338 30339 30340 30341 30342 30343 30344 30345 30346 30347 30348 30349 30350 30351 30352 30353 30354 30355 30356 30357 30358 30359 30360 30361 30362 30363 30364 30365 30366 30367 30368 30369 30370 30371 30372 30373 30374 30375 30376 30377 30378 30379 30380 30381 30382 30383 30384 30385 30386 30387 30388 30389 30390 30391 30392 30393 30394 30395 30396 30397 30398 30399 30400 30401 30402 30403 30404 30405 30406 30407 30408 30409 30410 30411 30412 30413 30414 30415 30416 30417 30418 30419 30420 30421 30422 30423 30424 30425 30426 30427 30428 30429 30430 30431 30432 30433 30434 30435 30436 30437 30438 30439 30440 30441 30442 30443 30444 30445 30446 30447 30448 30449 30450 30451 30452 30453 30454 30455 30456 30457 30458 30459 30460 30461 30462 30463 30464 30465 30466 30467 30468 30469 30470 30471 30472 30473 30474 30475 30476 30477 30478 30479 30480 30481 30482 30483 30484 30485 30486 30487 30488 30489 30490 30491 30492 30493 30494 30495 30496 30497 30498 30499 30500 30501 30502 30503 30504 30505 30506 30507 30508 30509 30510 30511 30512 30513 30514 30515 30516 30517 30518 30519 30520 30521 30522 30523 30524 30525 30526 30527 30528 30529 30530 30531 30532 30533 30534 30535 30536 30537 30538 30539 30540 30541 30542 30543 30544 30545 30546 30547 30548 30549 30550 30551 30552 30553 30554 30555 30556 30557 30558 30559 30560 30561 30562 30563 30564 30565 30566 30567 30568 30569 30570 30571 30572 30573 30574 30575 30576 30577 30578 30579 30580 30581 30582 30583 30584 30585 30586 30587 30588 30589 30590 30591 30592 30593 30594 30595 30596 30597 30598 30599 30600 30601 30602 30603 30604 30605 30606 30607 30608 30609 30610 30611 30612 30613 30614 30615 30616 30617 30618 30619 30620 30621 30622 30623 30624 30625 30626 30627 30628 30629 30630 30631 30632 30633 30634 30635 30636 30637 30638 30639 30640 30641 30642 30643 30644 30645 30646 30647 30648 30649 30650 30651 30652 30653 30654 30655 30656 30657 30658 30659 30660 30661 30662 30663 30664 30665 30666 30667 30668 30669 30670 30671 30672 30673 30674 30675 30676 30677 30678 30679 30680 30681 30682 30683 30684 30685 30686 30687 30688 30689 30690 30691 30692 30693 30694 30695 30696 30697 30698 30699 30700 30701 30702 30703 30704 30705 30706 30707 30708 30709 30710 30711 30712 30713 30714 30715 30716 30717 30718 30719 30720 30721 30722 30723 30724 30725 30726 30727 30728 30729 30730 30731 30732 30733 30734 30735 30736 30737 30738 30739 30740 30741 30742 30743 30744 30745 30746 30747 30748 30749 30750 30751 30752 30753 30754 30755 30756 30757 30758 30759 30760 30761 30762 30763 30764 30765 30766 30767 30768 30769 30770 30771 30772 30773 30774 30775 30776 30777 30778 30779 30780 30781 30782 30783 30784 30785 30786 30787 30788 30789 30790 30791 30792 30793 30794 30795 30796 30797 30798 30799 30800 30801 30802 30803 30804 30805 30806 30807 30808 30809 30810 30811 30812 30813 30814 30815 30816 30817 30818 30819 30820 30821 30822 30823 30824 30825 30826 30827 30828 30829 30830 30831 30832 30833 30834 30835 30836 30837 30838 30839 30840 30841 30842 30843 30844 30845 30846 30847 30848 30849 30850 30851 30852 30853 30854 30855 30856 30857 30858 30859 30860 30861 30862 30863 30864 30865 30866 30867 30868 30869 30870 30871 30872 30873 30874 30875 30876 30877 30878 30879 30880 30881 30882 30883 30884 30885 30886 30887 30888 30889 30890 30891 30892 30893 30894 30895 30896 30897 30898 30899 30900 30901 30902 30903 30904 30905 30906 30907 30908 30909 30910 30911 30912 30913 30914 30915 30916 30917 30918 30919 30920 30921 30922 30923 30924 30925 30926 30927 30928 30929 30930 30931 30932 30933 30934 30935 30936 30937 30938 30939 30940 30941 30942 30943 30944 30945 30946 30947 30948 30949 30950 30951 30952 30953 30954 30955 30956 30957 30958 30959 30960 30961 30962 30963 30964 30965 30966 30967 30968 30969 30970 30971 30972 30973 30974 30975 30976 30977 30978 30979 30980 30981 30982 30983 30984 30985 30986 30987 30988 30989 30990 30991 30992 30993 30994 30995 30996 30997 30998 30999 31000 31001 31002 31003 31004 31005 31006 31007 31008 31009 31010 31011 31012 31013 31014 31015 31016 31017 31018 31019 31020 31021 31022 31023 31024 31025 31026 31027 31028 31029 31030 31031 31032 31033 31034 31035 31036 31037 31038 31039 31040 31041 31042 31043 31044 31045 31046 31047 31048 31049 31050 31051 31052 31053 31054 31055 31056 31057 31058 31059 31060 31061 31062 31063 31064 31065 31066 31067 31068 31069 31070 31071 31072 31073 31074 31075 31076 31077 31078 31079 31080 31081 31082 31083 31084 31085 31086 31087 31088 31089 31090 31091 31092 31093 31094 31095 31096 31097 31098 31099 31100 31101 31102 31103 31104 31105 31106 31107 31108 31109 31110 31111 31112 31113 31114 31115 31116 31117 31118 31119 31120 31121 31122 31123 31124 31125 31126 31127 31128 31129 31130 31131 31132 31133 31134 31135 31136 31137 31138 31139 31140 31141 31142 31143 31144 31145 31146 31147 31148 31149 31150 31151 31152 31153 31154 31155 31156 31157 31158 31159 31160 31161 31162 31163 31164 31165 31166 31167 31168 31169 31170 31171 31172 31173 31174 31175 31176 31177 31178 31179 31180 31181 31182 31183 31184 31185 31186 31187 31188 31189 31190 31191 31192 31193 31194 31195 31196 31197 31198 31199 31200 31201 31202 31203 31204 31205 31206 31207 31208 31209 31210 31211 31212 31213 31214 31215 31216 31217 31218 31219 31220 31221 31222 31223 31224 31225 31226 31227 31228 31229 31230 31231 31232 31233 31234 31235 31236 31237 31238 31239 31240 31241 31242 31243 31244 31245 31246 31247 31248 31249 31250 31251 31252 31253 31254 31255 31256 31257 31258 31259 31260 31261 31262 31263 31264 31265 31266 31267 31268 31269 31270 31271 31272 31273 31274 31275 31276 31277 31278 31279 31280 31281 31282 31283 31284 31285 31286 31287 31288 31289 31290 31291 31292 31293 31294 31295 31296 31297 31298 31299 31300 31301 31302 31303 31304 31305 31306 31307 31308 31309 31310 31311 31312 31313 31314 31315 31316 31317 31318 31319 31320 31321 31322 31323 31324 31325 31326 31327 31328 31329 31330 31331 31332 31333 31334 31335 31336 31337 31338 31339 31340 31341 31342 31343 31344 31345 31346 31347 31348 31349 31350 31351 31352 31353 31354 31355 31356 31357 31358 31359 31360 31361 31362 31363 31364 31365 31366 31367 31368 31369 31370 31371 31372 31373 31374 31375 31376 31377 31378 31379 31380 31381 31382 31383 31384 31385 31386 31387 31388 31389 31390 31391 31392 31393 31394 31395 31396 31397 31398 31399 31400 31401 31402 31403 31404 31405 31406 31407 31408 31409 31410 31411 31412 31413 31414 31415 31416 31417 31418 31419 31420 31421 31422 31423 31424 31425 31426 31427 31428 31429 31430 31431 31432 31433 31434 31435 31436 31437 31438 31439 31440 31441 31442 31443 31444 31445 31446 31447 31448 31449 31450 31451 31452 31453 31454 31455 31456 31457 31458 31459 31460 31461 31462 31463 31464 31465 31466 31467 31468 31469 31470 31471 31472 31473 31474 31475 31476 31477 31478 31479 31480 31481 31482 31483 31484 31485 31486 31487 31488 31489 31490 31491 31492 31493 31494 31495 31496 31497 31498 31499 31500 31501 31502 31503 31504 31505 31506 31507 31508 31509 31510 31511 31512 31513 31514 31515 31516 31517 31518 31519 31520 31521 31522 31523 31524 31525 31526 31527 31528 31529 31530 31531 31532 31533 31534 31535 31536 31537 31538 31539 31540 31541 31542 31543 31544 31545 31546 31547 31548 31549 31550 31551 31552 31553 31554 31555 31556 31557 31558 31559 31560 31561 31562 31563 31564 31565 31566 31567 31568 31569 31570 31571 31572 31573 31574 31575 31576 31577 31578 31579 31580 31581 31582 31583 31584 31585 31586 31587 31588 31589 31590 31591 31592 31593 31594 31595 31596 31597 31598 31599 31600 31601 31602 31603 31604 31605 31606 31607 31608 31609 31610 31611 31612 31613 31614 31615 31616 31617 31618 31619 31620 31621 31622 31623 31624 31625 31626 31627 31628 31629 31630 31631 31632 31633 31634 31635 31636 31637 31638 31639 31640 31641 31642 31643 31644 31645 31646 31647 31648 31649 31650 31651 31652 31653 31654 31655 31656 31657 31658 31659 31660 31661 31662 31663 31664 31665 31666 31667 31668 31669 31670 31671 31672 31673 31674 31675 31676 31677 31678 31679 31680 31681 31682 31683 31684 31685 31686 31687 31688 31689 31690 31691 31692 31693 31694 31695 31696 31697 31698 31699 31700 31701 31702 31703 31704 31705 31706 31707 31708 31709 31710 31711 31712 31713 31714 31715 31716 31717 31718 31719 31720 31721 31722 31723 31724 31725 31726 31727 31728 31729 31730 31731 31732 31733 31734 31735 31736 31737 31738 31739 31740 31741 31742 31743 31744 31745 31746 31747 31748 31749 31750 31751 31752 31753 31754 31755 31756 31757 31758 31759 31760 31761 31762 31763 31764 31765 31766 31767 31768 31769 31770 31771 31772 31773 31774 31775 31776 31777 31778 31779 31780 31781 31782 31783 31784 31785 31786 31787 31788 31789 31790 31791 31792 31793 31794 31795 31796 31797 31798 31799 31800 31801 31802 31803 31804 31805 31806 31807 31808 31809 31810 31811 31812 31813 31814 31815 31816 31817 31818 31819 31820 31821 31822 31823 31824 31825 31826 31827 31828 31829 31830 31831 31832 31833 31834 31835 31836 31837 31838 31839 31840 31841 31842 31843 31844 31845 31846 31847 31848 31849 31850 31851 31852 31853 31854 31855 31856 31857 31858 31859 31860 31861 31862 31863 31864 31865 31866 31867 31868 31869 31870 31871 31872 31873 31874 31875 31876 31877 31878 31879 31880 31881 31882 31883 31884 31885 31886 31887 31888 31889 31890 31891 31892 31893 31894 31895 31896 31897 31898 31899 31900 31901 31902 31903 31904 31905 31906 31907 31908 31909 31910 31911 31912 31913 31914 31915 31916 31917 31918 31919 31920 31921 31922 31923 31924 31925 31926 31927 31928 31929 31930 31931 31932 31933 31934 31935 31936 31937 31938 31939 31940 31941 31942 31943 31944 31945 31946 31947 31948 31949 31950 31951 31952 31953 31954 31955 31956 31957 31958 31959 31960 31961 31962 31963 31964 31965 31966 31967 31968 31969 31970 31971 31972 31973 31974 31975 31976 31977 31978 31979 31980 31981 31982 31983 31984 31985 31986 31987 31988 31989 31990 31991 31992 31993 31994 31995 31996 31997 31998 31999 32000 32001 32002 32003 32004 32005 32006 32007 32008 32009 32010 32011 32012 32013 32014 32015 32016 32017 32018 32019 32020 32021 32022 32023 32024 32025 32026 32027 32028 32029 32030 32031 32032 32033 32034 32035 32036 32037 32038 32039 32040 32041 32042 32043 32044 32045 32046 32047 32048 32049 32050 32051 32052 32053 32054 32055 32056 32057 32058 32059 32060 32061 32062 32063 32064 32065 32066 32067 32068 32069 32070 32071 32072 32073 32074 32075 32076 32077 32078 32079 32080 32081 32082 32083 32084 32085 32086 32087 32088 32089 32090 32091 32092 32093 32094 32095 32096 32097 32098 32099 32100 32101 32102 32103 32104 32105 32106 32107 32108 32109 32110 32111 32112 32113 32114 32115 32116 32117 32118 32119 32120 32121 32122 32123 32124 32125 32126 32127 32128 32129 32130 32131 32132 32133 32134 32135 32136 32137 32138 32139 32140 32141 32142 32143 32144 32145 32146 32147 32148 32149 32150 32151 32152 32153 32154 32155 32156 32157 32158 32159 32160 32161 32162 32163 32164 32165 32166 32167 32168 32169 32170 32171 32172 32173 32174 32175 32176 32177 32178 32179 32180 32181 32182 32183 32184 32185 32186 32187 32188 32189 32190 32191 32192 32193 32194 32195 32196 32197 32198 32199 32200 32201 32202 32203 32204 32205 32206 32207 32208 32209 32210 32211 32212 32213 32214 32215 32216 32217 32218 32219 32220 32221 32222 32223 32224 32225 32226 32227 32228 32229 32230 32231 32232 32233 32234 32235 32236 32237 32238 32239 32240 32241 32242 32243 32244 32245 32246 32247 32248 32249 32250 32251 32252 32253 32254 32255 32256 32257 32258 32259 32260 32261 32262 32263 32264 32265 32266 32267 32268 32269 32270 32271 32272 32273 32274 32275 32276 32277 32278 32279 32280 32281 32282 32283 32284 32285 32286 32287 32288 32289 32290 32291 32292 32293 32294 32295 32296 32297 32298 32299 32300 32301 32302 32303 32304 32305 32306 32307 32308 32309 32310 32311 32312 32313 32314 32315 32316 32317 32318 32319 32320 32321 32322 32323 32324 32325 32326 32327 32328 32329 32330 32331 32332 32333 32334 32335 32336 32337 32338 32339 32340 32341 32342 32343 32344 32345 32346 32347 32348 32349 32350 32351 32352 32353 32354 32355 32356 32357 32358 32359 32360 32361 32362 32363 32364 32365 32366 32367 32368 32369 32370 32371 32372 32373 32374 32375 32376 32377 32378 32379 32380 32381 32382 32383 32384 32385 32386 32387 32388 32389 32390 32391 32392 32393 32394 32395 32396 32397 32398 32399 32400 32401 32402 32403 32404 32405 32406 32407 32408 32409 32410 32411 32412 32413 32414 32415 32416 32417 32418 32419 32420 32421 32422 32423 32424 32425 32426 32427 32428 32429 32430 32431 32432 32433 32434 32435 32436 32437 32438 32439 32440 32441 32442 32443 32444 32445 32446 32447 32448 32449 32450 32451 32452 32453 32454 32455 32456 32457 32458 32459 32460 32461 32462 32463 32464 32465 32466 32467 32468 32469 32470 32471 32472 32473 32474 32475 32476 32477 32478 32479 32480 32481 32482 32483 32484 32485 32486 32487 32488 32489 32490 32491 32492 32493 32494 32495 32496 32497 32498 32499 32500 32501 32502 32503 32504 32505 32506 32507 32508 32509 32510 32511 32512 32513 32514 32515 32516 32517 32518 32519 32520 32521 32522 32523 32524 32525 32526 32527 32528 32529 32530 32531 32532 32533 32534 32535 32536 32537 32538 32539 32540 32541 32542 32543 32544 32545 32546 32547 32548 32549 32550 32551 32552 32553 32554 32555 32556 32557 32558 32559 32560 32561 32562 32563 32564 32565 32566 32567 32568 32569 32570 32571 32572 32573 32574 32575 32576 32577 32578 32579 32580 32581 32582 32583 32584 32585 32586 32587 32588 32589 32590 32591 32592 32593 32594 32595 32596 32597 32598 32599 32600 32601 32602 32603 32604 32605 32606 32607 32608 32609 32610 32611 32612 32613 32614 32615 32616 32617 32618 32619 32620 32621 32622 32623 32624 32625 32626 32627 32628 32629 32630 32631 32632 32633 32634 32635 32636 32637 32638 32639 32640 32641 32642 32643 32644 32645 32646 32647 32648 32649 32650 32651 32652 32653 32654 32655 32656 32657 32658 32659 32660 32661 32662 32663 32664 32665 32666 32667 32668 32669 32670 32671 32672 32673 32674 32675 32676 32677 32678 32679 32680 32681 32682 32683 32684 32685 32686 32687 32688 32689 32690 32691 32692 32693 32694 32695 32696 32697 32698 32699 32700 32701 32702 32703 32704 32705 32706 32707 32708 32709 32710 32711 32712 32713 32714 32715 32716 32717 32718 32719 32720 32721 32722 32723 32724 32725 32726 32727 32728 32729 32730 32731 32732 32733 32734 32735 32736 32737 32738 32739 32740 32741 32742 32743 32744 32745 32746 32747 32748 32749 32750 32751 32752 32753 32754 32755 32756 32757 32758 32759 32760 32761 32762 32763 32764 32765 32766 32767 32768 32769 32770 32771 32772 32773 32774 32775 32776 32777 32778 32779 32780 32781 32782 32783 32784 32785 32786 32787 32788 32789 32790 32791 32792 32793 32794 32795 32796 32797 32798 32799 32800 32801 32802 32803 32804 32805 32806 32807 32808 32809 32810 32811 32812 32813 32814 32815 32816 32817 32818 32819 32820 32821 32822 32823 32824 32825 32826 32827 32828 32829 32830 32831 32832 32833 32834 32835 32836 32837 32838 32839 32840 32841 32842 32843 32844 32845 32846 32847 32848 32849 32850 32851 32852 32853 32854 32855 32856 32857 32858 32859 32860 32861 32862 32863 32864 32865 32866 32867 32868 32869 32870 32871 32872 32873 32874 32875 32876 32877 32878 32879 32880 32881 32882 32883 32884 32885 32886 32887 32888 32889 32890 32891 32892 32893 32894 32895 32896 32897 32898 32899 32900 32901 32902 32903 32904 32905 32906 32907 32908 32909 32910 32911 32912 32913 32914 32915 32916 32917 32918 32919 32920 32921 32922 32923 32924 32925 32926 32927 32928 32929 32930 32931 32932 32933 32934 32935 32936 32937 32938 32939 32940 32941 32942 32943 32944 32945 32946 32947 32948 32949 32950 32951 32952 32953 32954 32955 32956 32957 32958 32959 32960 32961 32962 32963 32964 32965 32966 32967 32968 32969 32970 32971 32972 32973 32974 32975 32976 32977 32978 32979 32980 32981 32982 32983 32984 32985 32986 32987 32988 32989 32990 32991 32992 32993 32994 32995 32996 32997 32998 32999 33000 33001 33002 33003 33004 33005 33006 33007 33008 33009 33010 33011 33012 33013 33014 33015 33016 33017 33018 33019 33020 33021 33022 33023 33024 33025 33026 33027 33028 33029 33030 33031 33032 33033 33034 33035 33036 33037 33038 33039 33040 33041 33042 33043 33044 33045 33046 33047 33048 33049 33050 33051 33052 33053 33054 33055 33056 33057 33058 33059 33060 33061 33062 33063 33064 33065 33066 33067 33068 33069 33070 33071 33072 33073 33074 33075 33076 33077 33078 33079 33080 33081 33082 33083 33084 33085 33086 33087 33088 33089 33090 33091 33092 33093 33094 33095 33096 33097 33098 33099 33100 33101 33102 33103 33104 33105 33106 33107 33108 33109 33110 33111 33112 33113 33114 33115 33116 33117 33118 33119 33120 33121 33122 33123 33124 33125 33126 33127 33128 33129 33130 33131 33132 33133 33134 33135 33136 33137 33138 33139 33140 33141 33142 33143 33144 33145 33146 33147 33148 33149 33150 33151 33152 33153 33154 33155 33156 33157 33158 33159 33160 33161 33162 33163 33164 33165 33166 33167 33168 33169 33170 33171 33172 33173 33174 33175 33176 33177 33178 33179 33180 33181 33182 33183 33184 33185 33186 33187 33188 33189 33190 33191 33192 33193 33194 33195 33196 33197 33198 33199 33200 33201 33202 33203 33204 33205 33206 33207 33208 33209 33210 33211 33212 33213 33214 33215 33216 33217 33218 33219 33220 33221 33222 33223 33224 33225 33226 33227 33228 33229 33230 33231 33232 33233 33234 33235 33236 33237 33238 33239 33240 33241 33242 33243 33244 33245 33246 33247 33248 33249 33250 33251 33252 33253 33254 33255 33256 33257 33258 33259 33260 33261 33262 33263 33264 33265 33266 33267 33268 33269 33270 33271 33272 33273 33274 33275 33276 33277 33278 33279 33280 33281 33282 33283 33284 33285 33286 33287 33288 33289 33290 33291 33292 33293 33294 33295 33296 33297 33298 33299 33300 33301 33302 33303 33304 33305 33306 33307 33308 33309 33310 33311 33312 33313 33314 33315 33316 33317 33318 33319 33320 33321 33322 33323 33324 33325 33326 33327 33328 33329 33330 33331 33332 33333 33334 33335 33336 33337 33338 33339 33340 33341 33342 33343 33344 33345 33346 33347 33348 33349 33350 33351 33352 33353 33354 33355 33356 33357 33358 33359 33360 33361 33362 33363 33364 33365 33366 33367 33368 33369 33370 33371 33372 33373 33374 33375 33376 33377 33378 33379 33380 33381 33382 33383 33384 33385 33386 33387 33388 33389 33390 33391 33392 33393 33394 33395 33396 33397 33398 33399 33400 33401 33402 33403 33404 33405 33406 33407 33408 33409 33410 33411 33412 33413 33414 33415 33416 33417 33418 33419 33420 33421 33422 33423 33424 33425 33426 33427 33428 33429 33430 33431 33432 33433 33434 33435 33436 33437 33438 33439 33440 33441 33442 33443 33444 33445 33446 33447 33448 33449 33450 33451 33452 33453 33454 33455 33456 33457 33458 33459 33460 33461 33462 33463 33464 33465 33466 33467 33468 33469 33470 33471 33472 33473 33474 33475 33476 33477 33478 33479 33480 33481 33482 33483 33484 33485 33486 33487 33488 33489 33490 33491 33492 33493 33494 33495 33496 33497 33498 33499 33500 33501 33502 33503 33504 33505 33506 33507 33508 33509 33510 33511 33512 33513 33514 33515 33516 33517 33518 33519 33520 33521 33522 33523 33524 33525 33526 33527 33528 33529 33530 33531 33532 33533 33534 33535 33536 33537 33538 33539 33540 33541 33542 33543 33544 33545 33546 33547 33548 33549 33550 33551 33552 33553 33554 33555 33556 33557 33558 33559 33560 33561 33562 33563 33564 33565 33566 33567 33568 33569 33570 33571 33572 33573 33574 33575 33576 33577 33578 33579 33580 33581 33582 33583 33584 33585 33586 33587 33588 33589 33590 33591 33592 33593 33594 33595 33596 33597 33598 33599 33600 33601 33602 33603 33604 33605 33606 33607 33608 33609 33610 33611 33612 33613 33614 33615 33616 33617 33618 33619 33620 33621 33622 33623 33624 33625 33626 33627 33628 33629 33630 33631 33632 33633 33634 33635 33636 33637 33638 33639 33640 33641 33642 33643 33644 33645 33646 33647 33648 33649 33650 33651 33652 33653 33654 33655 33656 33657 33658 33659 33660 33661 33662 33663 33664 33665 33666 33667 33668 33669 33670 33671 33672 33673 33674 33675 33676 33677 33678 33679 33680 33681 33682 33683 33684 33685 33686 33687 33688 33689 33690 33691 33692 33693 33694 33695 33696 33697 33698 33699 33700 33701 33702 33703 33704 33705 33706 33707 33708 33709 33710 33711 33712 33713 33714 33715 33716 33717 33718 33719 33720 33721 33722 33723 33724 33725 33726 33727 33728 33729 33730 33731 33732 33733 33734 33735 33736 33737 33738 33739 33740 33741 33742 33743 33744 33745 33746 33747 33748 33749 33750 33751 33752 33753 33754 33755 33756 33757 33758 33759 33760 33761 33762 33763 33764 33765 33766 33767 33768 33769 33770 33771 33772 33773 33774 33775 33776 33777 33778 33779 33780 33781 33782 33783 33784 33785 33786 33787 33788 33789 33790 33791 33792 33793 33794 33795 33796 33797 33798 33799 33800 33801 33802 33803 33804 33805 33806 33807 33808 33809 33810 33811 33812 33813 33814 33815 33816 33817 33818 33819 33820 33821 33822 33823 33824 33825 33826 33827 33828 33829 33830 33831 33832 33833 33834 33835 33836 33837 33838 33839 33840 33841 33842 33843 33844 33845 33846 33847 33848 33849 33850 33851 33852 33853 33854 33855 33856 33857 33858 33859 33860 33861 33862 33863 33864 33865 33866 33867 33868 33869 33870 33871 33872 33873 33874 33875 33876 33877 33878 33879 33880 33881 33882 33883 33884 33885 33886 33887 33888 33889 33890 33891 33892 33893 33894 33895 33896 33897 33898 33899 33900 33901 33902 33903 33904 33905 33906 33907 33908 33909 33910 33911 33912 33913 33914 33915 33916 33917 33918 33919 33920 33921 33922 33923 33924 33925 33926 33927 33928 33929 33930 33931 33932 33933 33934 33935 33936 33937 33938 33939 33940 33941 33942 33943 33944 33945 33946 33947 33948 33949 33950 33951 33952 33953 33954 33955 33956 33957 33958 33959 33960 33961 33962 33963 33964 33965 33966 33967 33968 33969 33970 33971 33972 33973 33974 33975 33976 33977 33978 33979 33980 33981 33982 33983 33984 33985 33986 33987 33988 33989 33990 33991 33992 33993 33994 33995 33996 33997 33998 33999 34000 34001 34002 34003 34004 34005 34006 34007 34008 34009 34010 34011 34012 34013 34014 34015 34016 34017 34018 34019 34020 34021 34022 34023 34024 34025 34026 34027 34028 34029 34030 34031 34032 34033 34034 34035 34036 34037 34038 34039 34040 34041 34042 34043 34044 34045 34046 34047 34048 34049 34050 34051 34052 34053 34054 34055 34056 34057 34058 34059 34060 34061 34062 34063 34064 34065 34066 34067 34068 34069 34070 34071 34072 34073 34074 34075 34076 34077 34078 34079 34080 34081 34082 34083 34084 34085 34086 34087 34088 34089 34090 34091 34092 34093 34094 34095 34096 34097 34098 34099 34100 34101 34102 34103 34104 34105 34106 34107 34108 34109 34110 34111 34112 34113 34114 34115 34116 34117 34118 34119 34120 34121 34122 34123 34124 34125 34126 34127 34128 34129 34130 34131 34132 34133 34134 34135 34136 34137 34138 34139 34140 34141 34142 34143 34144 34145 34146 34147 34148 34149 34150 34151 34152 34153 34154 34155 34156 34157 34158 34159 34160 34161 34162 34163 34164 34165 34166 34167 34168 34169 34170 34171 34172 34173 34174 34175 34176 34177 34178 34179 34180 34181 34182 34183 34184 34185 34186 34187 34188 34189 34190 34191 34192 34193 34194 34195 34196 34197 34198 34199 34200 34201 34202 34203 34204 34205 34206 34207 34208 34209 34210 34211 34212 34213 34214 34215 34216 34217 34218 34219 34220 34221 34222 34223 34224 34225 34226 34227 34228 34229 34230 34231 34232 34233 34234 34235 34236 34237 34238 34239 34240 34241 34242 34243 34244 34245 34246 34247 34248 34249 34250 34251 34252 34253 34254 34255 34256 34257 34258 34259 34260 34261 34262 34263 34264 34265 34266 34267 34268 34269 34270 34271 34272 34273 34274 34275 34276 34277 34278 34279 34280 34281 34282 34283 34284 34285 34286 34287 34288 34289 34290 34291 34292 34293 34294 34295 34296 34297 34298 34299 34300 34301 34302 34303 34304 34305 34306 34307 34308 34309 34310 34311 34312 34313 34314 34315 34316 34317 34318 34319 34320 34321 34322 34323 34324 34325 34326 34327 34328 34329 34330 34331 34332 34333 34334 34335 34336 34337 34338 34339 34340 34341 34342 34343 34344 34345 34346 34347 34348 34349 34350 34351 34352 34353 34354 34355 34356 34357 34358 34359 34360 34361 34362 34363 34364 34365 34366 34367 34368 34369 34370 34371 34372 34373 34374 34375 34376 34377 34378 34379 34380 34381 34382 34383 34384 34385 34386 34387 34388 34389 34390 34391 34392 34393 34394 34395 34396 34397 34398 34399 34400 34401 34402 34403 34404 34405 34406 34407 34408 34409 34410 34411 34412 34413 34414 34415 34416 34417 34418 34419 34420 34421 34422 34423 34424 34425 34426 34427 34428 34429 34430 34431 34432 34433 34434 34435 34436 34437 34438 34439 34440 34441 34442 34443 34444 34445 34446 34447 34448 34449 34450 34451 34452 34453 34454 34455 34456 34457 34458 34459 34460 34461 34462 34463 34464 34465 34466 34467 34468 34469 34470 34471 34472 34473 34474 34475 34476 34477 34478 34479 34480 34481 34482 34483 34484 34485 34486 34487 34488 34489 34490 34491 34492 34493 34494 34495 34496 34497 34498 34499 34500 34501 34502 34503 34504 34505 34506 34507 34508 34509 34510 34511 34512 34513 34514 34515 34516 34517 34518 34519 34520 34521 34522 34523 34524 34525 34526 34527 34528 34529 34530 34531 34532 34533 34534 34535 34536 34537 34538 34539 34540 34541 34542 34543 34544 34545 34546 34547 34548 34549 34550 34551 34552 34553 34554 34555 34556 34557 34558 34559 34560 34561 34562 34563 34564 34565 34566 34567 34568 34569 34570 34571 34572 34573 34574 34575 34576 34577 34578 34579 34580 34581 34582 34583 34584 34585 34586 34587 34588 34589 34590 34591 34592 34593 34594 34595 34596 34597 34598 34599 34600 34601 34602 34603 34604 34605 34606 34607 34608 34609 34610 34611 34612 34613 34614 34615 34616 34617 34618 34619 34620 34621 34622 34623 34624 34625 34626 34627 34628 34629 34630 34631 34632 34633 34634 34635 34636 34637 34638 34639 34640 34641 34642 34643 34644 34645 34646 34647 34648 34649 34650 34651 34652 34653 34654 34655 34656 34657 34658 34659 34660 34661 34662 34663 34664 34665 34666 34667 34668 34669 34670 34671 34672 34673 34674 34675 34676 34677 34678 34679 34680 34681 34682 34683 34684 34685 34686 34687 34688 34689 34690 34691 34692 34693 34694 34695 34696 34697 34698 34699 34700 34701 34702 34703 34704 34705 34706 34707 34708 34709 34710 34711 34712 34713 34714 34715 34716 34717 34718 34719 34720 34721 34722 34723 34724 34725 34726 34727 34728 34729 34730 34731 34732 34733 34734 34735 34736 34737 34738 34739 34740 34741 34742 34743 34744 34745 34746 34747 34748 34749 34750 34751 34752 34753 34754 34755 34756 34757 34758 34759 34760 34761 34762 34763 34764 34765 34766 34767 34768 34769 34770 34771 34772 34773 34774 34775 34776 34777 34778 34779 34780 34781 34782 34783 34784 34785 34786 34787 34788 34789 34790 34791 34792 34793 34794 34795 34796 34797 34798 34799 34800 34801 34802 34803 34804 34805 34806 34807 34808 34809 34810 34811 34812 34813 34814 34815 34816 34817 34818 34819 34820 34821 34822 34823 34824 34825 34826 34827 34828 34829 34830 34831 34832 34833 34834 34835 34836 34837 34838 34839 34840 34841 34842 34843 34844 34845 34846 34847 34848 34849 34850 34851 34852 34853 34854 34855 34856 34857 34858 34859 34860 34861 34862 34863 34864 34865 34866 34867 34868 34869 34870 34871 34872 34873 34874 34875 34876 34877 34878 34879 34880 34881 34882 34883 34884 34885 34886 34887 34888 34889 34890 34891 34892 34893 34894 34895 34896 34897 34898 34899 34900 34901 34902 34903 34904 34905 34906 34907 34908 34909 34910 34911 34912 34913 34914 34915 34916 34917 34918 34919 34920 34921 34922 34923 34924 34925 34926 34927 34928 34929 34930 34931 34932 34933 34934 34935 34936 34937 34938 34939 34940 34941 34942 34943 34944 34945 34946 34947 34948 34949 34950 34951 34952 34953 34954 34955 34956 34957 34958 34959 34960 34961 34962 34963 34964 34965 34966 34967 34968 34969 34970 34971 34972 34973 34974 34975 34976 34977 34978 34979 34980 34981 34982 34983 34984 34985 34986 34987 34988 34989 34990 34991 34992 34993 34994 34995 34996 34997 34998 34999 35000 35001 35002 35003 35004 35005 35006 35007 35008 35009 35010 35011 35012 35013 35014 35015 35016 35017 35018 35019 35020 35021 35022 35023 35024 35025 35026 35027 35028 35029 35030 35031 35032 35033 35034 35035 35036 35037 35038 35039 35040 35041 35042 35043 35044 35045 35046 35047 35048 35049 35050 35051 35052 35053 35054 35055 35056 35057 35058 35059 35060 35061 35062 35063 35064 35065 35066 35067 35068 35069 35070 35071 35072 35073 35074 35075 35076 35077 35078 35079 35080 35081 35082 35083 35084 35085 35086 35087 35088 35089 35090 35091 35092 35093 35094 35095 35096 35097 35098 35099 35100 35101 35102 35103 35104 35105 35106 35107 35108 35109 35110 35111 35112 35113 35114 35115 35116 35117 35118 35119 35120 35121 35122 35123 35124 35125 35126 35127 35128 35129 35130 35131 35132 35133 35134 35135 35136 35137 35138 35139 35140 35141 35142 35143 35144 35145 35146 35147 35148 35149 35150 35151 35152 35153 35154 35155 35156 35157 35158 35159 35160 35161 35162 35163 35164 35165 35166 35167 35168 35169 35170 35171 35172 35173 35174 35175 35176 35177 35178 35179 35180 35181 35182 35183 35184 35185 35186 35187 35188 35189 35190 35191 35192 35193 35194 35195 35196 35197 35198 35199 35200 35201 35202 35203 35204 35205 35206 35207 35208 35209 35210 35211 35212 35213 35214 35215 35216 35217 35218 35219 35220 35221 35222 35223 35224 35225 35226 35227 35228 35229 35230 35231 35232 35233 35234 35235 35236 35237 35238 35239 35240 35241 35242 35243 35244 35245 35246 35247 35248 35249 35250 35251 35252 35253 35254 35255 35256 35257 35258 35259 35260 35261 35262 35263 35264 35265 35266 35267 35268 35269 35270 35271 35272 35273 35274 35275 35276 35277 35278 35279 35280 35281 35282 35283 35284 35285 35286 35287 35288 35289 35290 35291 35292 35293 35294 35295 35296 35297 35298 35299 35300 35301 35302 35303 35304 35305 35306 35307 35308 35309 35310 35311 35312 35313 35314 35315 35316 35317 35318 35319 35320 35321 35322 35323 35324 35325 35326 35327 35328 35329 35330 35331 35332 35333 35334 35335 35336 35337 35338 35339 35340 35341 35342 35343 35344 35345 35346 35347 35348 35349 35350 35351 35352 35353 35354 35355 35356 35357 35358 35359 35360 35361 35362 35363 35364 35365 35366 35367 35368 35369 35370 35371 35372 35373 35374 35375 35376 35377 35378 35379 35380 35381 35382 35383 35384 35385 35386 35387 35388 35389 35390 35391 35392 35393 35394 35395 35396 35397 35398 35399 35400 35401 35402 35403 35404 35405 35406 35407 35408 35409 35410 35411 35412 35413 35414 35415 35416 35417 35418 35419 35420 35421 35422 35423 35424 35425 35426 35427 35428 35429 35430 35431 35432 35433 35434 35435 35436 35437 35438 35439 35440 35441 35442 35443 35444 35445 35446 35447 35448 35449 35450 35451 35452 35453 35454 35455 35456 35457 35458 35459 35460 35461 35462 35463 35464 35465 35466 35467 35468 35469 35470 35471 35472 35473 35474 35475 35476 35477 35478 35479 35480 35481 35482 35483 35484 35485 35486 35487 35488 35489 35490 35491 35492 35493 35494 35495 35496 35497 35498 35499 35500 35501 35502 35503 35504 35505 35506 35507 35508 35509 35510 35511 35512 35513 35514 35515 35516 35517 35518 35519 35520 35521 35522 35523 35524 35525 35526 35527 35528 35529 35530 35531 35532 35533 35534 35535 35536 35537 35538 35539 35540 35541 35542 35543 35544 35545 35546 35547 35548 35549 35550 35551 35552 35553 35554 35555 35556 35557 35558 35559 35560 35561 35562 35563 35564 35565 35566 35567 35568 35569 35570 35571 35572 35573 35574 35575 35576 35577 35578 35579 35580 35581 35582 35583 35584 35585 35586 35587 35588 35589 35590 35591 35592 35593 35594 35595 35596 35597 35598 35599 35600 35601 35602 35603 35604 35605 35606 35607 35608 35609 35610 35611 35612 35613 35614 35615 35616 35617 35618 35619 35620 35621 35622 35623 35624 35625 35626 35627 35628 35629 35630 35631 35632 35633 35634 35635 35636 35637 35638 35639 35640 35641 35642 35643 35644 35645 35646 35647 35648 35649 35650 35651 35652 35653 35654 35655 35656 35657 35658 35659 35660 35661 35662 35663 35664 35665 35666 35667 35668 35669 35670 35671 35672 35673 35674 35675 35676 35677 35678 35679 35680 35681 35682 35683 35684 35685 35686 35687 35688 35689 35690 35691 35692 35693 35694 35695 35696 35697 35698 35699 35700 35701 35702 35703 35704 35705 35706 35707 35708 35709 35710 35711 35712 35713 35714 35715 35716 35717 35718 35719 35720 35721 35722 35723 35724 35725 35726 35727 35728 35729 35730 35731 35732 35733 35734 35735 35736 35737 35738 35739 35740 35741 35742 35743 35744 35745 35746 35747 35748 35749 35750 35751 35752 35753 35754 35755 35756 35757 35758 35759 35760 35761 35762 35763 35764 35765 35766 35767 35768 35769 35770 35771 35772 35773 35774 35775 35776 35777 35778 35779 35780 35781 35782 35783 35784 35785 35786 35787 35788 35789 35790 35791 35792 35793 35794 35795 35796 35797 35798 35799 35800 35801 35802 35803 35804 35805 35806 35807 35808 35809 35810 35811 35812 35813 35814 35815 35816 35817 35818 35819 35820 35821 35822 35823 35824 35825 35826 35827 35828 35829 35830 35831 35832 35833 35834 35835 35836 35837 35838 35839 35840 35841 35842 35843 35844 35845 35846 35847 35848 35849 35850 35851 35852 35853 35854 35855 35856 35857 35858 35859 35860 35861 35862 35863 35864 35865 35866 35867 35868 35869 35870 35871 35872 35873 35874 35875 35876 35877 35878 35879 35880 35881 35882 35883 35884 35885 35886 35887 35888 35889 35890 35891 35892 35893 35894 35895 35896 35897 35898 35899 35900 35901 35902 35903 35904 35905 35906 35907 35908 35909 35910 35911 35912 35913 35914 35915 35916 35917 35918 35919 35920 35921 35922 35923 35924 35925 35926 35927 35928 35929 35930 35931 35932 35933 35934 35935 35936 35937 35938 35939 35940 35941 35942 35943 35944 35945 35946 35947 35948 35949 35950 35951 35952 35953 35954 35955 35956 35957 35958 35959 35960 35961 35962 35963 35964 35965 35966 35967 35968 35969 35970 35971 35972 35973 35974 35975 35976 35977 35978 35979 35980 35981 35982 35983 35984 35985 35986 35987 35988 35989 35990 35991 35992 35993 35994 35995 35996 35997 35998 35999 36000 36001 36002 36003 36004 36005 36006 36007 36008 36009 36010 36011 36012 36013 36014 36015 36016 36017 36018 36019 36020 36021 36022 36023 36024 36025 36026 36027 36028 36029 36030 36031 36032 36033 36034 36035 36036 36037 36038 36039 36040 36041 36042 36043 36044 36045 36046 36047 36048 36049 36050 36051 36052 36053 36054 36055 36056 36057 36058 36059 36060 36061 36062 36063 36064 36065 36066 36067 36068 36069 36070 36071 36072 36073 36074 36075 36076 36077 36078 36079 36080 36081 36082 36083 36084 36085 36086 36087 36088 36089 36090 36091 36092 36093 36094 36095 36096 36097 36098 36099 36100 36101 36102 36103 36104 36105 36106 36107 36108 36109 36110 36111 36112 36113 36114 36115 36116 36117 36118 36119 36120 36121 36122 36123 36124 36125 36126 36127 36128 36129 36130 36131 36132 36133 36134 36135 36136 36137 36138 36139 36140 36141 36142 36143 36144 36145 36146 36147 36148 36149 36150 36151 36152 36153 36154 36155 36156 36157 36158 36159 36160 36161 36162 36163 36164 36165 36166 36167 36168 36169 36170 36171 36172 36173 36174 36175 36176 36177 36178 36179 36180 36181 36182 36183 36184 36185 36186 36187 36188 36189 36190 36191 36192 36193 36194 36195 36196 36197 36198 36199 36200 36201 36202 36203 36204 36205 36206 36207 36208 36209 36210 36211 36212 36213 36214 36215 36216 36217 36218 36219 36220 36221 36222 36223 36224 36225 36226 36227 36228 36229 36230 36231 36232 36233 36234 36235 36236 36237 36238 36239 36240 36241 36242 36243 36244 36245 36246 36247 36248 36249 36250 36251 36252 36253 36254 36255 36256 36257 36258 36259 36260 36261 36262 36263 36264 36265 36266 36267 36268 36269 36270 36271 36272 36273 36274 36275 36276 36277 36278 36279 36280 36281 36282 36283 36284 36285 36286 36287 36288 36289 36290 36291 36292 36293 36294 36295 36296 36297 36298 36299 36300 36301 36302 36303 36304 36305 36306 36307 36308 36309 36310 36311 36312 36313 36314 36315 36316 36317 36318 36319 36320 36321 36322 36323 36324 36325 36326 36327 36328 36329 36330 36331 36332 36333 36334 36335 36336 36337 36338 36339 36340 36341 36342 36343 36344 36345 36346 36347 36348 36349 36350 36351 36352 36353 36354 36355 36356 36357 36358 36359 36360 36361 36362 36363 36364 36365 36366 36367 36368 36369 36370 36371 36372 36373 36374 36375 36376 36377 36378 36379 36380 36381 36382 36383 36384 36385 36386 36387 36388 36389 36390 36391 36392 36393 36394 36395 36396 36397 36398 36399 36400 36401 36402 36403 36404 36405 36406 36407 36408 36409 36410 36411 36412 36413 36414 36415 36416 36417 36418 36419 36420 36421 36422 36423 36424 36425 36426 36427 36428 36429 36430 36431 36432 36433 36434 36435 36436 36437 36438 36439 36440 36441 36442 36443 36444 36445 36446 36447 36448 36449 36450 36451 36452 36453 36454 36455 36456 36457 36458 36459 36460 36461 36462 36463 36464 36465 36466 36467 36468 36469 36470 36471 36472 36473 36474 36475 36476 36477 36478 36479 36480 36481 36482 36483 36484 36485 36486 36487 36488 36489 36490 36491 36492 36493 36494 36495 36496 36497 36498 36499 36500 36501 36502 36503 36504 36505 36506 36507 36508 36509 36510 36511 36512 36513 36514 36515 36516 36517 36518 36519 36520 36521 36522 36523 36524 36525 36526 36527 36528 36529 36530 36531 36532 36533 36534 36535 36536 36537 36538 36539 36540 36541 36542 36543 36544 36545 36546 36547 36548 36549 36550 36551 36552 36553 36554 36555 36556 36557 36558 36559 36560 36561 36562 36563 36564 36565 36566 36567 36568 36569 36570 36571 36572 36573 36574 36575 36576 36577 36578 36579 36580 36581 36582 36583 36584 36585 36586 36587 36588 36589 36590 36591 36592 36593 36594 36595 36596 36597 36598 36599 36600 36601 36602 36603 36604 36605 36606 36607 36608 36609 36610 36611 36612 36613 36614 36615 36616 36617 36618 36619 36620 36621 36622 36623 36624 36625 36626 36627 36628 36629 36630 36631 36632 36633 36634 36635 36636 36637 36638 36639 36640 36641 36642 36643 36644 36645 36646 36647 36648 36649 36650 36651 36652 36653 36654 36655 36656 36657 36658 36659 36660 36661 36662 36663 36664 36665 36666 36667 36668 36669 36670 36671 36672 36673 36674 36675 36676 36677 36678 36679 36680 36681 36682 36683 36684 36685 36686 36687 36688 36689 36690 36691 36692 36693 36694 36695 36696 36697 36698 36699 36700 36701 36702 36703 36704 36705 36706 36707 36708 36709 36710 36711 36712 36713 36714 36715 36716 36717 36718 36719 36720 36721 36722 36723 36724 36725 36726 36727 36728 36729 36730 36731 36732 36733 36734 36735 36736 36737 36738 36739 36740 36741 36742 36743 36744 36745 36746 36747 36748 36749 36750 36751 36752 36753 36754 36755 36756 36757 36758 36759 36760 36761 36762 36763 36764 36765 36766 36767 36768 36769 36770 36771 36772 36773 36774 36775 36776 36777 36778 36779 36780 36781 36782 36783 36784 36785 36786 36787 36788 36789 36790 36791 36792 36793 36794 36795 36796 36797 36798 36799 36800 36801 36802 36803 36804 36805 36806 36807 36808 36809 36810 36811 36812 36813 36814 36815 36816 36817 36818 36819 36820 36821 36822 36823 36824 36825 36826 36827 36828 36829 36830 36831 36832 36833 36834 36835 36836 36837 36838 36839 36840 36841 36842 36843 36844 36845 36846 36847 36848 36849 36850 36851 36852 36853 36854 36855 36856 36857 36858 36859 36860 36861 36862 36863 36864 36865 36866 36867 36868 36869 36870 36871 36872 36873 36874 36875 36876 36877 36878 36879 36880 36881 36882 36883 36884 36885 36886 36887 36888 36889 36890 36891 36892 36893 36894 36895 36896 36897 36898 36899 36900 36901 36902 36903 36904 36905 36906 36907 36908 36909 36910 36911 36912 36913 36914 36915 36916 36917 36918 36919 36920 36921 36922 36923 36924 36925 36926 36927 36928 36929 36930 36931 36932 36933 36934 36935 36936 36937 36938 36939 36940 36941 36942 36943 36944 36945 36946 36947 36948 36949 36950 36951 36952 36953 36954 36955 36956 36957 36958 36959 36960 36961 36962 36963 36964 36965 36966 36967 36968 36969 36970 36971 36972 36973 36974 36975 36976 36977 36978 36979 36980 36981 36982 36983 36984 36985 36986 36987 36988 36989 36990 36991 36992 36993 36994 36995 36996 36997 36998 36999 37000 37001 37002 37003 37004 37005 37006 37007 37008 37009 37010 37011 37012 37013 37014 37015 37016 37017 37018 37019 37020 37021 37022 37023 37024 37025 37026 37027 37028 37029 37030 37031 37032 37033 37034 37035 37036 37037 37038 37039 37040 37041 37042 37043 37044 37045 37046 37047 37048 37049 37050 37051 37052 37053 37054 37055 37056 37057 37058 37059 37060 37061 37062 37063 37064 37065 37066 37067 37068 37069 37070 37071 37072 37073 37074 37075 37076 37077 37078 37079 37080 37081 37082 37083 37084 37085 37086 37087 37088 37089 37090 37091 37092 37093 37094 37095 37096 37097 37098 37099 37100 37101 37102 37103 37104 37105 37106 37107 37108 37109 37110 37111 37112 37113 37114 37115 37116 37117 37118 37119 37120 37121 37122 37123 37124 37125 37126 37127 37128 37129 37130 37131 37132 37133 37134 37135 37136 37137 37138 37139 37140 37141 37142 37143 37144 37145 37146 37147 37148 37149 37150 37151 37152 37153 37154 37155 37156 37157 37158 37159 37160 37161 37162 37163 37164 37165 37166 37167 37168 37169 37170 37171 37172 37173 37174 37175 37176 37177 37178 37179 37180 37181 37182 37183 37184 37185 37186 37187 37188 37189 37190 37191 37192 37193 37194 37195 37196 37197 37198 37199 37200 37201 37202 37203 37204 37205 37206 37207 37208 37209 37210 37211 37212 37213 37214 37215 37216 37217 37218 37219 37220 37221 37222 37223 37224 37225 37226 37227 37228 37229 37230 37231 37232 37233 37234 37235 37236 37237 37238 37239 37240 37241 37242 37243 37244 37245 37246 37247 37248 37249 37250 37251 37252 37253 37254 37255 37256 37257 37258 37259 37260 37261 37262 37263 37264 37265 37266 37267 37268 37269 37270 37271 37272 37273 37274 37275 37276 37277 37278 37279 37280 37281 37282 37283 37284 37285 37286 37287 37288 37289 37290 37291 37292 37293 37294 37295 37296 37297 37298 37299 37300 37301 37302 37303 37304 37305 37306 37307 37308 37309 37310 37311 37312 37313 37314 37315 37316 37317 37318 37319 37320 37321 37322 37323 37324 37325 37326 37327 37328 37329 37330 37331 37332 37333 37334 37335 37336 37337 37338 37339 37340 37341 37342 37343 37344 37345 37346 37347 37348 37349 37350 37351 37352 37353 37354 37355 37356 37357 37358 37359 37360 37361 37362 37363 37364 37365 37366 37367 37368 37369 37370 37371 37372 37373 37374 37375 37376 37377 37378 37379 37380 37381 37382 37383 37384 37385 37386 37387 37388 37389 37390 37391 37392 37393 37394 37395 37396 37397 37398 37399 37400 37401 37402 37403 37404 37405 37406 37407 37408 37409 37410 37411 37412 37413 37414 37415 37416 37417 37418 37419 37420 37421 37422 37423 37424 37425 37426 37427 37428 37429 37430 37431 37432 37433 37434 37435 37436 37437 37438 37439 37440 37441 37442 37443 37444 37445 37446 37447 37448 37449 37450 37451 37452 37453 37454 37455 37456 37457 37458 37459 37460 37461 37462 37463 37464 37465 37466 37467 37468 37469 37470 37471 37472 37473 37474 37475 37476 37477 37478 37479 37480 37481 37482 37483 37484 37485 37486 37487 37488 37489 37490 37491 37492 37493 37494 37495 37496 37497 37498 37499 37500 37501 37502 37503 37504 37505 37506 37507 37508 37509 37510 37511 37512 37513 37514 37515 37516 37517 37518 37519 37520 37521 37522 37523 37524 37525 37526 37527 37528 37529 37530 37531 37532 37533 37534 37535 37536 37537 37538 37539 37540 37541 37542 37543 37544 37545 37546 37547 37548 37549 37550 37551 37552 37553 37554 37555 37556 37557 37558 37559 37560 37561 37562 37563 37564 37565 37566 37567 37568 37569 37570 37571 37572 37573 37574 37575 37576 37577 37578 37579 37580 37581 37582 37583 37584 37585 37586 37587 37588 37589 37590 37591 37592 37593 37594 37595 37596 37597 37598 37599 37600 37601 37602 37603 37604 37605 37606 37607 37608 37609 37610 37611 37612 37613 37614 37615 37616 37617 37618 37619 37620 37621 37622 37623 37624 37625 37626 37627 37628 37629 37630 37631 37632 37633 37634 37635 37636 37637 37638 37639 37640 37641 37642 37643 37644 37645 37646 37647 37648 37649 37650 37651 37652 37653 37654 37655 37656 37657 37658 37659 37660 37661 37662 37663 37664 37665 37666 37667 37668 37669 37670 37671 37672 37673 37674 37675 37676 37677 37678 37679 37680 37681 37682 37683 37684 37685 37686 37687 37688 37689 37690 37691 37692 37693 37694 37695 37696 37697 37698 37699 37700 37701 37702 37703 37704 37705 37706 37707 37708 37709 37710 37711 37712 37713 37714 37715 37716 37717 37718 37719 37720 37721 37722 37723 37724 37725 37726 37727 37728 37729 37730 37731 37732 37733 37734 37735 37736 37737 37738 37739 37740 37741 37742 37743 37744 37745 37746 37747 37748 37749 37750 37751 37752 37753 37754 37755 37756 37757 37758 37759 37760 37761 37762 37763 37764 37765 37766 37767 37768 37769 37770 37771 37772 37773 37774 37775 37776 37777 37778 37779 37780 37781 37782 37783 37784 37785 37786 37787 37788 37789 37790 37791 37792 37793 37794 37795 37796 37797 37798 37799 37800 37801 37802 37803 37804 37805 37806 37807 37808 37809 37810 37811 37812 37813 37814 37815 37816 37817 37818 37819 37820 37821 37822 37823 37824 37825 37826 37827 37828 37829 37830 37831 37832 37833 37834 37835 37836 37837 37838 37839 37840 37841 37842 37843 37844 37845 37846 37847 37848 37849 37850 37851 37852 37853 37854 37855 37856 37857 37858 37859 37860 37861 37862 37863 37864 37865 37866 37867 37868 37869 37870 37871 37872 37873 37874 37875 37876 37877 37878 37879 37880 37881 37882 37883 37884 37885 37886 37887 37888 37889 37890 37891 37892 37893 37894 37895 37896 37897 37898 37899 37900 37901 37902 37903 37904 37905 37906 37907 37908 37909 37910 37911 37912 37913 37914 37915 37916 37917 37918 37919 37920 37921 37922 37923 37924 37925 37926 37927 37928 37929 37930 37931 37932 37933 37934 37935 37936 37937 37938 37939 37940 37941 37942 37943 37944 37945 37946 37947 37948 37949 37950 37951 37952 37953 37954 37955 37956 37957 37958 37959 37960 37961 37962 37963 37964 37965 37966 37967 37968 37969 37970 37971 37972 37973 37974 37975 37976 37977 37978 37979 37980 37981 37982 37983 37984 37985 37986 37987 37988 37989 37990 37991 37992 37993 37994 37995 37996 37997 37998 37999 38000 38001 38002 38003 38004 38005 38006 38007 38008 38009 38010 38011 38012 38013 38014 38015 38016 38017 38018 38019 38020 38021 38022 38023 38024 38025 38026 38027 38028 38029 38030 38031 38032 38033 38034 38035 38036 38037 38038 38039 38040 38041 38042 38043 38044 38045 38046 38047 38048 38049 38050 38051 38052 38053 38054 38055 38056 38057 38058 38059 38060 38061 38062 38063 38064 38065 38066 38067 38068 38069 38070 38071 38072 38073 38074 38075 38076 38077 38078 38079 38080 38081 38082 38083 38084 38085 38086 38087 38088 38089 38090 38091 38092 38093 38094 38095 38096 38097 38098 38099 38100 38101 38102 38103 38104 38105 38106 38107 38108 38109 38110 38111 38112 38113 38114 38115 38116 38117 38118 38119 38120 38121 38122 38123 38124 38125 38126 38127 38128 38129 38130 38131 38132 38133 38134 38135 38136 38137 38138 38139 38140 38141 38142 38143 38144 38145 38146 38147 38148 38149 38150 38151 38152 38153 38154 38155 38156 38157 38158 38159 38160 38161 38162 38163 38164 38165 38166 38167 38168 38169 38170 38171 38172 38173 38174 38175 38176 38177 38178 38179 38180 38181 38182 38183 38184 38185 38186 38187 38188 38189 38190 38191 38192 38193 38194 38195 38196 38197 38198 38199 38200 38201 38202 38203 38204 38205 38206 38207 38208 38209 38210 38211 38212 38213 38214 38215 38216 38217 38218 38219 38220 38221 38222 38223 38224 38225 38226 38227 38228 38229 38230 38231 38232 38233 38234 38235 38236 38237 38238 38239 38240 38241 38242 38243 38244 38245 38246 38247 38248 38249 38250 38251 38252 38253 38254 38255 38256 38257 38258 38259 38260 38261 38262 38263 38264 38265 38266 38267 38268 38269 38270 38271 38272 38273 38274 38275 38276 38277 38278 38279 38280 38281 38282 38283 38284 38285 38286 38287 38288 38289 38290 38291 38292 38293 38294 38295 38296 38297 38298 38299 38300 38301 38302 38303 38304 38305 38306 38307 38308 38309 38310 38311 38312 38313 38314 38315 38316 38317 38318 38319 38320 38321 38322 38323 38324 38325 38326 38327 38328 38329 38330 38331 38332 38333 38334 38335 38336 38337 38338 38339 38340 38341 38342 38343 38344 38345 38346 38347 38348 38349 38350 38351 38352 38353 38354 38355 38356 38357 38358 38359 38360 38361 38362 38363 38364 38365 38366 38367 38368 38369 38370 38371 38372 38373 38374 38375 38376 38377 38378 38379 38380 38381 38382 38383 38384 38385 38386 38387 38388 38389 38390 38391 38392 38393 38394 38395 38396 38397 38398 38399 38400 38401 38402 38403 38404 38405 38406 38407 38408 38409 38410 38411 38412 38413 38414 38415 38416 38417 38418 38419 38420 38421 38422 38423 38424 38425 38426 38427 38428 38429 38430 38431 38432 38433 38434 38435 38436 38437 38438 38439 38440 38441 38442 38443 38444 38445 38446 38447 38448 38449 38450 38451 38452 38453 38454 38455 38456 38457 38458 38459 38460 38461 38462 38463 38464 38465 38466 38467 38468 38469 38470 38471 38472 38473 38474 38475 38476 38477 38478 38479 38480 38481 38482 38483 38484 38485 38486 38487 38488 38489 38490 38491 38492 38493 38494 38495 38496 38497 38498 38499 38500 38501 38502 38503 38504 38505 38506 38507 38508 38509 38510 38511 38512 38513 38514 38515 38516 38517 38518 38519 38520 38521 38522 38523 38524 38525 38526 38527 38528 38529 38530 38531 38532 38533 38534 38535 38536 38537 38538 38539 38540 38541 38542 38543 38544 38545 38546 38547 38548 38549 38550 38551 38552 38553 38554 38555 38556 38557 38558 38559 38560 38561 38562 38563 38564 38565 38566 38567 38568 38569 38570 38571 38572 38573 38574 38575 38576 38577 38578 38579 38580 38581 38582 38583 38584 38585 38586 38587 38588 38589 38590 38591 38592 38593 38594 38595 38596 38597 38598 38599 38600 38601 38602 38603 38604 38605 38606 38607 38608 38609 38610 38611 38612 38613 38614 38615 38616 38617 38618 38619 38620 38621 38622 38623 38624 38625 38626 38627 38628 38629 38630 38631 38632 38633 38634 38635 38636 38637 38638 38639 38640 38641 38642 38643 38644 38645 38646 38647 38648 38649 38650 38651 38652 38653 38654 38655 38656 38657 38658 38659 38660 38661 38662 38663 38664 38665 38666 38667 38668 38669 38670 38671 38672 38673 38674 38675 38676 38677 38678 38679 38680 38681 38682 38683 38684 38685 38686 38687 38688 38689 38690 38691 38692 38693 38694 38695 38696 38697 38698 38699 38700 38701 38702 38703 38704 38705 38706 38707 38708 38709 38710 38711 38712 38713 38714 38715 38716 38717 38718 38719 38720 38721 38722 38723 38724 38725 38726 38727 38728 38729 38730 38731 38732 38733 38734 38735 38736 38737 38738 38739 38740 38741 38742 38743 38744 38745 38746 38747 38748 38749 38750 38751 38752 38753 38754 38755 38756 38757 38758 38759 38760 38761 38762 38763 38764 38765 38766 38767 38768 38769 38770 38771 38772 38773 38774 38775 38776 38777 38778 38779 38780 38781 38782 38783 38784 38785 38786 38787 38788 38789 38790 38791 38792 38793 38794 38795 38796 38797 38798 38799 38800 38801 38802 38803 38804 38805 38806 38807 38808 38809 38810 38811 38812 38813 38814 38815 38816 38817 38818 38819 38820 38821 38822 38823 38824 38825 38826 38827 38828 38829 38830 38831 38832 38833 38834 38835 38836 38837 38838 38839 38840 38841 38842 38843 38844 38845 38846 38847 38848 38849 38850 38851 38852 38853 38854 38855 38856 38857 38858 38859 38860 38861 38862 38863 38864 38865 38866 38867 38868 38869 38870 38871 38872 38873 38874 38875 38876 38877 38878 38879 38880 38881 38882 38883 38884 38885 38886 38887 38888 38889 38890 38891 38892 38893 38894 38895 38896 38897 38898 38899 38900 38901 38902 38903 38904 38905 38906 38907 38908 38909 38910 38911 38912 38913 38914 38915 38916 38917 38918 38919 38920 38921 38922 38923 38924 38925 38926 38927 38928 38929 38930 38931 38932 38933 38934 38935 38936 38937 38938 38939 38940 38941 38942 38943 38944 38945 38946 38947 38948 38949 38950 38951 38952 38953 38954 38955 38956 38957 38958 38959 38960 38961 38962 38963 38964 38965 38966 38967 38968 38969 38970 38971 38972 38973 38974 38975 38976 38977 38978 38979 38980 38981 38982 38983 38984 38985 38986 38987 38988 38989 38990 38991 38992 38993 38994 38995 38996 38997 38998 38999 39000 39001 39002 39003 39004 39005 39006 39007 39008 39009 39010 39011 39012 39013 39014 39015 39016 39017 39018 39019 39020 39021 39022 39023 39024 39025 39026 39027 39028 39029 39030 39031 39032 39033 39034 39035 39036 39037 39038 39039 39040 39041 39042 39043 39044 39045 39046 39047 39048 39049 39050 39051 39052 39053 39054 39055 39056 39057 39058 39059 39060 39061 39062 39063 39064 39065 39066 39067 39068 39069 39070 39071 39072 39073 39074 39075 39076 39077 39078 39079 39080 39081 39082 39083 39084 39085 39086 39087 39088 39089 39090 39091 39092 39093 39094 39095 39096 39097 39098 39099 39100 39101 39102 39103 39104 39105 39106 39107 39108 39109 39110 39111 39112 39113 39114 39115 39116 39117 39118 39119 39120 39121 39122 39123 39124 39125 39126 39127 39128 39129 39130 39131 39132 39133 39134 39135 39136 39137 39138 39139 39140 39141 39142 39143 39144 39145 39146 39147 39148 39149 39150 39151 39152 39153 39154 39155 39156 39157 39158 39159 39160 39161 39162 39163 39164 39165 39166 39167 39168 39169 39170 39171 39172 39173 39174 39175 39176 39177 39178 39179 39180 39181 39182 39183 39184 39185 39186 39187 39188 39189 39190 39191 39192 39193 39194 39195 39196 39197 39198 39199 39200 39201 39202 39203 39204 39205 39206 39207 39208 39209 39210 39211 39212 39213 39214 39215 39216 39217 39218 39219 39220 39221 39222 39223 39224 39225 39226 39227 39228 39229 39230 39231 39232 39233 39234 39235 39236 39237 39238 39239 39240 39241 39242 39243 39244 39245 39246 39247 39248 39249 39250 39251 39252 39253 39254 39255 39256 39257 39258 39259 39260 39261 39262 39263 39264 39265 39266 39267 39268 39269 39270 39271 39272 39273 39274 39275 39276 39277 39278 39279 39280 39281 39282 39283 39284 39285 39286 39287 39288 39289 39290 39291 39292 39293 39294 39295 39296 39297 39298 39299 39300 39301 39302 39303 39304 39305 39306 39307 39308 39309 39310 39311 39312 39313 39314 39315 39316 39317 39318 39319 39320 39321 39322 39323 39324 39325 39326 39327 39328 39329 39330 39331 39332 39333 39334 39335 39336 39337 39338 39339 39340 39341 39342 39343 39344 39345 39346 39347 39348 39349 39350 39351 39352 39353 39354 39355 39356 39357 39358 39359 39360 39361 39362 39363 39364 39365 39366 39367 39368 39369 39370 39371 39372 39373 39374 39375 39376 39377 39378 39379 39380 39381 39382 39383 39384 39385 39386 39387 39388 39389 39390 39391 39392 39393 39394 39395 39396 39397 39398 39399 39400 39401 39402 39403 39404 39405 39406 39407 39408 39409 39410 39411 39412 39413 39414 39415 39416 39417 39418 39419 39420 39421 39422 39423 39424 39425 39426 39427 39428 39429 39430 39431 39432 39433 39434 39435 39436 39437 39438 39439 39440 39441 39442 39443 39444 39445 39446 39447 39448 39449 39450 39451 39452 39453 39454 39455 39456 39457 39458 39459 39460 39461 39462 39463 39464 39465 39466 39467 39468 39469 39470 39471 39472 39473 39474 39475 39476 39477 39478 39479 39480 39481 39482 39483 39484 39485 39486 39487 39488 39489 39490 39491 39492 39493 39494 39495 39496 39497 39498 39499 39500 39501 39502 39503 39504 39505 39506 39507 39508 39509 39510 39511 39512 39513 39514 39515 39516 39517 39518 39519 39520 39521 39522 39523 39524 39525 39526 39527 39528 39529 39530 39531 39532 39533 39534 39535 39536 39537 39538 39539 39540 39541 39542 39543 39544 39545 39546 39547 39548 39549 39550 39551 39552 39553 39554 39555 39556 39557 39558 39559 39560 39561 39562 39563 39564 39565 39566 39567 39568 39569 39570 39571 39572 39573 39574 39575 39576 39577 39578 39579 39580 39581 39582 39583 39584 39585 39586 39587 39588 39589 39590 39591 39592 39593 39594 39595 39596 39597 39598 39599 39600 39601 39602 39603 39604 39605 39606 39607 39608 39609 39610 39611 39612 39613 39614 39615 39616 39617 39618 39619 39620 39621 39622 39623 39624 39625 39626 39627 39628 39629 39630 39631 39632 39633 39634 39635 39636 39637 39638 39639 39640 39641 39642 39643 39644 39645 39646 39647 39648 39649 39650 39651 39652 39653 39654 39655 39656 39657 39658 39659 39660 39661 39662 39663 39664 39665 39666 39667 39668 39669 39670 39671 39672 39673 39674 39675 39676 39677 39678 39679 39680 39681 39682 39683 39684 39685 39686 39687 39688 39689 39690 39691 39692 39693 39694 39695 39696 39697 39698 39699 39700 39701 39702 39703 39704 39705 39706 39707 39708 39709 39710 39711 39712 39713 39714 39715 39716 39717 39718 39719 39720 39721 39722 39723 39724 39725 39726 39727 39728 39729 39730 39731 39732 39733 39734 39735 39736 39737 39738 39739 39740 39741 39742 39743 39744 39745 39746 39747 39748 39749 39750 39751 39752 39753 39754 39755 39756 39757 39758 39759 39760 39761 39762 39763 39764 39765 39766 39767 39768 39769 39770 39771 39772 39773 39774 39775 39776 39777 39778 39779 39780 39781 39782 39783 39784 39785 39786 39787 39788 39789 39790 39791 39792 39793 39794 39795 39796 39797 39798 39799 39800 39801 39802 39803 39804 39805 39806 39807 39808 39809 39810 39811 39812 39813 39814 39815 39816 39817 39818 39819 39820 39821 39822 39823 39824 39825 39826 39827 39828 39829 39830 39831 39832 39833 39834 39835 39836 39837 39838 39839 39840 39841 39842 39843 39844 39845 39846 39847 39848 39849 39850 39851 39852 39853 39854 39855 39856 39857 39858 39859 39860 39861 39862 39863 39864 39865 39866 39867 39868 39869 39870 39871 39872 39873 39874 39875 39876 39877 39878 39879 39880 39881 39882 39883 39884 39885 39886 39887 39888 39889 39890 39891 39892 39893 39894 39895 39896 39897 39898 39899 39900 39901 39902 39903 39904 39905 39906 39907 39908 39909 39910 39911 39912 39913 39914 39915 39916 39917 39918 39919 39920 39921 39922 39923 39924 39925 39926 39927 39928 39929 39930 39931 39932 39933 39934 39935 39936 39937 39938 39939 39940 39941 39942 39943 39944 39945 39946 39947 39948 39949 39950 39951 39952 39953 39954 39955 39956 39957 39958 39959 39960 39961 39962 39963 39964 39965 39966 39967 39968 39969 39970 39971 39972 39973 39974 39975 39976 39977 39978 39979 39980 39981 39982 39983 39984 39985 39986 39987 39988 39989 39990 39991 39992 39993 39994 39995 39996 39997 39998 39999 40000 40001 40002 40003 40004 40005 40006 40007 40008 40009 40010 40011 40012 40013 40014 40015 40016 40017 40018 40019 40020 40021 40022 40023 40024 40025 40026 40027 40028 40029 40030 40031 40032 40033 40034 40035 40036 40037 40038 40039 40040 40041 40042 40043 40044 40045 40046 40047 40048 40049 40050 40051 40052 40053 40054 40055 40056 40057 40058 40059 40060 40061 40062 40063 40064 40065 40066 40067 40068 40069 40070 40071 40072 40073 40074 40075 40076 40077 40078 40079 40080 40081 40082 40083 40084 40085 40086 40087 40088 40089 40090 40091 40092 40093 40094 40095 40096 40097 40098 40099 40100 40101 40102 40103 40104 40105 40106 40107 40108 40109 40110 40111 40112 40113 40114 40115 40116 40117 40118 40119 40120 40121 40122 40123 40124 40125 40126 40127 40128 40129 40130 40131 40132 40133 40134 40135 40136 40137 40138 40139 40140 40141 40142 40143 40144 40145 40146 40147 40148 40149 40150 40151 40152 40153 40154 40155 40156 40157 40158 40159 40160 40161 40162 40163 40164 40165 40166 40167 40168 40169 40170 40171 40172 40173 40174 40175 40176 40177 40178 40179 40180 40181 40182 40183 40184 40185 40186 40187 40188 40189 40190 40191 40192 40193 40194 40195 40196 40197 40198 40199 40200 40201 40202 40203 40204 40205 40206 40207 40208 40209 40210 40211 40212 40213 40214 40215 40216 40217 40218 40219 40220 40221 40222 40223 40224 40225 40226 40227 40228 40229 40230 40231 40232 40233 40234 40235 40236 40237 40238 40239 40240 40241 40242 40243 40244 40245 40246 40247 40248 40249 40250 40251 40252 40253 40254 40255 40256 40257 40258 40259 40260 40261 40262 40263 40264 40265 40266 40267 40268 40269 40270 40271 40272 40273 40274 40275 40276 40277 40278 40279 40280 40281 40282 40283 40284 40285 40286 40287 40288 40289 40290 40291 40292 40293 40294 40295 40296 40297 40298 40299 40300 40301 40302 40303 40304 40305 40306 40307 40308 40309 40310 40311 40312 40313 40314 40315 40316 40317 40318 40319 40320 40321 40322 40323 40324 40325 40326 40327 40328 40329 40330 40331 40332 40333 40334 40335 40336 40337 40338 40339 40340 40341 40342 40343 40344 40345 40346 40347 40348 40349 40350 40351 40352 40353 40354 40355 40356 40357 40358 40359 40360 40361 40362 40363 40364 40365 40366 40367 40368 40369 40370 40371 40372 40373 40374 40375 40376 40377 40378 40379 40380 40381 40382 40383 40384 40385 40386 40387 40388 40389 40390 40391 40392 40393 40394 40395 40396 40397 40398 40399 40400 40401 40402 40403 40404 40405 40406 40407 40408 40409 40410 40411 40412 40413 40414 40415 40416 40417 40418 40419 40420 40421 40422 40423 40424 40425 40426 40427 40428 40429 40430 40431 40432 40433 40434 40435 40436 40437 40438 40439 40440 40441 40442 40443 40444 40445 40446 40447 40448 40449 40450 40451 40452 40453 40454 40455 40456 40457 40458 40459 40460 40461 40462 40463 40464 40465 40466 40467 40468 40469 40470 40471 40472 40473 40474 40475 40476 40477 40478 40479 40480 40481 40482 40483 40484 40485 40486 40487 40488 40489 40490 40491 40492 40493 40494 40495 40496 40497 40498 40499 40500 40501 40502 40503 40504 40505 40506 40507 40508 40509 40510 40511 40512 40513 40514 40515 40516 40517 40518 40519 40520 40521 40522 40523 40524 40525 40526 40527 40528 40529 40530 40531 40532 40533 40534 40535 40536 40537 40538 40539 40540 40541 40542 40543 40544 40545 40546 40547 40548 40549 40550 40551 40552 40553 40554 40555 40556 40557 40558 40559 40560 40561 40562 40563 40564 40565 40566 40567 40568 40569 40570 40571 40572 40573 40574 40575 40576 40577 40578 40579 40580 40581 40582 40583 40584 40585 40586 40587 40588 40589 40590 40591 40592 40593 40594 40595 40596 40597 40598 40599 40600 40601 40602 40603 40604 40605 40606 40607 40608 40609 40610 40611 40612 40613 40614 40615 40616 40617 40618 40619 40620 40621 40622 40623 40624 40625 40626 40627 40628 40629 40630 40631 40632 40633 40634 40635 40636 40637 40638 40639 40640 40641 40642 40643 40644 40645 40646 40647 40648 40649 40650 40651 40652 40653 40654 40655 40656 40657 40658 40659 40660 40661 40662 40663 40664 40665 40666 40667 40668 40669 40670 40671 40672 40673 40674 40675 40676 40677 40678 40679 40680 40681 40682 40683 40684 40685 40686 40687 40688 40689 40690 40691 40692 40693 40694 40695 40696 40697 40698 40699 40700 40701 40702 40703 40704 40705 40706 40707 40708 40709 40710 40711 40712 40713 40714 40715 40716 40717 40718 40719 40720 40721 40722 40723 40724 40725 40726 40727 40728 40729 40730 40731 40732 40733 40734 40735 40736 40737 40738 40739 40740 40741 40742 40743 40744 40745 40746 40747 40748 40749 40750 40751 40752 40753 40754 40755 40756 40757 40758 40759 40760 40761 40762 40763 40764 40765 40766 40767 40768 40769 40770 40771 40772 40773 40774 40775 40776 40777 40778 40779 40780 40781 40782 40783 40784 40785 40786 40787 40788 40789 40790 40791 40792 40793 40794 40795 40796 40797 40798 40799 40800 40801 40802 40803 40804 40805 40806 40807 40808 40809 40810 40811 40812 40813 40814 40815 40816 40817 40818 40819 40820 40821 40822 40823 40824 40825 40826 40827 40828 40829 40830 40831 40832 40833 40834 40835 40836 40837 40838 40839 40840 40841 40842 40843 40844 40845 40846 40847 40848 40849 40850 40851 40852 40853 40854 40855 40856 40857 40858 40859 40860 40861 40862 40863 40864 40865 40866 40867 40868 40869 40870 40871 40872 40873 40874 40875 40876 40877 40878 40879 40880 40881 40882 40883 40884 40885 40886 40887 40888 40889 40890 40891 40892 40893 40894 40895 40896 40897 40898 40899 40900 40901 40902 40903 40904 40905 40906 40907 40908 40909 40910 40911 40912 40913 40914 40915 40916 40917 40918 40919 40920 40921 40922 40923 40924 40925 40926 40927 40928 40929 40930 40931 40932 40933 40934 40935 40936 40937 40938 40939 40940 40941 40942 40943 40944 40945 40946 40947 40948 40949 40950 40951 40952 40953 40954 40955 40956 40957 40958 40959 40960 40961 40962 40963 40964 40965 40966 40967 40968 40969 40970 40971 40972 40973 40974 40975 40976 40977 40978 40979 40980 40981 40982 40983 40984 40985 40986 40987 40988 40989 40990 40991 40992 40993 40994 40995 40996 40997 40998 40999 41000 41001 41002 41003 41004 41005 41006 41007 41008 41009 41010 41011 41012 41013 41014 41015 41016 41017 41018 41019 41020 41021 41022 41023 41024 41025 41026 41027 41028 41029 41030 41031 41032 41033 41034 41035 41036 41037 41038 41039 41040 41041 41042 41043 41044 41045 41046 41047 41048 41049 41050 41051 41052 41053 41054 41055 41056 41057 41058 41059 41060 41061 41062 41063 41064 41065 41066 41067 41068 41069 41070 41071 41072 41073 41074 41075 41076 41077 41078 41079 41080 41081 41082 41083 41084 41085 41086 41087 41088 41089 41090 41091 41092 41093 41094 41095 41096 41097 41098 41099 41100 41101 41102 41103 41104 41105 41106 41107 41108 41109 41110 41111 41112 41113 41114 41115 41116 41117 41118 41119 41120 41121 41122 41123 41124 41125 41126 41127 41128 41129 41130 41131 41132 41133 41134 41135 41136 41137 41138 41139 41140 41141 41142 41143 41144 41145 41146 41147 41148 41149 41150 41151 41152 41153 41154 41155 41156 41157 41158 41159 41160 41161 41162 41163 41164 41165 41166 41167 41168 41169 41170 41171 41172 41173 41174 41175 41176 41177 41178 41179 41180 41181 41182 41183 41184 41185 41186 41187 41188 41189 41190 41191 41192 41193 41194 41195 41196 41197 41198 41199 41200 41201 41202 41203 41204 41205 41206 41207 41208 41209 41210 41211 41212 41213 41214 41215 41216 41217 41218 41219 41220 41221 41222 41223 41224 41225 41226 41227 41228 41229 41230 41231 41232 41233 41234 41235 41236 41237 41238 41239 41240 41241 41242 41243 41244 41245 41246 41247 41248 41249 41250 41251 41252 41253 41254 41255 41256 41257 41258 41259 41260 41261 41262 41263 41264 41265 41266 41267 41268 41269 41270 41271 41272 41273 41274 41275 41276 41277 41278 41279 41280 41281 41282 41283 41284 41285 41286 41287 41288 41289 41290 41291 41292 41293 41294 41295 41296 41297 41298 41299 41300 41301 41302 41303 41304 41305 41306 41307 41308 41309 41310 41311 41312 41313 41314 41315 41316 41317 41318 41319 41320 41321 41322 41323 41324 41325 41326 41327 41328 41329 41330 41331 41332 41333 41334 41335 41336 41337 41338 41339 41340 41341 41342 41343 41344 41345 41346 41347 41348 41349 41350 41351 41352 41353 41354 41355 41356 41357 41358 41359 41360 41361 41362 41363 41364 41365 41366 41367 41368 41369 41370 41371 41372 41373 41374 41375 41376 41377 41378 41379 41380 41381 41382 41383 41384 41385 41386 41387 41388 41389 41390 41391 41392 41393 41394 41395 41396 41397 41398 41399 41400 41401 41402 41403 41404 41405 41406 41407 41408 41409 41410 41411 41412 41413 41414 41415 41416 41417 41418 41419 41420 41421 41422 41423 41424 41425 41426 41427 41428 41429 41430 41431 41432 41433 41434 41435 41436 41437 41438 41439 41440 41441 41442 41443 41444 41445 41446 41447 41448 41449 41450 41451 41452 41453 41454 41455 41456 41457 41458 41459 41460 41461 41462 41463 41464 41465 41466 41467 41468 41469 41470 41471 41472 41473 41474 41475 41476 41477 41478 41479 41480 41481 41482 41483 41484 41485 41486 41487 41488 41489 41490 41491 41492 41493 41494 41495 41496 41497 41498 41499 41500 41501 41502 41503 41504 41505 41506 41507 41508 41509 41510 41511 41512 41513 41514 41515 41516 41517 41518 41519 41520 41521 41522 41523 41524 41525 41526 41527 41528 41529 41530 41531 41532 41533 41534 41535 41536 41537 41538 41539 41540 41541 41542 41543 41544 41545 41546 41547 41548 41549 41550 41551 41552 41553 41554 41555 41556 41557 41558 41559 41560 41561 41562 41563 41564 41565 41566 41567 41568 41569 41570 41571 41572 41573 41574 41575 41576 41577 41578 41579 41580 41581 41582 41583 41584 41585 41586 41587 41588 41589 41590 41591 41592 41593 41594 41595 41596 41597 41598 41599 41600 41601 41602 41603 41604 41605 41606 41607 41608 41609 41610 41611 41612 41613 41614 41615 41616 41617 41618 41619 41620 41621 41622 41623 41624 41625 41626 41627 41628 41629 41630 41631 41632 41633 41634 41635 41636 41637 41638 41639 41640 41641 41642 41643 41644 41645 41646 41647 41648 41649 41650 41651 41652 41653 41654 41655 41656 41657 41658 41659 41660 41661 41662 41663 41664 41665 41666 41667 41668 41669 41670 41671 41672 41673 41674 41675 41676 41677 41678 41679 41680 41681 41682 41683 41684 41685 41686 41687 41688 41689 41690 41691 41692 41693 41694 41695 41696 41697 41698 41699 41700 41701 41702 41703 41704 41705 41706 41707 41708 41709 41710 41711 41712 41713 41714 41715 41716 41717 41718 41719 41720 41721 41722 41723 41724 41725 41726 41727 41728 41729 41730 41731 41732 41733 41734 41735 41736 41737 41738 41739 41740 41741 41742 41743 41744 41745 41746 41747 41748 41749 41750 41751 41752 41753 41754 41755 41756 41757 41758 41759 41760 41761 41762 41763 41764 41765 41766 41767 41768 41769 41770 41771 41772 41773 41774 41775 41776 41777 41778 41779 41780 41781 41782 41783 41784 41785 41786 41787 41788 41789 41790 41791 41792 41793 41794 41795 41796 41797 41798 41799 41800 41801 41802 41803 41804 41805 41806 41807 41808 41809 41810 41811 41812 41813 41814 41815 41816 41817 41818 41819 41820 41821 41822 41823 41824 41825 41826 41827 41828 41829 41830 41831 41832 41833 41834 41835 41836 41837 41838 41839 41840 41841 41842 41843 41844 41845 41846 41847 41848 41849 41850 41851 41852 41853 41854 41855 41856 41857 41858 41859 41860 41861 41862 41863 41864 41865 41866 41867 41868 41869 41870 41871 41872 41873 41874 41875 41876 41877 41878 41879 41880 41881 41882 41883 41884 41885 41886 41887 41888 41889 41890 41891 41892 41893 41894 41895 41896 41897 41898 41899 41900 41901 41902 41903 41904 41905 41906 41907 41908 41909 41910 41911 41912 41913 41914 41915 41916 41917 41918 41919 41920 41921 41922 41923 41924 41925 41926 41927 41928 41929 41930 41931 41932 41933 41934 41935 41936 41937 41938 41939 41940 41941 41942 41943 41944 41945 41946 41947 41948 41949 41950 41951 41952 41953 41954 41955 41956 41957 41958 41959 41960 41961 41962 41963 41964 41965 41966 41967 41968 41969 41970 41971 41972 41973 41974 41975 41976 41977 41978 41979 41980 41981 41982 41983 41984 41985 41986 41987 41988 41989 41990 41991 41992 41993 41994 41995 41996 41997 41998 41999 42000 42001 42002 42003 42004 42005 42006 42007 42008 42009 42010 42011 42012 42013 42014 42015 42016 42017 42018 42019 42020 42021 42022 42023 42024 42025 42026 42027 42028 42029 42030 42031 42032 42033 42034 42035 42036 42037 42038 42039 42040 42041 42042 42043 42044 42045 42046 42047 42048 42049 42050 42051 42052 42053 42054 42055 42056 42057 42058 42059 42060 42061 42062 42063 42064 42065 42066 42067 42068 42069 42070 42071 42072 42073 42074 42075 42076 42077 42078 42079 42080 42081 42082 42083 42084 42085 42086 42087 42088 42089 42090 42091 42092 42093 42094 42095 42096 42097 42098 42099 42100 42101 42102 42103 42104 42105 42106 42107 42108 42109 42110 42111 42112 42113 42114 42115 42116 42117 42118 42119 42120 42121 42122 42123 42124 42125 42126 42127 42128 42129 42130 42131 42132 42133 42134 42135 42136 42137 42138 42139 42140 42141 42142 42143 42144 42145 42146 42147 42148 42149 42150 42151 42152 42153 42154 42155 42156 42157 42158 42159 42160 42161 42162 42163 42164 42165 42166 42167 42168 42169 42170 42171 42172 42173 42174 42175 42176 42177 42178 42179 42180 42181 42182 42183 42184 42185 42186 42187 42188 42189 42190 42191 42192 42193 42194 42195 42196 42197 42198 42199 42200 42201 42202 42203 42204 42205 42206 42207 42208 42209 42210 42211 42212 42213 42214 42215 42216 42217 42218 42219 42220 42221 42222 42223 42224 42225 42226 42227 42228 42229 42230 42231 42232 42233 42234 42235 42236 42237 42238 42239 42240 42241 42242 42243 42244 42245 42246 42247 42248 42249 42250 42251 42252 42253 42254 42255 42256 42257 42258 42259 42260 42261 42262 42263 42264 42265 42266 42267 42268 42269 42270 42271 42272 42273 42274 42275 42276 42277 42278 42279 42280 42281 42282 42283 42284 42285 42286 42287 42288 42289 42290 42291 42292 42293 42294 42295 42296 42297 42298 42299 42300 42301 42302 42303 42304 42305 42306 42307 42308 42309 42310 42311 42312 42313 42314 42315 42316 42317 42318 42319 42320 42321 42322 42323 42324 42325 42326 42327 42328 42329 42330 42331 42332 42333 42334 42335 42336 42337 42338 42339 42340 42341 42342 42343 42344 42345 42346 42347 42348 42349 42350 42351 42352 42353 42354 42355 42356 42357 42358 42359 42360 42361 42362 42363 42364 42365 42366 42367 42368 42369 42370 42371 42372 42373 42374 42375 42376 42377 42378 42379 42380 42381 42382 42383 42384 42385 42386 42387 42388 42389 42390 42391 42392 42393 42394 42395 42396 42397 42398 42399 42400 42401 42402 42403 42404 42405 42406 42407 42408 42409 42410 42411 42412 42413 42414 42415 42416 42417 42418 42419 42420 42421 42422 42423 42424 42425 42426 42427 42428 42429 42430 42431 42432 42433 42434 42435 42436 42437 42438 42439 42440 42441 42442 42443 42444 42445 42446 42447 42448 42449 42450 42451 42452 42453 42454 42455 42456 42457 42458 42459 42460 42461 42462 42463 42464 42465 42466 42467 42468 42469 42470 42471 42472 42473 42474 42475 42476 42477 42478 42479 42480 42481 42482 42483 42484 42485 42486 42487 42488 42489 42490 42491 42492 42493 42494 42495 42496 42497 42498 42499 42500 42501 42502 42503 42504 42505 42506 42507 42508 42509 42510 42511 42512 42513 42514 42515 42516 42517 42518 42519 42520 42521 42522 42523 42524 42525 42526 42527 42528 42529 42530 42531 42532 42533 42534 42535 42536 42537 42538 42539 42540 42541 42542 42543 42544 42545 42546 42547 42548 42549 42550 42551 42552 42553 42554 42555 42556 42557 42558 42559 42560 42561 42562 42563 42564 42565 42566 42567 42568 42569 42570 42571 42572 42573 42574 42575 42576 42577 42578 42579 42580 42581 42582 42583 42584 42585 42586 42587 42588 42589 42590 42591 42592 42593 42594 42595 42596 42597 42598 42599 42600 42601 42602 42603 42604 42605 42606 42607 42608 42609 42610 42611 42612 42613 42614 42615 42616 42617 42618 42619 42620 42621 42622 42623 42624 42625 42626 42627 42628 42629 42630 42631 42632 42633 42634 42635 42636 42637 42638 42639 42640 42641 42642 42643 42644 42645 42646 42647 42648 42649 42650 42651 42652 42653 42654 42655 42656 42657 42658 42659 42660 42661 42662 42663 42664 42665 42666 42667 42668 42669 42670 42671 42672 42673 42674 42675 42676 42677 42678 42679 42680 42681 42682 42683 42684 42685 42686 42687 42688 42689 42690 42691 42692 42693 42694 42695 42696 42697 42698 42699 42700 42701 42702 42703 42704 42705 42706 42707 42708 42709 42710 42711 42712 42713 42714 42715 42716 42717 42718 42719 42720 42721 42722 42723 42724 42725 42726 42727 42728 42729 42730 42731 42732 42733 42734 42735 42736 42737 42738 42739 42740 42741 42742 42743 42744 42745 42746 42747 42748 42749 42750 42751 42752 42753 42754 42755 42756 42757 42758 42759 42760 42761 42762 42763 42764 42765 42766 42767 42768 42769 42770 42771 42772 42773 42774 42775 42776 42777 42778 42779 42780 42781 42782 42783 42784 42785 42786 42787 42788 42789 42790 42791 42792 42793 42794 42795 42796 42797 42798 42799 42800 42801 42802 42803 42804 42805 42806 42807 42808 42809 42810 42811 42812 42813 42814 42815 42816 42817 42818 42819 42820 42821 42822 42823 42824 42825 42826 42827 42828 42829 42830 42831 42832 42833 42834 42835 42836 42837 42838 42839 42840 42841 42842 42843 42844 42845 42846 42847 42848 42849 42850 42851 42852 42853 42854 42855 42856 42857 42858 42859 42860 42861 42862 42863 42864 42865 42866 42867 42868 42869 42870 42871 42872 42873 42874 42875 42876 42877 42878 42879 42880 42881 42882 42883 42884 42885 42886 42887 42888 42889 42890 42891 42892 42893 42894 42895 42896 42897 42898 42899 42900 42901 42902 42903 42904 42905 42906 42907 42908 42909 42910 42911 42912 42913 42914 42915 42916 42917 42918 42919 42920 42921 42922 42923 42924 42925 42926 42927 42928 42929 42930 42931 42932 42933 42934 42935 42936 42937 42938 42939 42940 42941 42942 42943 42944 42945 42946 42947 42948 42949 42950 42951 42952 42953 42954 42955 42956 42957 42958 42959 42960 42961 42962 42963 42964 42965 42966 42967 42968 42969 42970 42971 42972 42973 42974 42975 42976 42977 42978 42979 42980 42981 42982 42983 42984 42985 42986 42987 42988 42989 42990 42991 42992 42993 42994 42995 42996 42997 42998 42999 43000 43001 43002 43003 43004 43005 43006 43007 43008 43009 43010 43011 43012 43013 43014 43015 43016 43017 43018 43019 43020 43021 43022 43023 43024 43025 43026 43027 43028 43029 43030 43031 43032 43033 43034 43035 43036 43037 43038 43039 43040 43041 43042 43043 43044 43045 43046 43047 43048 43049 43050 43051 43052 43053 43054 43055 43056 43057 43058 43059 43060 43061 43062 43063 43064 43065 43066 43067 43068 43069 43070 43071 43072 43073 43074 43075 43076 43077 43078 43079 43080 43081 43082 43083 43084 43085 43086 43087 43088 43089 43090 43091 43092 43093 43094 43095 43096 43097 43098 43099 43100 43101 43102 43103 43104 43105 43106 43107 43108 43109 43110 43111 43112 43113 43114 43115 43116 43117 43118 43119 43120 43121 43122 43123 43124 43125 43126 43127 43128 43129 43130 43131 43132 43133 43134 43135 43136 43137 43138 43139 43140 43141 43142 43143 43144 43145 43146 43147 43148 43149 43150 43151 43152 43153 43154 43155 43156 43157 43158 43159 43160 43161 43162 43163 43164 43165 43166 43167 43168 43169 43170 43171 43172 43173 43174 43175 43176 43177 43178 43179 43180 43181 43182 43183 43184 43185 43186 43187 43188 43189 43190 43191 43192 43193 43194 43195 43196 43197 43198 43199 43200 43201 43202 43203 43204 43205 43206 43207 43208 43209 43210 43211 43212 43213 43214 43215 43216 43217 43218 43219 43220 43221 43222 43223 43224 43225 43226 43227 43228 43229 43230 43231 43232 43233 43234 43235 43236 43237 43238 43239 43240 43241 43242 43243 43244 43245 43246 43247 43248 43249 43250 43251 43252 43253 43254 43255 43256 43257 43258 43259 43260 43261 43262 43263 43264 43265 43266 43267 43268 43269 43270 43271 43272 43273 43274 43275 43276 43277 43278 43279 43280 43281 43282 43283 43284 43285 43286 43287 43288 43289 43290 43291 43292 43293 43294 43295 43296 43297 43298 43299 43300 43301 43302 43303 43304 43305 43306 43307 43308 43309 43310 43311 43312 43313 43314 43315 43316 43317 43318 43319 43320 43321 43322 43323 43324 43325 43326 43327 43328 43329 43330 43331 43332 43333 43334 43335 43336 43337 43338 43339 43340 43341 43342 43343 43344 43345 43346 43347 43348 43349 43350 43351 43352 43353 43354 43355 43356 43357 43358 43359 43360 43361 43362 43363 43364 43365 43366 43367 43368 43369 43370 43371 43372 43373 43374 43375 43376 43377 43378 43379 43380 43381 43382 43383 43384 43385 43386 43387 43388 43389 43390 43391 43392 43393 43394 43395 43396 43397 43398 43399 43400 43401 43402 43403 43404 43405 43406 43407 43408 43409 43410 43411 43412 43413 43414 43415 43416 43417 43418 43419 43420 43421 43422 43423 43424 43425 43426 43427 43428 43429 43430 43431 43432 43433 43434 43435 43436 43437 43438 43439 43440 43441 43442 43443 43444 43445 43446 43447 43448 43449 43450 43451 43452 43453 43454 43455 43456 43457 43458 43459 43460 43461 43462 43463 43464 43465 43466 43467 43468 43469 43470 43471 43472 43473 43474 43475 43476 43477 43478 43479 43480 43481 43482 43483 43484 43485 43486 43487 43488 43489 43490 43491 43492 43493 43494 43495 43496 43497 43498 43499 43500 43501 43502 43503 43504 43505 43506 43507 43508 43509 43510 43511 43512 43513 43514 43515 43516 43517 43518 43519 43520 43521 43522 43523 43524 43525 43526 43527 43528 43529 43530 43531 43532 43533 43534 43535 43536 43537 43538 43539 43540 43541 43542 43543 43544 43545 43546 43547 43548 43549 43550 43551 43552 43553 43554 43555 43556 43557 43558 43559 43560 43561 43562 43563 43564 43565 43566 43567 43568 43569 43570 43571 43572 43573 43574 43575 43576 43577 43578 43579 43580 43581 43582 43583 43584 43585 43586 43587 43588 43589 43590 43591 43592 43593 43594 43595 43596 43597 43598 43599 43600 43601 43602 43603 43604 43605 43606 43607 43608 43609 43610 43611 43612 43613 43614 43615 43616 43617 43618 43619 43620 43621 43622 43623 43624 43625 43626 43627 43628 43629 43630 43631 43632 43633 43634 43635 43636 43637 43638 43639 43640 43641 43642 43643 43644 43645 43646 43647 43648 43649 43650 43651 43652 43653 43654 43655 43656 43657 43658 43659 43660 43661 43662 43663 43664 43665 43666 43667 43668 43669 43670 43671 43672 43673 43674 43675 43676 43677 43678 43679 43680 43681 43682 43683 43684 43685 43686 43687 43688 43689 43690 43691 43692 43693 43694 43695 43696 43697 43698 43699 43700 43701 43702 43703 43704 43705 43706 43707 43708 43709 43710 43711 43712 43713 43714 43715 43716 43717 43718 43719 43720 43721 43722 43723 43724 43725 43726 43727 43728 43729 43730 43731 43732 43733 43734 43735 43736 43737 43738 43739 43740 43741 43742 43743 43744 43745 43746 43747 43748 43749 43750 43751 43752 43753 43754 43755 43756 43757 43758 43759 43760 43761 43762 43763 43764 43765 43766 43767 43768 43769 43770 43771 43772 43773 43774 43775 43776 43777 43778 43779 43780 43781 43782 43783 43784 43785 43786 43787 43788 43789 43790 43791 43792 43793 43794 43795 43796 43797 43798 43799 43800 43801 43802 43803 43804 43805 43806 43807 43808 43809 43810 43811 43812 43813 43814 43815 43816 43817 43818 43819 43820 43821 43822 43823 43824 43825 43826 43827 43828 43829 43830 43831 43832 43833 43834 43835 43836 43837 43838 43839 43840 43841 43842 43843 43844 43845 43846 43847 43848 43849 43850 43851 43852 43853 43854 43855 43856 43857 43858 43859 43860 43861 43862 43863 43864 43865 43866 43867 43868 43869 43870 43871 43872 43873 43874 43875 43876 43877 43878 43879 43880 43881 43882 43883 43884 43885 43886 43887 43888 43889 43890 43891 43892 43893 43894 43895 43896 43897 43898 43899 43900 43901 43902 43903 43904 43905 43906 43907 43908 43909 43910 43911 43912 43913 43914 43915 43916 43917 43918 43919 43920 43921 43922 43923 43924 43925 43926 43927 43928 43929 43930 43931 43932 43933 43934 43935 43936 43937 43938 43939 43940 43941 43942 43943 43944 43945 43946 43947 43948 43949 43950 43951 43952 43953 43954 43955 43956 43957 43958 43959 43960 43961 43962 43963 43964 43965 43966 43967 43968 43969 43970 43971 43972 43973 43974 43975 43976 43977 43978 43979 43980 43981 43982 43983 43984 43985 43986 43987 43988 43989 43990 43991 43992 43993 43994 43995 43996 43997 43998 43999 44000 44001 44002 44003 44004 44005 44006 44007 44008 44009 44010 44011 44012 44013 44014 44015 44016 44017 44018 44019 44020 44021 44022 44023 44024 44025 44026 44027 44028 44029 44030 44031 44032 44033 44034 44035 44036 44037 44038 44039 44040 44041 44042 44043 44044 44045 44046 44047 44048 44049 44050 44051 44052 44053 44054 44055 44056 44057 44058 44059 44060 44061 44062 44063 44064 44065 44066 44067 44068 44069 44070 44071 44072 44073 44074 44075 44076 44077 44078 44079 44080 44081 44082 44083 44084 44085 44086 44087 44088 44089 44090 44091 44092 44093 44094 44095 44096 44097 44098 44099 44100 44101 44102 44103 44104 44105 44106 44107 44108 44109 44110 44111 44112 44113 44114 44115 44116 44117 44118 44119 44120 44121 44122 44123 44124 44125 44126 44127 44128 44129 44130 44131 44132 44133 44134 44135 44136 44137 44138 44139 44140 44141 44142 44143 44144 44145 44146 44147 44148 44149 44150 44151 44152 44153 44154 44155 44156 44157 44158 44159 44160 44161 44162 44163 44164 44165 44166 44167 44168 44169 44170 44171 44172 44173 44174 44175 44176 44177 44178 44179 44180 44181 44182 44183 44184 44185 44186 44187 44188 44189 44190 44191 44192 44193 44194 44195 44196 44197 44198 44199 44200 44201 44202 44203 44204 44205 44206 44207 44208 44209 44210 44211 44212 44213 44214 44215 44216 44217 44218 44219 44220 44221 44222 44223 44224 44225 44226 44227 44228 44229 44230 44231 44232 44233 44234 44235 44236 44237 44238 44239 44240 44241 44242 44243 44244 44245 44246 44247 44248 44249 44250 44251 44252 44253 44254 44255 44256 44257 44258 44259 44260 44261 44262 44263 44264 44265 44266 44267 44268 44269 44270 44271 44272 44273 44274 44275 44276 44277 44278 44279 44280 44281 44282 44283 44284 44285 44286 44287 44288 44289 44290 44291 44292 44293 44294 44295 44296 44297 44298 44299 44300 44301 44302 44303 44304 44305 44306 44307 44308 44309 44310 44311 44312 44313 44314 44315 44316 44317 44318 44319 44320 44321 44322 44323 44324 44325 44326 44327 44328 44329 44330 44331 44332 44333 44334 44335 44336 44337 44338 44339 44340 44341 44342 44343 44344 44345 44346 44347 44348 44349 44350 44351 44352 44353 44354 44355 44356 44357 44358 44359 44360 44361 44362 44363 44364 44365 44366 44367 44368 44369 44370 44371 44372 44373 44374 44375 44376 44377 44378 44379 44380 44381 44382 44383 44384 44385 44386 44387 44388 44389 44390 44391 44392 44393 44394 44395 44396 44397 44398 44399 44400 44401 44402 44403 44404 44405 44406 44407 44408 44409 44410 44411 44412 44413 44414 44415 44416 44417 44418 44419 44420 44421 44422 44423 44424 44425 44426 44427 44428 44429 44430 44431 44432 44433 44434 44435 44436 44437 44438 44439 44440 44441 44442 44443 44444 44445 44446 44447 44448 44449 44450 44451 44452 44453 44454 44455 44456 44457 44458 44459 44460 44461 44462 44463 44464 44465 44466 44467 44468 44469 44470 44471 44472 44473 44474 44475 44476 44477 44478 44479 44480 44481 44482 44483 44484 44485 44486 44487 44488 44489 44490 44491 44492 44493 44494 44495 44496 44497 44498 44499 44500 44501 44502 44503 44504 44505 44506 44507 44508 44509 44510 44511 44512 44513 44514 44515 44516 44517 44518 44519 44520 44521 44522 44523 44524 44525 44526 44527 44528 44529 44530 44531 44532 44533 44534 44535 44536 44537 44538 44539 44540 44541 44542 44543 44544 44545 44546 44547 44548 44549 44550 44551 44552 44553 44554 44555 44556 44557 44558 44559 44560 44561 44562 44563 44564 44565 44566 44567 44568 44569 44570 44571 44572 44573 44574 44575 44576 44577 44578 44579 44580 44581 44582 44583 44584 44585 44586 44587 44588 44589 44590 44591 44592 44593 44594 44595 44596 44597 44598 44599 44600 44601 44602 44603 44604 44605 44606 44607 44608 44609 44610 44611 44612 44613 44614 44615 44616 44617 44618 44619 44620 44621 44622 44623 44624 44625 44626 44627 44628 44629 44630 44631 44632 44633 44634 44635 44636 44637 44638 44639 44640 44641 44642 44643 44644 44645 44646 44647 44648 44649 44650 44651 44652 44653 44654 44655 44656 44657 44658 44659 44660 44661 44662 44663 44664 44665 44666 44667 44668 44669 44670 44671 44672 44673 44674 44675 44676 44677 44678 44679 44680 44681 44682 44683 44684 44685 44686 44687 44688 44689 44690 44691 44692 44693 44694 44695 44696 44697 44698 44699 44700 44701 44702 44703 44704 44705 44706 44707 44708 44709 44710 44711 44712 44713 44714 44715 44716 44717 44718 44719 44720 44721 44722 44723 44724 44725 44726 44727 44728 44729 44730 44731 44732 44733 44734 44735 44736 44737 44738 44739 44740 44741 44742 44743 44744 44745 44746 44747 44748 44749 44750 44751 44752 44753 44754 44755 44756 44757 44758 44759 44760 44761 44762 44763 44764 44765 44766 44767 44768 44769 44770 44771 44772 44773 44774 44775 44776 44777 44778 44779 44780 44781 44782 44783 44784 44785 44786 44787 44788 44789 44790 44791 44792 44793 44794 44795 44796 44797 44798 44799 44800 44801 44802 44803 44804 44805 44806 44807 44808 44809 44810 44811 44812 44813 44814 44815 44816 44817 44818 44819 44820 44821 44822 44823 44824 44825 44826 44827 44828 44829 44830 44831 44832 44833 44834 44835 44836 44837 44838 44839 44840 44841 44842 44843 44844 44845 44846 44847 44848 44849 44850 44851 44852 44853 44854 44855 44856 44857 44858 44859 44860 44861 44862 44863 44864 44865 44866 44867 44868 44869 44870 44871 44872 44873 44874 44875 44876 44877 44878 44879 44880 44881 44882 44883 44884 44885 44886 44887 44888 44889 44890 44891 44892 44893 44894 44895 44896 44897 44898 44899 44900 44901 44902 44903 44904 44905 44906 44907 44908 44909 44910 44911 44912 44913 44914 44915 44916 44917 44918 44919 44920 44921 44922 44923 44924 44925 44926 44927 44928 44929 44930 44931 44932 44933 44934 44935 44936 44937 44938 44939 44940 44941 44942 44943 44944 44945 44946 44947 44948 44949 44950 44951 44952 44953 44954 44955 44956 44957 44958 44959 44960 44961 44962 44963 44964 44965 44966 44967 44968 44969 44970 44971 44972 44973 44974 44975 44976 44977 44978 44979 44980 44981 44982 44983 44984 44985 44986 44987 44988 44989 44990 44991 44992 44993 44994 44995 44996 44997 44998 44999 45000 45001 45002 45003 45004 45005 45006 45007 45008 45009 45010 45011 45012 45013 45014 45015 45016 45017 45018 45019 45020 45021 45022 45023 45024 45025 45026 45027 45028 45029 45030 45031 45032 45033 45034 45035 45036 45037 45038 45039 45040 45041 45042 45043 45044 45045 45046 45047 45048 45049 45050 45051 45052 45053 45054 45055 45056 45057 45058 45059 45060 45061 45062 45063 45064 45065 45066 45067 45068 45069 45070 45071 45072 45073 45074 45075 45076 45077 45078 45079 45080 45081 45082 45083 45084 45085 45086 45087 45088 45089 45090 45091 45092 45093 45094 45095 45096 45097 45098 45099 45100 45101 45102 45103 45104 45105 45106 45107 45108 45109 45110 45111 45112 45113 45114 45115 45116 45117 45118 45119 45120 45121 45122 45123 45124 45125 45126 45127 45128 45129 45130 45131 45132 45133 45134 45135 45136 45137 45138 45139 45140 45141 45142 45143 45144 45145 45146 45147 45148 45149 45150 45151 45152 45153 45154 45155 45156 45157 45158 45159 45160 45161 45162 45163 45164 45165 45166 45167 45168 45169 45170 45171 45172 45173 45174 45175 45176 45177 45178 45179 45180 45181 45182 45183 45184 45185 45186 45187 45188 45189 45190 45191 45192 45193 45194 45195 45196 45197 45198 45199 45200 45201 45202 45203 45204 45205 45206 45207 45208 45209 45210 45211 45212 45213 45214 45215 45216 45217 45218 45219 45220 45221 45222 45223 45224 45225 45226 45227 45228 45229 45230 45231 45232 45233 45234 45235 45236 45237 45238 45239 45240 45241 45242 45243 45244 45245 45246 45247 45248 45249 45250 45251 45252 45253 45254 45255 45256 45257 45258 45259 45260 45261 45262 45263 45264 45265 45266 45267 45268 45269 45270 45271 45272 45273 45274 45275 45276 45277 45278 45279 45280 45281 45282 45283 45284 45285 45286 45287 45288 45289 45290 45291 45292 45293 45294 45295 45296 45297 45298 45299 45300 45301 45302 45303 45304 45305 45306 45307 45308 45309 45310 45311 45312 45313 45314 45315 45316 45317 45318 45319 45320 45321 45322 45323 45324 45325 45326 45327 45328 45329 45330 45331 45332 45333 45334 45335 45336 45337 45338 45339 45340 45341 45342 45343 45344 45345 45346 45347 45348 45349 45350 45351 45352 45353 45354 45355 45356 45357 45358 45359 45360 45361 45362 45363 45364 45365 45366 45367 45368 45369 45370 45371 45372 45373 45374 45375 45376 45377 45378 45379 45380 45381 45382 45383 45384 45385 45386 45387 45388 45389 45390 45391 45392 45393 45394 45395 45396 45397 45398 45399 45400 45401 45402 45403 45404 45405 45406 45407 45408 45409 45410 45411 45412 45413 45414 45415 45416 45417 45418 45419 45420 45421 45422 45423 45424 45425 45426 45427 45428 45429 45430 45431 45432 45433 45434 45435 45436 45437 45438 45439 45440 45441 45442 45443 45444 45445 45446 45447 45448 45449 45450 45451 45452 45453 45454 45455 45456 45457 45458 45459 45460 45461 45462 45463 45464 45465 45466 45467 45468 45469 45470 45471 45472 45473 45474 45475 45476 45477 45478 45479 45480 45481 45482 45483 45484 45485 45486 45487 45488 45489 45490 45491 45492 45493 45494 45495 45496 45497 45498 45499 45500 45501 45502 45503 45504 45505 45506 45507 45508 45509 45510 45511 45512 45513 45514 45515 45516 45517 45518 45519 45520 45521 45522 45523 45524 45525 45526 45527 45528 45529 45530 45531 45532 45533 45534 45535 45536 45537 45538 45539 45540 45541 45542 45543 45544 45545 45546 45547 45548 45549 45550 45551 45552 45553 45554 45555 45556 45557 45558 45559 45560 45561 45562 45563 45564 45565 45566 45567 45568 45569 45570 45571 45572 45573 45574 45575 45576 45577 45578 45579 45580 45581 45582 45583 45584 45585 45586 45587 45588 45589 45590 45591 45592 45593 45594 45595 45596 45597 45598 45599 45600 45601 45602 45603 45604 45605 45606 45607 45608 45609 45610 45611 45612 45613 45614 45615 45616 45617 45618 45619 45620 45621 45622 45623 45624 45625 45626 45627 45628 45629 45630 45631 45632 45633 45634 45635 45636 45637 45638 45639 45640 45641 45642 45643 45644 45645 45646 45647 45648 45649 45650 45651 45652 45653 45654 45655 45656 45657 45658 45659 45660 45661 45662 45663 45664 45665 45666 45667 45668 45669 45670 45671 45672 45673 45674 45675 45676 45677 45678 45679 45680 45681 45682 45683 45684 45685 45686 45687 45688 45689 45690 45691 45692 45693 45694 45695 45696 45697 45698 45699 45700 45701 45702 45703 45704 45705 45706 45707 45708 45709 45710 45711 45712 45713 45714 45715 45716 45717 45718 45719 45720 45721 45722 45723 45724 45725 45726 45727 45728 45729 45730 45731 45732 45733 45734 45735 45736 45737 45738 45739 45740 45741 45742 45743 45744 45745 45746 45747 45748 45749 45750 45751 45752 45753 45754 45755 45756 45757 45758 45759 45760 45761 45762 45763 45764 45765 45766 45767 45768 45769 45770 45771 45772 45773 45774 45775 45776 45777 45778 45779 45780 45781 45782 45783 45784 45785 45786 45787 45788 45789 45790 45791 45792 45793 45794 45795 45796 45797 45798 45799 45800 45801 45802 45803 45804 45805 45806 45807 45808 45809 45810 45811 45812 45813 45814 45815 45816 45817 45818 45819 45820 45821 45822 45823 45824 45825 45826 45827 45828 45829 45830 45831 45832 45833 45834 45835 45836 45837 45838 45839 45840 45841 45842 45843 45844 45845 45846 45847 45848 45849 45850 45851 45852 45853 45854 45855 45856 45857 45858 45859 45860 45861 45862 45863 45864 45865 45866 45867 45868 45869 45870 45871 45872 45873 45874 45875 45876 45877 45878 45879 45880 45881 45882 45883 45884 45885 45886 45887 45888 45889 45890 45891 45892 45893 45894 45895 45896 45897 45898 45899 45900 45901 45902 45903 45904 45905 45906 45907 45908 45909 45910 45911 45912 45913 45914 45915 45916 45917 45918 45919 45920 45921 45922 45923 45924 45925 45926 45927 45928 45929 45930 45931 45932 45933 45934 45935 45936 45937 45938 45939 45940 45941 45942 45943 45944 45945 45946 45947 45948 45949 45950 45951 45952 45953 45954 45955 45956 45957 45958 45959 45960 45961 45962 45963 45964 45965 45966 45967 45968 45969 45970 45971 45972 45973 45974 45975 45976 45977 45978 45979 45980 45981 45982 45983 45984 45985 45986 45987 45988 45989 45990 45991 45992 45993 45994 45995 45996 45997 45998 45999 46000 46001 46002 46003 46004 46005 46006 46007 46008 46009 46010 46011 46012 46013 46014 46015 46016 46017 46018 46019 46020 46021 46022 46023 46024 46025 46026 46027 46028 46029 46030 46031 46032 46033 46034 46035 46036 46037 46038 46039 46040 46041 46042 46043 46044 46045 46046 46047 46048 46049 46050 46051 46052 46053 46054 46055 46056 46057 46058 46059 46060 46061 46062 46063 46064 46065 46066 46067 46068 46069 46070 46071 46072 46073 46074 46075 46076 46077 46078 46079 46080 46081 46082 46083 46084 46085 46086 46087 46088 46089 46090 46091 46092 46093 46094 46095 46096 46097 46098 46099 46100 46101 46102 46103 46104 46105 46106 46107 46108 46109 46110 46111 46112 46113 46114 46115 46116 46117 46118 46119 46120 46121 46122 46123 46124 46125 46126 46127 46128 46129 46130 46131 46132 46133 46134 46135 46136 46137 46138 46139 46140 46141 46142 46143 46144 46145 46146 46147 46148 46149 46150 46151 46152 46153 46154 46155 46156 46157 46158 46159 46160 46161 46162 46163 46164 46165 46166 46167 46168 46169 46170 46171 46172 46173 46174 46175 46176 46177 46178 46179 46180 46181 46182 46183 46184 46185 46186 46187 46188 46189 46190 46191 46192 46193 46194 46195 46196 46197 46198 46199 46200 46201 46202 46203 46204 46205 46206 46207 46208 46209 46210 46211 46212 46213 46214 46215 46216 46217 46218 46219 46220 46221 46222 46223 46224 46225 46226 46227 46228 46229 46230 46231 46232 46233 46234 46235 46236 46237 46238 46239 46240 46241 46242 46243 46244 46245 46246 46247 46248 46249 46250 46251 46252 46253 46254 46255 46256 46257 46258 46259 46260 46261 46262 46263 46264 46265 46266 46267 46268 46269 46270 46271 46272 46273 46274 46275 46276 46277 46278 46279 46280 46281 46282 46283 46284 46285 46286 46287 46288 46289 46290 46291 46292 46293 46294 46295 46296 46297 46298 46299 46300 46301 46302 46303 46304 46305 46306 46307 46308 46309 46310 46311 46312 46313 46314 46315 46316 46317 46318 46319 46320 46321 46322 46323 46324 46325 46326 46327 46328 46329 46330 46331 46332 46333 46334 46335 46336 46337 46338 46339 46340 46341 46342 46343 46344 46345 46346 46347 46348 46349 46350 46351 46352 46353 46354 46355 46356 46357 46358 46359 46360 46361 46362 46363 46364 46365 46366 46367 46368 46369 46370 46371 46372 46373 46374 46375 46376 46377 46378 46379 46380 46381 46382 46383 46384 46385 46386 46387 46388 46389 46390 46391 46392 46393 46394 46395 46396 46397 46398 46399 46400 46401 46402 46403 46404 46405 46406 46407 46408 46409 46410 46411 46412 46413 46414 46415 46416 46417 46418 46419 46420 46421 46422 46423 46424 46425 46426 46427 46428 46429 46430 46431 46432 46433 46434 46435 46436 46437 46438 46439 46440 46441 46442 46443 46444 46445 46446 46447 46448 46449 46450 46451 46452 46453 46454 46455 46456 46457 46458 46459 46460 46461 46462 46463 46464 46465 46466 46467 46468 46469 46470 46471 46472 46473 46474 46475 46476 46477 46478 46479 46480 46481 46482 46483 46484 46485 46486 46487 46488 46489 46490 46491 46492 46493 46494 46495 46496 46497 46498 46499 46500 46501 46502 46503 46504 46505 46506 46507 46508 46509 46510 46511 46512 46513 46514 46515 46516 46517 46518 46519 46520 46521 46522 46523 46524 46525 46526 46527 46528 46529 46530 46531 46532 46533 46534 46535 46536 46537 46538 46539 46540 46541 46542 46543 46544 46545 46546 46547 46548 46549 46550 46551 46552 46553 46554 46555 46556 46557 46558 46559 46560 46561 46562 46563 46564 46565 46566 46567 46568 46569 46570 46571 46572 46573 46574 46575 46576 46577 46578 46579 46580 46581 46582 46583 46584 46585 46586 46587 46588 46589 46590 46591 46592 46593 46594 46595 46596 46597 46598 46599 46600 46601 46602 46603 46604 46605 46606 46607 46608 46609 46610 46611 46612 46613 46614 46615 46616 46617 46618 46619 46620 46621 46622 46623 46624 46625 46626 46627 46628 46629 46630 46631 46632 46633 46634 46635 46636 46637 46638 46639 46640 46641 46642 46643 46644 46645 46646 46647 46648 46649 46650 46651 46652 46653 46654 46655 46656 46657 46658 46659 46660 46661 46662 46663 46664 46665 46666 46667 46668 46669 46670 46671 46672 46673 46674 46675 46676 46677 46678 46679 46680 46681 46682 46683 46684 46685 46686 46687 46688 46689 46690 46691 46692 46693 46694 46695 46696 46697 46698 46699 46700 46701 46702 46703 46704 46705 46706 46707 46708 46709 46710 46711 46712 46713 46714 46715 46716 46717 46718 46719 46720 46721 46722 46723 46724 46725 46726 46727 46728 46729 46730 46731 46732 46733 46734 46735 46736 46737 46738 46739 46740 46741 46742 46743 46744 46745 46746 46747 46748 46749 46750 46751 46752 46753 46754 46755 46756 46757 46758 46759 46760 46761 46762 46763 46764 46765 46766 46767 46768 46769 46770 46771 46772 46773 46774 46775 46776 46777 46778 46779 46780 46781 46782 46783 46784 46785 46786 46787 46788 46789 46790 46791 46792 46793 46794 46795 46796 46797 46798 46799 46800 46801 46802 46803 46804 46805 46806 46807 46808 46809 46810 46811 46812 46813 46814 46815 46816 46817 46818 46819 46820 46821 46822 46823 46824 46825 46826 46827 46828 46829 46830 46831 46832 46833 46834 46835 46836 46837 46838 46839 46840 46841 46842 46843 46844 46845 46846 46847 46848 46849 46850 46851 46852 46853 46854 46855 46856 46857 46858 46859 46860 46861 46862 46863 46864 46865 46866 46867 46868 46869 46870 46871 46872 46873 46874 46875 46876 46877 46878 46879 46880 46881 46882 46883 46884 46885 46886 46887 46888 46889 46890 46891 46892 46893 46894 46895 46896 46897 46898 46899 46900 46901 46902 46903 46904 46905 46906 46907 46908 46909 46910 46911 46912 46913 46914 46915 46916 46917 46918 46919 46920 46921 46922 46923 46924 46925 46926 46927 46928 46929 46930 46931 46932 46933 46934 46935 46936 46937 46938 46939 46940 46941 46942 46943 46944 46945 46946 46947 46948 46949 46950 46951 46952 46953 46954 46955 46956 46957 46958 46959 46960 46961 46962 46963 46964 46965 46966 46967 46968 46969 46970 46971 46972 46973 46974 46975 46976 46977 46978 46979 46980 46981 46982 46983 46984 46985 46986 46987 46988 46989 46990 46991 46992 46993 46994 46995 46996 46997 46998 46999 47000 47001 47002 47003 47004 47005 47006 47007 47008 47009 47010 47011 47012 47013 47014 47015 47016 47017 47018 47019 47020 47021 47022 47023 47024 47025 47026 47027 47028 47029 47030 47031 47032 47033 47034 47035 47036 47037 47038 47039 47040 47041 47042 47043 47044 47045 47046 47047 47048 47049 47050 47051 47052 47053 47054 47055 47056 47057 47058 47059 47060 47061 47062 47063 47064 47065 47066 47067 47068 47069 47070 47071 47072 47073 47074 47075 47076 47077 47078 47079 47080 47081 47082 47083 47084 47085 47086 47087 47088 47089 47090 47091 47092 47093 47094 47095 47096 47097 47098 47099 47100 47101 47102 47103 47104 47105 47106 47107 47108 47109 47110 47111 47112 47113 47114 47115 47116 47117 47118 47119 47120 47121 47122 47123 47124 47125 47126 47127 47128 47129 47130 47131 47132 47133 47134 47135 47136 47137 47138 47139 47140 47141 47142 47143 47144 47145 47146 47147 47148 47149 47150 47151 47152 47153 47154 47155 47156 47157 47158 47159 47160 47161 47162 47163 47164 47165 47166 47167 47168 47169 47170 47171 47172 47173 47174 47175 47176 47177 47178 47179 47180 47181 47182 47183 47184 47185 47186 47187 47188 47189 47190 47191 47192 47193 47194 47195 47196 47197 47198 47199 47200 47201 47202 47203 47204 47205 47206 47207 47208 47209 47210 47211 47212 47213 47214 47215 47216 47217 47218 47219 47220 47221 47222 47223 47224 47225 47226 47227 47228 47229 47230 47231 47232 47233 47234 47235 47236 47237 47238 47239 47240 47241 47242 47243 47244 47245 47246 47247 47248 47249 47250 47251 47252 47253 47254 47255 47256 47257 47258 47259 47260 47261 47262 47263 47264 47265 47266 47267 47268 47269 47270 47271 47272 47273 47274 47275 47276 47277 47278 47279 47280 47281 47282 47283 47284 47285 47286 47287 47288 47289 47290 47291 47292 47293 47294 47295 47296 47297 47298 47299 47300 47301 47302 47303 47304 47305 47306 47307 47308 47309 47310 47311 47312 47313 47314 47315 47316 47317 47318 47319 47320 47321 47322 47323 47324 47325 47326 47327 47328 47329 47330 47331 47332 47333 47334 47335 47336 47337 47338 47339 47340 47341 47342 47343 47344 47345 47346 47347 47348 47349 47350 47351 47352 47353 47354 47355 47356 47357 47358 47359 47360 47361 47362 47363 47364 47365 47366 47367 47368 47369 47370 47371 47372 47373 47374 47375 47376 47377 47378 47379 47380 47381 47382 47383 47384 47385 47386 47387 47388 47389 47390 47391 47392 47393 47394 47395 47396 47397 47398 47399 47400 47401 47402 47403 47404 47405 47406 47407 47408 47409 47410 47411 47412 47413 47414 47415 47416 47417 47418 47419 47420 47421 47422 47423 47424 47425 47426 47427 47428 47429 47430 47431 47432 47433 47434 47435 47436 47437 47438 47439 47440 47441 47442 47443 47444 47445 47446 47447 47448 47449 47450 47451 47452 47453 47454 47455 47456 47457 47458 47459 47460 47461 47462 47463 47464 47465 47466 47467 47468 47469 47470 47471 47472 47473 47474 47475 47476 47477 47478 47479 47480 47481 47482 47483 47484 47485 47486 47487 47488 47489 47490 47491 47492 47493 47494 47495 47496 47497 47498 47499 47500 47501 47502 47503 47504 47505 47506 47507 47508 47509 47510 47511 47512 47513 47514 47515 47516 47517 47518 47519 47520 47521 47522 47523 47524 47525 47526 47527 47528 47529 47530 47531 47532 47533 47534 47535 47536 47537 47538 47539 47540 47541 47542 47543 47544 47545 47546 47547 47548 47549 47550 47551 47552 47553 47554 47555 47556 47557 47558 47559 47560 47561 47562 47563 47564 47565 47566 47567 47568 47569 47570 47571 47572 47573 47574 47575 47576 47577 47578 47579 47580 47581 47582 47583 47584 47585 47586 47587 47588 47589 47590 47591 47592 47593 47594 47595 47596 47597 47598 47599 47600 47601 47602 47603 47604 47605 47606 47607 47608 47609 47610 47611 47612 47613 47614 47615 47616 47617 47618 47619 47620 47621 47622 47623 47624 47625 47626 47627 47628 47629 47630 47631 47632 47633 47634 47635 47636 47637 47638 47639 47640 47641 47642 47643 47644 47645 47646 47647 47648 47649 47650 47651 47652 47653 47654 47655 47656 47657 47658 47659 47660 47661 47662 47663 47664 47665 47666 47667 47668 47669 47670 47671 47672 47673 47674 47675 47676 47677 47678 47679 47680 47681 47682 47683 47684 47685 47686 47687 47688 47689 47690 47691 47692 47693 47694 47695 47696 47697 47698 47699 47700 47701 47702 47703 47704 47705 47706 47707 47708 47709 47710 47711 47712 47713 47714 47715 47716 47717 47718 47719 47720 47721 47722 47723 47724 47725 47726 47727 47728 47729 47730 47731 47732 47733 47734 47735 47736 47737 47738 47739 47740 47741 47742 47743 47744 47745 47746 47747 47748 47749 47750 47751 47752 47753 47754 47755 47756 47757 47758 47759 47760 47761 47762 47763 47764 47765 47766 47767 47768 47769 47770 47771 47772 47773 47774 47775 47776 47777 47778 47779 47780 47781 47782 47783 47784 47785 47786 47787 47788 47789 47790 47791 47792 47793 47794 47795 47796 47797 47798 47799 47800 47801 47802 47803 47804 47805 47806 47807 47808 47809 47810 47811 47812 47813 47814 47815 47816 47817 47818 47819 47820 47821 47822 47823 47824 47825 47826 47827 47828 47829 47830 47831 47832 47833 47834 47835 47836 47837 47838 47839 47840 47841 47842 47843 47844 47845 47846 47847 47848 47849 47850 47851 47852 47853 47854 47855 47856 47857 47858 47859 47860 47861 47862 47863 47864 47865 47866 47867 47868 47869 47870 47871 47872 47873 47874 47875 47876 47877 47878 47879 47880 47881 47882 47883 47884 47885 47886 47887 47888 47889 47890 47891 47892 47893 47894 47895 47896 47897 47898 47899 47900 47901 47902 47903 47904 47905 47906 47907 47908 47909 47910 47911 47912 47913 47914 47915 47916 47917 47918 47919 47920 47921 47922 47923 47924 47925 47926 47927 47928 47929 47930 47931 47932 47933 47934 47935 47936 47937 47938 47939 47940 47941 47942 47943 47944 47945 47946 47947 47948 47949 47950 47951 47952 47953 47954 47955 47956 47957 47958 47959 47960 47961 47962 47963 47964 47965 47966 47967 47968 47969 47970 47971 47972 47973 47974 47975 47976 47977 47978 47979 47980 47981 47982 47983 47984 47985 47986 47987 47988 47989 47990 47991 47992 47993 47994 47995 47996 47997 47998 47999 48000 48001 48002 48003 48004 48005 48006 48007 48008 48009 48010 48011 48012 48013 48014 48015 48016 48017 48018 48019 48020 48021 48022 48023 48024 48025 48026 48027 48028 48029 48030 48031 48032 48033 48034 48035 48036 48037 48038 48039 48040 48041 48042 48043 48044 48045 48046 48047 48048 48049 48050 48051 48052 48053 48054 48055 48056 48057 48058 48059 48060 48061 48062 48063 48064 48065 48066 48067 48068 48069 48070 48071 48072 48073 48074 48075 48076 48077 48078 48079 48080 48081 48082 48083 48084 48085 48086 48087 48088 48089 48090 48091 48092 48093 48094 48095 48096 48097 48098 48099 48100 48101 48102 48103 48104 48105 48106 48107 48108 48109 48110 48111 48112 48113 48114 48115 48116 48117 48118 48119 48120 48121 48122 48123 48124 48125 48126 48127 48128 48129 48130 48131 48132 48133 48134 48135 48136 48137 48138 48139 48140 48141 48142 48143 48144 48145 48146 48147 48148 48149 48150 48151 48152 48153 48154 48155 48156 48157 48158 48159 48160 48161 48162 48163 48164 48165 48166 48167 48168 48169 48170 48171 48172 48173 48174 48175 48176 48177 48178 48179 48180 48181 48182 48183 48184 48185 48186 48187 48188 48189 48190 48191 48192 48193 48194 48195 48196 48197 48198 48199 48200 48201 48202 48203 48204 48205 48206 48207 48208 48209 48210 48211 48212 48213 48214 48215 48216 48217 48218 48219 48220 48221 48222 48223 48224 48225 48226 48227 48228 48229 48230 48231 48232 48233 48234 48235 48236 48237 48238 48239 48240 48241 48242 48243 48244 48245 48246 48247 48248 48249 48250 48251 48252 48253 48254 48255 48256 48257 48258 48259 48260 48261 48262 48263 48264 48265 48266 48267 48268 48269 48270 48271 48272 48273 48274 48275 48276 48277 48278 48279 48280 48281 48282 48283 48284 48285 48286 48287 48288 48289 48290 48291 48292 48293 48294 48295 48296 48297 48298 48299 48300 48301 48302 48303 48304 48305 48306 48307 48308 48309 48310 48311 48312 48313 48314 48315 48316 48317 48318 48319 48320 48321 48322 48323 48324 48325 48326 48327 48328 48329 48330 48331 48332 48333 48334 48335 48336 48337 48338 48339 48340 48341 48342 48343 48344 48345 48346 48347 48348 48349 48350 48351 48352 48353 48354 48355 48356 48357 48358 48359 48360 48361 48362 48363 48364 48365 48366 48367 48368 48369 48370 48371 48372 48373 48374 48375 48376 48377 48378 48379 48380 48381 48382 48383 48384 48385 48386 48387 48388 48389 48390 48391 48392 48393 48394 48395 48396 48397 48398 48399 48400 48401 48402 48403 48404 48405 48406 48407 48408 48409 48410 48411 48412 48413 48414 48415 48416 48417 48418 48419 48420 48421 48422 48423 48424 48425 48426 48427 48428 48429 48430 48431 48432 48433 48434 48435 48436 48437 48438 48439 48440 48441 48442 48443 48444 48445 48446 48447 48448 48449 48450 48451 48452 48453 48454 48455 48456 48457 48458 48459 48460 48461 48462 48463 48464 48465 48466 48467 48468 48469 48470 48471 48472 48473 48474 48475 48476 48477 48478 48479 48480 48481 48482 48483 48484 48485 48486 48487 48488 48489 48490 48491 48492 48493 48494 48495 48496 48497 48498 48499 48500 48501 48502 48503 48504 48505 48506 48507 48508 48509 48510 48511 48512 48513 48514 48515 48516 48517 48518 48519 48520 48521 48522 48523 48524 48525 48526 48527 48528 48529 48530 48531 48532 48533 48534 48535 48536 48537 48538 48539 48540 48541 48542 48543 48544 48545 48546 48547 48548 48549 48550 48551 48552 48553 48554 48555 48556 48557 48558 48559 48560 48561 48562 48563 48564 48565 48566 48567 48568 48569 48570 48571 48572 48573 48574 48575 48576 48577 48578 48579 48580 48581 48582 48583 48584 48585 48586 48587 48588 48589 48590 48591 48592 48593 48594 48595 48596 48597 48598 48599 48600 48601 48602 48603 48604 48605 48606 48607 48608 48609 48610 48611 48612 48613 48614 48615 48616 48617 48618 48619 48620 48621 48622 48623 48624 48625 48626 48627 48628 48629 48630 48631 48632 48633 48634 48635 48636 48637 48638 48639 48640 48641 48642 48643 48644 48645 48646 48647 48648 48649 48650 48651 48652 48653 48654 48655 48656 48657 48658 48659 48660 48661 48662 48663 48664 48665 48666 48667 48668 48669 48670 48671 48672 48673 48674 48675 48676 48677 48678 48679 48680 48681 48682 48683 48684 48685 48686 48687 48688 48689 48690 48691 48692 48693 48694 48695 48696 48697 48698 48699 48700 48701 48702 48703 48704 48705 48706 48707 48708 48709 48710 48711 48712 48713 48714 48715 48716 48717 48718 48719 48720 48721 48722 48723 48724 48725 48726 48727 48728 48729 48730 48731 48732 48733 48734 48735 48736 48737 48738 48739 48740 48741 48742 48743 48744 48745 48746 48747 48748 48749 48750 48751 48752 48753 48754 48755 48756 48757 48758 48759 48760 48761 48762 48763 48764 48765 48766 48767 48768 48769 48770 48771 48772 48773 48774 48775 48776 48777 48778 48779 48780 48781 48782 48783 48784 48785 48786 48787 48788 48789 48790 48791 48792 48793 48794 48795 48796 48797 48798 48799 48800 48801 48802 48803 48804 48805 48806 48807 48808 48809 48810 48811 48812 48813 48814 48815 48816 48817 48818 48819 48820 48821 48822 48823 48824 48825 48826 48827 48828 48829 48830 48831 48832 48833 48834 48835 48836 48837 48838 48839 48840 48841 48842 48843 48844 48845 48846 48847 48848 48849 48850 48851 48852 48853 48854 48855 48856 48857 48858 48859 48860 48861 48862 48863 48864 48865 48866 48867 48868 48869 48870 48871 48872 48873 48874 48875 48876 48877 48878 48879 48880 48881 48882 48883 48884 48885 48886 48887 48888 48889 48890 48891 48892 48893 48894 48895 48896 48897 48898 48899 48900 48901 48902 48903 48904 48905 48906 48907 48908 48909 48910 48911 48912 48913 48914 48915 48916 48917 48918 48919 48920 48921 48922 48923 48924 48925 48926 48927 48928 48929 48930 48931 48932 48933 48934 48935 48936 48937 48938 48939 48940 48941 48942 48943 48944 48945 48946 48947 48948 48949 48950 48951 48952 48953 48954 48955 48956 48957 48958 48959 48960 48961 48962 48963 48964 48965 48966 48967 48968 48969 48970 48971 48972 48973 48974 48975 48976 48977 48978 48979 48980 48981 48982 48983 48984 48985 48986 48987 48988 48989 48990 48991 48992 48993 48994 48995 48996 48997 48998 48999 49000 49001 49002 49003 49004 49005 49006 49007 49008 49009 49010 49011 49012 49013 49014 49015 49016 49017 49018 49019 49020 49021 49022 49023 49024 49025 49026 49027 49028 49029 49030 49031 49032 49033 49034 49035 49036 49037 49038 49039 49040 49041 49042 49043 49044 49045 49046 49047 49048 49049 49050 49051 49052 49053 49054 49055 49056 49057 49058 49059 49060 49061 49062 49063 49064 49065 49066 49067 49068 49069 49070 49071 49072 49073 49074 49075 49076 49077 49078 49079 49080 49081 49082 49083 49084 49085 49086 49087 49088 49089 49090 49091 49092 49093 49094 49095 49096 49097 49098 49099 49100 49101 49102 49103 49104 49105 49106 49107 49108 49109 49110 49111 49112 49113 49114 49115 49116 49117 49118 49119 49120 49121 49122 49123 49124 49125 49126 49127 49128 49129 49130 49131 49132 49133 49134 49135 49136 49137 49138 49139 49140 49141 49142 49143 49144 49145 49146 49147 49148 49149 49150 49151 49152 49153 49154 49155 49156 49157 49158 49159 49160 49161 49162 49163 49164 49165 49166 49167 49168 49169 49170 49171 49172 49173 49174 49175 49176 49177 49178 49179 49180 49181 49182 49183 49184 49185 49186 49187 49188 49189 49190 49191 49192 49193 49194 49195 49196 49197 49198 49199 49200 49201 49202 49203 49204 49205 49206 49207 49208 49209 49210 49211 49212 49213 49214 49215 49216 49217 49218 49219 49220 49221 49222 49223 49224 49225 49226 49227 49228 49229 49230 49231 49232 49233 49234 49235 49236 49237 49238 49239 49240 49241 49242 49243 49244 49245 49246 49247 49248 49249 49250 49251 49252 49253 49254 49255 49256 49257 49258 49259 49260 49261 49262 49263 49264 49265 49266 49267 49268 49269 49270 49271 49272 49273 49274 49275 49276 49277 49278 49279 49280 49281 49282 49283 49284 49285 49286 49287 49288 49289 49290 49291 49292 49293 49294 49295 49296 49297 49298 49299 49300 49301 49302 49303 49304 49305 49306 49307 49308 49309 49310 49311 49312 49313 49314 49315 49316 49317 49318 49319 49320 49321 49322 49323 49324 49325 49326 49327 49328 49329 49330 49331 49332 49333 49334 49335 49336 49337 49338 49339 49340 49341 49342 49343 49344 49345 49346 49347 49348 49349 49350 49351 49352 49353 49354 49355 49356 49357 49358 49359 49360 49361 49362 49363 49364 49365 49366 49367 49368 49369 49370 49371 49372 49373 49374 49375 49376 49377 49378 49379 49380 49381 49382 49383 49384 49385 49386 49387 49388 49389 49390 49391 49392 49393 49394 49395 49396 49397 49398 49399 49400 49401 49402 49403 49404 49405 49406 49407 49408 49409 49410 49411 49412 49413 49414 49415 49416 49417 49418 49419 49420 49421 49422 49423 49424 49425 49426 49427 49428 49429 49430 49431 49432 49433 49434 49435 49436 49437 49438 49439 49440 49441 49442 49443 49444 49445 49446 49447 49448 49449 49450 49451 49452 49453 49454 49455 49456 49457 49458 49459 49460 49461 49462 49463 49464 49465 49466 49467 49468 49469 49470 49471 49472 49473 49474 49475 49476 49477 49478 49479 49480 49481 49482 49483 49484 49485 49486 49487 49488 49489 49490 49491 49492 49493 49494 49495 49496 49497 49498 49499 49500 49501 49502 49503 49504 49505 49506 49507 49508 49509 49510 49511 49512 49513 49514 49515 49516 49517 49518 49519 49520 49521 49522 49523 49524 49525 49526 49527 49528 49529 49530 49531 49532 49533 49534 49535 49536 49537 49538 49539 49540 49541 49542 49543 49544 49545 49546 49547 49548 49549 49550 49551 49552 49553 49554 49555 49556 49557 49558 49559 49560 49561 49562 49563 49564 49565 49566 49567 49568 49569 49570 49571 49572 49573 49574 49575 49576 49577 49578 49579 49580 49581 49582 49583 49584 49585 49586 49587 49588 49589 49590 49591 49592 49593 49594 49595 49596 49597 49598 49599 49600 49601 49602 49603 49604 49605 49606 49607 49608 49609 49610 49611 49612 49613 49614 49615 49616 49617 49618 49619 49620 49621 49622 49623 49624 49625 49626 49627 49628 49629 49630 49631 49632 49633 49634 49635 49636 49637 49638 49639 49640 49641 49642 49643 49644 49645 49646 49647 49648 49649 49650 49651 49652 49653 49654 49655 49656 49657 49658 49659 49660 49661 49662 49663 49664 49665 49666 49667 49668 49669 49670 49671 49672 49673 49674 49675 49676 49677 49678 49679 49680 49681 49682 49683 49684 49685 49686 49687 49688 49689 49690 49691 49692 49693 49694 49695 49696 49697 49698 49699 49700 49701 49702 49703 49704 49705 49706 49707 49708 49709 49710 49711 49712 49713 49714 49715 49716 49717 49718 49719 49720 49721 49722 49723 49724 49725 49726 49727 49728 49729 49730 49731 49732 49733 49734 49735 49736 49737 49738 49739 49740 49741 49742 49743 49744 49745 49746 49747 49748 49749 49750 49751 49752 49753 49754 49755 49756 49757 49758 49759 49760 49761 49762 49763 49764 49765 49766 49767 49768 49769 49770 49771 49772 49773 49774 49775 49776 49777 49778 49779 49780 49781 49782 49783 49784 49785 49786 49787 49788 49789 49790 49791 49792 49793 49794 49795 49796 49797 49798 49799 49800 49801 49802 49803 49804 49805 49806 49807 49808 49809 49810 49811 49812 49813 49814 49815 49816 49817 49818 49819 49820 49821 49822 49823 49824 49825 49826 49827 49828 49829 49830 49831 49832 49833 49834 49835 49836 49837 49838 49839 49840 49841 49842 49843 49844 49845 49846 49847 49848 49849 49850 49851 49852 49853 49854 49855 49856 49857 49858 49859 49860 49861 49862 49863 49864 49865 49866 49867 49868 49869 49870 49871 49872 49873 49874 49875 49876 49877 49878 49879 49880 49881 49882 49883 49884 49885 49886 49887 49888 49889 49890 49891 49892 49893 49894 49895 49896 49897 49898 49899 49900 49901 49902 49903 49904 49905 49906 49907 49908 49909 49910 49911 49912 49913 49914 49915 49916 49917 49918 49919 49920 49921 49922 49923 49924 49925 49926 49927 49928 49929 49930 49931 49932 49933 49934 49935 49936 49937 49938 49939 49940 49941 49942 49943 49944 49945 49946 49947 49948 49949 49950 49951 49952 49953 49954 49955 49956 49957 49958 49959 49960 49961 49962 49963 49964 49965 49966 49967 49968 49969 49970 49971 49972 49973 49974 49975 49976 49977 49978 49979 49980 49981 49982 49983 49984 49985 49986 49987 49988 49989 49990 49991 49992 49993 49994 49995 49996 49997 49998 49999 50000 50001 50002 50003 50004 50005 50006 50007 50008 50009 50010 50011 50012 50013 50014 50015 50016 50017 50018 50019 50020 50021 50022 50023 50024 50025 50026 50027 50028 50029 50030 50031 50032 50033 50034 50035 50036 50037 50038 50039 50040 50041 50042 50043 50044 50045 50046 50047 50048 50049 50050 50051 50052 50053 50054 50055 50056 50057 50058 50059 50060 50061 50062 50063 50064 50065 50066 50067 50068 50069 50070 50071 50072 50073 50074 50075 50076 50077 50078 50079 50080 50081 50082 50083 50084 50085 50086 50087 50088 50089 50090 50091 50092 50093 50094 50095 50096 50097 50098 50099 50100 50101 50102 50103 50104 50105 50106 50107 50108 50109 50110 50111 50112 50113 50114 50115 50116 50117 50118 50119 50120 50121 50122 50123 50124 50125 50126 50127 50128 50129 50130 50131 50132 50133 50134 50135 50136 50137 50138 50139 50140 50141 50142 50143 50144 50145 50146 50147 50148 50149 50150 50151 50152 50153 50154 50155 50156 50157 50158 50159 50160 50161 50162 50163 50164 50165 50166 50167 50168 50169 50170 50171 50172 50173 50174 50175 50176 50177 50178 50179 50180 50181 50182 50183 50184 50185 50186 50187 50188 50189 50190 50191 50192 50193 50194 50195 50196 50197 50198 50199 50200 50201 50202 50203 50204 50205 50206 50207 50208 50209 50210 50211 50212 50213 50214 50215 50216 50217 50218 50219 50220 50221 50222 50223 50224 50225 50226 50227 50228 50229 50230 50231 50232 50233 50234 50235 50236 50237 50238 50239 50240 50241 50242 50243 50244 50245 50246 50247 50248 50249 50250 50251 50252 50253 50254 50255 50256 50257 50258 50259 50260 50261 50262 50263 50264 50265 50266 50267 50268 50269 50270 50271 50272 50273 50274 50275 50276 50277 50278 50279 50280 50281 50282 50283 50284 50285 50286 50287 50288 50289 50290 50291 50292 50293 50294 50295 50296 50297 50298 50299 50300 50301 50302 50303 50304 50305 50306 50307 50308 50309 50310 50311 50312 50313 50314 50315 50316 50317 50318 50319 50320 50321 50322 50323 50324 50325 50326 50327 50328 50329 50330 50331 50332 50333 50334 50335 50336 50337 50338 50339 50340 50341 50342 50343 50344 50345 50346 50347 50348 50349 50350 50351 50352 50353 50354 50355 50356 50357 50358 50359 50360 50361 50362 50363 50364 50365 50366 50367 50368 50369 50370 50371 50372 50373 50374 50375 50376 50377 50378 50379 50380 50381 50382 50383 50384 50385 50386 50387 50388 50389 50390 50391 50392 50393 50394 50395 50396 50397 50398 50399 50400 50401 50402 50403 50404 50405 50406 50407 50408 50409 50410 50411 50412 50413 50414 50415 50416 50417 50418 50419 50420 50421 50422 50423 50424 50425 50426 50427 50428 50429 50430 50431 50432 50433 50434 50435 50436 50437 50438 50439 50440 50441 50442 50443 50444 50445 50446 50447 50448 50449 50450 50451 50452 50453 50454 50455 50456 50457 50458 50459 50460 50461 50462 50463 50464 50465 50466 50467 50468 50469 50470 50471 50472 50473 50474 50475 50476 50477 50478 50479 50480 50481 50482 50483 50484 50485 50486 50487 50488 50489 50490 50491 50492 50493 50494 50495 50496 50497 50498 50499 50500 50501 50502 50503 50504 50505 50506 50507 50508 50509 50510 50511 50512 50513 50514 50515 50516 50517 50518 50519 50520 50521 50522 50523 50524 50525 50526 50527 50528 50529 50530 50531 50532 50533 50534 50535 50536 50537 50538 50539 50540 50541 50542 50543 50544 50545 50546 50547 50548 50549 50550 50551 50552 50553 50554 50555 50556 50557 50558 50559 50560 50561 50562 50563 50564 50565 50566 50567 50568 50569 50570 50571 50572 50573 50574 50575 50576 50577 50578 50579 50580 50581 50582 50583 50584 50585 50586 50587 50588 50589 50590 50591 50592 50593 50594 50595 50596 50597 50598 50599 50600 50601 50602 50603 50604 50605 50606 50607 50608 50609 50610 50611 50612 50613 50614 50615 50616 50617 50618 50619 50620 50621 50622 50623 50624 50625 50626 50627 50628 50629 50630 50631 50632 50633 50634 50635 50636 50637 50638 50639 50640 50641 50642 50643 50644 50645 50646 50647 50648 50649 50650 50651 50652 50653 50654 50655 50656 50657 50658 50659 50660 50661 50662 50663 50664 50665 50666 50667 50668 50669 50670 50671 50672 50673 50674 50675 50676 50677 50678 50679 50680 50681 50682 50683 50684 50685 50686 50687 50688 50689 50690 50691 50692 50693 50694 50695 50696 50697 50698 50699 50700 50701 50702 50703 50704 50705 50706 50707 50708 50709 50710 50711 50712 50713 50714 50715 50716 50717 50718 50719 50720 50721 50722 50723 50724 50725 50726 50727 50728 50729 50730 50731 50732 50733 50734 50735 50736 50737 50738 50739 50740 50741 50742 50743 50744 50745 50746 50747 50748 50749 50750 50751 50752 50753 50754 50755 50756 50757 50758 50759 50760 50761 50762 50763 50764 50765 50766 50767 50768 50769 50770 50771 50772 50773 50774 50775 50776 50777 50778 50779 50780 50781 50782 50783 50784 50785 50786 50787 50788 50789 50790 50791 50792 50793 50794 50795 50796 50797 50798 50799 50800 50801 50802 50803 50804 50805 50806 50807 50808 50809 50810 50811 50812 50813 50814 50815 50816 50817 50818 50819 50820 50821 50822 50823 50824 50825 50826 50827 50828 50829 50830 50831 50832 50833 50834 50835 50836 50837 50838 50839 50840 50841 50842 50843 50844 50845 50846 50847 50848 50849 50850 50851 50852 50853 50854 50855 50856 50857 50858 50859 50860 50861 50862 50863 50864 50865 50866 50867 50868 50869 50870 50871 50872 50873 50874 50875 50876 50877 50878 50879 50880 50881 50882 50883 50884 50885 50886 50887 50888 50889 50890 50891 50892 50893 50894 50895 50896 50897 50898 50899 50900 50901 50902 50903 50904 50905 50906 50907 50908 50909 50910 50911 50912 50913 50914 50915 50916 50917 50918 50919 50920 50921 50922 50923 50924 50925 50926 50927 50928 50929 50930 50931 50932 50933 50934 50935 50936 50937 50938 50939 50940 50941 50942 50943 50944 50945 50946 50947 50948 50949 50950 50951 50952 50953 50954 50955 50956 50957 50958 50959 50960 50961 50962 50963 50964 50965 50966 50967 50968 50969 50970 50971 50972 50973 50974 50975 50976 50977 50978 50979 50980 50981 50982 50983 50984 50985 50986 50987 50988 50989 50990 50991 50992 50993 50994 50995 50996 50997 50998 50999 51000 51001 51002 51003 51004 51005 51006 51007 51008 51009 51010 51011 51012 51013 51014 51015 51016 51017 51018 51019 51020 51021 51022 51023 51024 51025 51026 51027 51028 51029 51030 51031 51032 51033 51034 51035 51036 51037 51038 51039 51040 51041 51042 51043 51044 51045 51046 51047 51048 51049 51050 51051 51052 51053 51054 51055 51056 51057 51058 51059 51060 51061 51062 51063 51064 51065 51066 51067 51068 51069 51070 51071 51072 51073 51074 51075 51076 51077 51078 51079 51080 51081 51082 51083 51084 51085 51086 51087 51088 51089 51090 51091 51092 51093 51094 51095 51096 51097 51098 51099 51100 51101 51102 51103 51104 51105 51106 51107 51108 51109 51110 51111 51112 51113 51114 51115 51116 51117 51118 51119 51120 51121 51122 51123 51124 51125 51126 51127 51128 51129 51130 51131 51132 51133 51134 51135 51136 51137 51138 51139 51140 51141 51142 51143 51144 51145 51146 51147 51148 51149 51150 51151 51152 51153 51154 51155 51156 51157 51158 51159 51160 51161 51162 51163 51164 51165 51166 51167 51168 51169 51170 51171 51172 51173 51174 51175 51176 51177 51178 51179 51180 51181 51182 51183 51184 51185 51186 51187 51188 51189 51190 51191 51192 51193 51194 51195 51196 51197 51198 51199 51200 51201 51202 51203 51204 51205 51206 51207 51208 51209 51210 51211 51212 51213 51214 51215 51216 51217 51218 51219 51220 51221 51222 51223 51224 51225 51226 51227 51228 51229 51230 51231 51232 51233 51234 51235 51236 51237 51238 51239 51240 51241 51242 51243 51244 51245 51246 51247 51248 51249 51250 51251 51252 51253 51254 51255 51256 51257 51258 51259 51260 51261 51262 51263 51264 51265 51266 51267 51268 51269 51270 51271 51272 51273 51274 51275 51276 51277 51278 51279 51280 51281 51282 51283 51284 51285 51286 51287 51288 51289 51290 51291 51292 51293 51294 51295 51296 51297 51298 51299 51300 51301 51302 51303 51304 51305 51306 51307 51308 51309 51310 51311 51312 51313 51314 51315 51316 51317 51318 51319 51320 51321 51322 51323 51324 51325 51326 51327 51328 51329 51330 51331 51332 51333 51334 51335 51336 51337 51338 51339 51340 51341 51342 51343 51344 51345 51346 51347 51348 51349 51350 51351 51352 51353 51354 51355 51356 51357 51358 51359 51360 51361 51362 51363 51364 51365 51366 51367 51368 51369 51370 51371 51372 51373 51374 51375 51376 51377 51378 51379 51380 51381 51382 51383 51384 51385 51386 51387 51388 51389 51390 51391 51392 51393 51394 51395 51396 51397 51398 51399 51400 51401 51402 51403 51404 51405 51406 51407 51408 51409 51410 51411 51412 51413 51414 51415 51416 51417 51418 51419 51420 51421 51422 51423 51424 51425 51426 51427 51428 51429 51430 51431 51432 51433 51434 51435 51436 51437 51438 51439 51440 51441 51442 51443 51444 51445 51446 51447 51448 51449 51450 51451 51452 51453 51454 51455 51456 51457 51458 51459 51460 51461 51462 51463 51464 51465 51466 51467 51468 51469 51470 51471 51472 51473 51474 51475 51476 51477 51478 51479 51480 51481 51482 51483 51484 51485 51486 51487 51488 51489 51490 51491 51492 51493 51494 51495 51496 51497 51498 51499 51500 51501 51502 51503 51504 51505 51506 51507 51508 51509 51510 51511 51512 51513 51514 51515 51516 51517 51518 51519 51520 51521 51522 51523 51524 51525 51526 51527 51528 51529 51530 51531 51532 51533 51534 51535 51536 51537 51538 51539 51540 51541 51542 51543 51544 51545 51546 51547 51548 51549 51550 51551 51552 51553 51554 51555 51556 51557 51558 51559 51560 51561 51562 51563 51564 51565 51566 51567 51568 51569 51570 51571 51572 51573 51574 51575 51576 51577 51578 51579 51580 51581 51582 51583 51584 51585 51586 51587 51588 51589 51590 51591 51592 51593 51594 51595 51596 51597 51598 51599 51600 51601 51602 51603 51604 51605 51606 51607 51608 51609 51610 51611 51612 51613 51614 51615 51616 51617 51618 51619 51620 51621 51622 51623 51624 51625 51626 51627 51628 51629 51630 51631 51632 51633 51634 51635 51636 51637 51638 51639 51640 51641 51642 51643 51644 51645 51646 51647 51648 51649 51650 51651 51652 51653 51654 51655 51656 51657 51658 51659 51660 51661 51662 51663 51664 51665 51666 51667 51668 51669 51670 51671 51672 51673 51674 51675 51676 51677 51678 51679 51680 51681 51682 51683 51684 51685 51686 51687 51688 51689 51690 51691 51692 51693 51694 51695 51696 51697 51698 51699 51700 51701 51702 51703 51704 51705 51706 51707 51708 51709 51710 51711 51712 51713 51714 51715 51716 51717 51718 51719 51720 51721 51722 51723 51724 51725 51726 51727 51728 51729 51730 51731 51732 51733 51734 51735 51736 51737 51738 51739 51740 51741 51742 51743 51744 51745 51746 51747 51748 51749 51750 51751 51752 51753 51754 51755 51756 51757 51758 51759 51760 51761 51762 51763 51764 51765 51766 51767 51768 51769 51770 51771 51772 51773 51774 51775 51776 51777 51778 51779 51780 51781 51782 51783 51784 51785 51786 51787 51788 51789 51790 51791 51792 51793 51794 51795 51796 51797 51798 51799 51800 51801 51802 51803 51804 51805 51806 51807 51808 51809 51810 51811 51812 51813 51814 51815 51816 51817 51818 51819 51820 51821 51822 51823 51824 51825 51826 51827 51828 51829 51830 51831 51832 51833 51834 51835 51836 51837 51838 51839 51840 51841 51842 51843 51844 51845 51846 51847 51848 51849 51850 51851 51852 51853 51854 51855 51856 51857 51858 51859 51860 51861 51862 51863 51864 51865 51866 51867 51868 51869 51870 51871 51872 51873 51874 51875 51876 51877 51878 51879 51880 51881 51882 51883 51884 51885 51886 51887 51888 51889 51890 51891 51892 51893 51894 51895 51896 51897 51898 51899 51900 51901 51902 51903 51904 51905 51906 51907 51908 51909 51910 51911 51912 51913 51914 51915 51916 51917 51918 51919 51920 51921 51922 51923 51924 51925 51926 51927 51928 51929 51930 51931 51932 51933 51934 51935 51936 51937 51938 51939 51940 51941 51942 51943 51944 51945 51946 51947 51948 51949 51950 51951 51952 51953 51954 51955 51956 51957 51958 51959 51960 51961 51962 51963 51964 51965 51966 51967 51968 51969 51970 51971 51972 51973 51974 51975 51976 51977 51978 51979 51980 51981 51982 51983 51984 51985 51986 51987 51988 51989 51990 51991 51992 51993 51994 51995 51996 51997 51998 51999 52000 52001 52002 52003 52004 52005 52006 52007 52008 52009 52010 52011 52012 52013 52014 52015 52016 52017 52018 52019 52020 52021 52022 52023 52024 52025 52026 52027 52028 52029 52030 52031 52032 52033 52034 52035 52036 52037 52038 52039 52040 52041 52042 52043 52044 52045 52046 52047 52048 52049 52050 52051 52052 52053 52054 52055 52056 52057 52058 52059 52060 52061 52062 52063 52064 52065 52066 52067 52068 52069 52070 52071 52072 52073 52074 52075 52076 52077 52078 52079 52080 52081 52082 52083 52084 52085 52086 52087 52088 52089 52090 52091 52092 52093 52094 52095 52096 52097 52098 52099 52100 52101 52102 52103 52104 52105 52106 52107 52108 52109 52110 52111 52112 52113 52114 52115 52116 52117 52118 52119 52120 52121 52122 52123 52124 52125 52126 52127 52128 52129 52130 52131 52132 52133 52134 52135 52136 52137 52138 52139 52140 52141 52142 52143 52144 52145 52146 52147 52148 52149 52150 52151 52152 52153 52154 52155 52156 52157 52158 52159 52160 52161 52162 52163 52164 52165 52166 52167 52168 52169 52170 52171 52172 52173 52174 52175 52176 52177 52178 52179 52180 52181 52182 52183 52184 52185 52186 52187 52188 52189 52190 52191 52192 52193 52194 52195 52196 52197 52198 52199 52200 52201 52202 52203 52204 52205 52206 52207 52208 52209 52210 52211 52212 52213 52214 52215 52216 52217 52218 52219 52220 52221 52222 52223 52224 52225 52226 52227 52228 52229 52230 52231 52232 52233 52234 52235 52236 52237 52238 52239 52240 52241 52242 52243 52244 52245 52246 52247 52248 52249 52250 52251 52252 52253 52254 52255 52256 52257 52258 52259 52260 52261 52262 52263 52264 52265 52266 52267 52268 52269 52270 52271 52272 52273 52274 52275 52276 52277 52278 52279 52280 52281 52282 52283 52284 52285 52286 52287 52288 52289 52290 52291 52292 52293 52294 52295 52296 52297 52298 52299 52300 52301 52302 52303 52304 52305 52306 52307 52308 52309 52310 52311 52312 52313 52314 52315 52316 52317 52318 52319 52320 52321 52322 52323 52324 52325 52326 52327 52328 52329 52330 52331 52332 52333 52334 52335 52336 52337 52338 52339 52340 52341 52342 52343 52344 52345 52346 52347 52348 52349 52350 52351 52352 52353 52354 52355 52356 52357 52358 52359 52360 52361 52362 52363 52364 52365 52366 52367 52368 52369 52370 52371 52372 52373 52374 52375 52376 52377 52378 52379 52380 52381 52382 52383 52384 52385 52386 52387 52388 52389 52390 52391 52392 52393 52394 52395 52396 52397 52398 52399 52400 52401 52402 52403 52404 52405 52406 52407 52408 52409 52410 52411 52412 52413 52414 52415 52416 52417 52418 52419 52420 52421 52422 52423 52424 52425 52426 52427 52428 52429 52430 52431 52432 52433 52434 52435 52436 52437 52438 52439 52440 52441 52442 52443 52444 52445 52446 52447 52448 52449 52450 52451 52452 52453 52454 52455 52456 52457 52458 52459 52460 52461 52462 52463 52464 52465 52466 52467 52468 52469 52470 52471 52472 52473 52474 52475 52476 52477 52478 52479 52480 52481 52482 52483 52484 52485 52486 52487 52488 52489 52490 52491 52492 52493 52494 52495 52496 52497 52498 52499 52500 52501 52502 52503 52504 52505 52506 52507 52508 52509 52510 52511 52512 52513 52514 52515 52516 52517 52518 52519 52520 52521 52522 52523 52524 52525 52526 52527 52528 52529 52530 52531 52532 52533 52534 52535 52536 52537 52538 52539 52540 52541 52542 52543 52544 52545 52546 52547 52548 52549 52550 52551 52552 52553 52554 52555 52556 52557 52558 52559 52560 52561 52562 52563 52564 52565 52566 52567 52568 52569 52570 52571 52572 52573 52574 52575 52576 52577 52578 52579 52580 52581 52582 52583 52584 52585 52586 52587 52588 52589 52590 52591 52592 52593 52594 52595 52596 52597 52598 52599 52600 52601 52602 52603 52604 52605 52606 52607 52608 52609 52610 52611 52612 52613 52614 52615 52616 52617 52618 52619 52620 52621 52622 52623 52624 52625 52626 52627 52628 52629 52630 52631 52632 52633 52634 52635 52636 52637 52638 52639 52640 52641 52642 52643 52644 52645 52646 52647 52648 52649 52650 52651 52652 52653 52654 52655 52656 52657 52658 52659 52660 52661 52662 52663 52664 52665 52666 52667 52668 52669 52670 52671 52672 52673 52674 52675 52676 52677 52678 52679 52680 52681 52682 52683 52684 52685 52686 52687 52688 52689 52690 52691 52692 52693 52694 52695 52696 52697 52698 52699 52700 52701 52702 52703 52704 52705 52706 52707 52708 52709 52710 52711 52712 52713 52714 52715 52716 52717 52718 52719 52720 52721 52722 52723 52724 52725 52726 52727 52728 52729 52730 52731 52732 52733 52734 52735 52736 52737 52738 52739 52740 52741 52742 52743 52744 52745 52746 52747 52748 52749 52750 52751 52752 52753 52754 52755 52756 52757 52758 52759 52760 52761 52762 52763 52764 52765 52766 52767 52768 52769 52770 52771 52772 52773 52774 52775 52776 52777 52778 52779 52780 52781 52782 52783 52784 52785 52786 52787 52788 52789 52790 52791 52792 52793 52794 52795 52796 52797 52798 52799 52800 52801 52802 52803 52804 52805 52806 52807 52808 52809 52810 52811 52812 52813 52814 52815 52816 52817 52818 52819 52820 52821 52822 52823 52824 52825 52826 52827 52828 52829 52830 52831 52832 52833 52834 52835 52836 52837 52838 52839 52840 52841 52842 52843 52844 52845 52846 52847 52848 52849 52850 52851 52852 52853 52854 52855 52856 52857 52858 52859 52860 52861 52862 52863 52864 52865 52866 52867 52868 52869 52870 52871 52872 52873 52874 52875 52876 52877 52878 52879 52880 52881 52882 52883 52884 52885 52886 52887 52888 52889 52890 52891 52892 52893 52894 52895 52896 52897 52898 52899 52900 52901 52902 52903 52904 52905 52906 52907 52908 52909 52910 52911 52912 52913 52914 52915 52916 52917 52918 52919 52920 52921 52922 52923 52924 52925 52926 52927 52928 52929 52930 52931 52932 52933 52934 52935 52936 52937 52938 52939 52940 52941 52942 52943 52944 52945 52946 52947 52948 52949 52950 52951 52952 52953 52954 52955 52956 52957 52958 52959 52960 52961 52962 52963 52964 52965 52966 52967 52968 52969 52970 52971 52972 52973 52974 52975 52976 52977 52978 52979 52980 52981 52982 52983 52984 52985 52986 52987 52988 52989 52990 52991 52992 52993 52994 52995 52996 52997 52998 52999 53000 53001 53002 53003 53004 53005 53006 53007 53008 53009 53010 53011 53012 53013 53014 53015 53016 53017 53018 53019 53020 53021 53022 53023 53024 53025 53026 53027 53028 53029 53030 53031 53032 53033 53034 53035 53036 53037 53038 53039 53040 53041 53042 53043 53044 53045 53046 53047 53048 53049 53050 53051 53052 53053 53054 53055 53056 53057 53058 53059 53060 53061 53062 53063 53064 53065 53066 53067 53068 53069 53070 53071 53072 53073 53074 53075 53076 53077 53078 53079 53080 53081 53082 53083 53084 53085 53086 53087 53088 53089 53090 53091 53092 53093 53094 53095 53096 53097 53098 53099 53100 53101 53102 53103 53104 53105 53106 53107 53108 53109 53110 53111 53112 53113 53114 53115 53116 53117 53118 53119 53120 53121 53122 53123 53124 53125 53126 53127 53128 53129 53130 53131 53132 53133 53134 53135 53136 53137 53138 53139 53140 53141 53142 53143 53144 53145 53146 53147 53148 53149 53150 53151 53152 53153 53154 53155 53156 53157 53158 53159 53160 53161 53162 53163 53164 53165 53166 53167 53168 53169 53170 53171 53172 53173 53174 53175 53176 53177 53178 53179 53180 53181 53182 53183 53184 53185 53186 53187 53188 53189 53190 53191 53192 53193 53194 53195 53196 53197 53198 53199 53200 53201 53202 53203 53204 53205 53206 53207 53208 53209 53210 53211 53212 53213 53214 53215 53216 53217 53218 53219 53220 53221 53222 53223 53224 53225 53226 53227 53228 53229 53230 53231 53232 53233 53234 53235 53236 53237 53238 53239 53240 53241 53242 53243 53244 53245 53246 53247 53248 53249 53250 53251 53252 53253 53254 53255 53256 53257 53258 53259 53260 53261 53262 53263 53264 53265 53266 53267 53268 53269 53270 53271 53272 53273 53274 53275 53276 53277 53278 53279 53280 53281 53282 53283 53284 53285 53286 53287 53288 53289 53290 53291 53292 53293 53294 53295 53296 53297 53298 53299 53300 53301 53302 53303 53304 53305 53306 53307 53308 53309 53310 53311 53312 53313 53314 53315 53316 53317 53318 53319 53320 53321 53322 53323 53324 53325 53326 53327 53328 53329 53330 53331 53332 53333 53334 53335 53336 53337 53338 53339 53340 53341 53342 53343 53344 53345 53346 53347 53348 53349 53350 53351 53352 53353 53354 53355 53356 53357 53358 53359 53360 53361 53362 53363 53364 53365 53366 53367 53368 53369 53370 53371 53372 53373 53374 53375 53376 53377 53378 53379 53380 53381 53382 53383 53384 53385 53386 53387 53388 53389 53390 53391 53392 53393 53394 53395 53396 53397 53398 53399 53400 53401 53402 53403 53404 53405 53406 53407 53408 53409 53410 53411 53412 53413 53414 53415 53416 53417 53418 53419 53420 53421 53422 53423 53424 53425 53426 53427 53428 53429 53430 53431 53432 53433 53434 53435 53436 53437 53438 53439 53440 53441 53442 53443 53444 53445 53446 53447 53448 53449 53450 53451 53452 53453 53454 53455 53456 53457 53458 53459 53460 53461 53462 53463 53464 53465 53466 53467 53468 53469 53470 53471 53472 53473 53474 53475 53476 53477 53478 53479 53480 53481 53482 53483 53484 53485 53486 53487 53488 53489 53490 53491 53492 53493 53494 53495 53496 53497 53498 53499 53500 53501 53502 53503 53504 53505 53506 53507 53508 53509 53510 53511 53512 53513 53514 53515 53516 53517 53518 53519 53520 53521 53522 53523 53524 53525 53526 53527 53528 53529 53530 53531 53532 53533 53534 53535 53536 53537 53538 53539 53540 53541 53542 53543 53544 53545 53546 53547 53548 53549 53550 53551 53552 53553 53554 53555 53556 53557 53558 53559 53560 53561 53562 53563 53564 53565 53566 53567 53568 53569 53570 53571 53572 53573 53574 53575 53576 53577 53578 53579 53580 53581 53582 53583 53584 53585 53586 53587 53588 53589 53590 53591 53592 53593 53594 53595 53596 53597 53598 53599 53600 53601 53602 53603 53604 53605 53606 53607 53608 53609 53610 53611 53612 53613 53614 53615 53616 53617 53618 53619 53620 53621 53622 53623 53624 53625 53626 53627 53628 53629 53630 53631 53632 53633 53634 53635 53636 53637 53638 53639 53640 53641 53642 53643 53644 53645 53646 53647 53648 53649 53650 53651 53652 53653 53654 53655 53656 53657 53658 53659 53660 53661 53662 53663 53664 53665 53666 53667 53668 53669 53670 53671 53672 53673 53674 53675 53676 53677 53678 53679 53680 53681 53682 53683 53684 53685 53686 53687 53688 53689 53690 53691 53692 53693 53694 53695 53696 53697 53698 53699 53700 53701 53702 53703 53704 53705 53706 53707 53708 53709 53710 53711 53712 53713 53714 53715 53716 53717 53718 53719 53720 53721 53722 53723 53724 53725 53726 53727 53728 53729 53730 53731 53732 53733 53734 53735 53736 53737 53738 53739 53740 53741 53742 53743 53744 53745 53746 53747 53748 53749 53750 53751 53752 53753 53754 53755 53756 53757 53758 53759 53760 53761 53762 53763 53764 53765 53766 53767 53768 53769 53770 53771 53772 53773 53774 53775 53776 53777 53778 53779 53780 53781 53782 53783 53784 53785 53786 53787 53788 53789 53790 53791 53792 53793 53794 53795 53796 53797 53798 53799 53800 53801 53802 53803 53804 53805 53806 53807 53808 53809 53810 53811 53812 53813 53814 53815 53816 53817 53818 53819 53820 53821 53822 53823 53824 53825 53826 53827 53828 53829 53830 53831 53832 53833 53834 53835 53836 53837 53838 53839 53840 53841 53842 53843 53844 53845 53846 53847 53848 53849 53850 53851 53852 53853 53854 53855 53856 53857 53858 53859 53860 53861 53862 53863 53864 53865 53866 53867 53868 53869 53870 53871 53872 53873 53874 53875 53876 53877 53878 53879 53880 53881 53882 53883 53884 53885 53886 53887 53888 53889 53890 53891 53892 53893 53894 53895 53896 53897 53898 53899 53900 53901 53902 53903 53904 53905 53906 53907 53908 53909 53910 53911 53912 53913 53914 53915 53916 53917 53918 53919 53920 53921 53922 53923 53924 53925 53926 53927 53928 53929 53930 53931 53932 53933 53934 53935 53936 53937 53938 53939 53940 53941 53942 53943 53944 53945 53946 53947 53948 53949 53950 53951 53952 53953 53954 53955 53956 53957 53958 53959 53960 53961 53962 53963 53964 53965 53966 53967 53968 53969 53970 53971 53972 53973 53974 53975 53976 53977 53978 53979 53980 53981 53982 53983 53984 53985 53986 53987 53988 53989 53990 53991 53992 53993 53994 53995 53996 53997 53998 53999 54000 54001 54002 54003 54004 54005 54006 54007 54008 54009 54010 54011 54012 54013 54014 54015 54016 54017 54018 54019 54020 54021 54022 54023 54024 54025 54026 54027 54028 54029 54030 54031 54032 54033 54034 54035 54036 54037 54038 54039 54040 54041 54042 54043 54044 54045 54046 54047 54048 54049 54050 54051 54052 54053 54054 54055 54056 54057 54058 54059 54060 54061 54062 54063 54064 54065 54066 54067 54068 54069 54070 54071 54072 54073 54074 54075 54076 54077 54078 54079 54080 54081 54082 54083 54084 54085 54086 54087 54088 54089 54090 54091 54092 54093 54094 54095 54096 54097 54098 54099 54100 54101 54102 54103 54104 54105 54106 54107 54108 54109 54110 54111 54112 54113 54114 54115 54116 54117 54118 54119 54120 54121 54122 54123 54124 54125 54126 54127 54128 54129 54130 54131 54132 54133 54134 54135 54136 54137 54138 54139 54140 54141 54142 54143 54144 54145 54146 54147 54148 54149 54150 54151 54152 54153 54154 54155 54156 54157 54158 54159 54160 54161 54162 54163 54164 54165 54166 54167 54168 54169 54170 54171 54172 54173 54174 54175 54176 54177 54178 54179 54180 54181 54182 54183 54184 54185 54186 54187 54188 54189 54190 54191 54192 54193 54194 54195 54196 54197 54198 54199 54200 54201 54202 54203 54204 54205 54206 54207 54208 54209 54210 54211 54212 54213 54214 54215 54216 54217 54218 54219 54220 54221 54222 54223 54224 54225 54226 54227 54228 54229 54230 54231 54232 54233 54234 54235 54236 54237 54238 54239 54240 54241 54242 54243 54244 54245 54246 54247 54248 54249 54250 54251 54252 54253 54254 54255 54256 54257 54258 54259 54260 54261 54262 54263 54264 54265 54266 54267 54268 54269 54270 54271 54272 54273 54274 54275 54276 54277 54278 54279 54280 54281 54282 54283 54284 54285 54286 54287 54288 54289 54290 54291 54292 54293 54294 54295 54296 54297 54298 54299 54300 54301 54302 54303 54304 54305 54306 54307 54308 54309 54310 54311 54312 54313 54314 54315 54316 54317 54318 54319 54320 54321 54322 54323 54324 54325 54326 54327 54328 54329 54330 54331 54332 54333 54334 54335 54336 54337 54338 54339 54340 54341 54342 54343 54344 54345 54346 54347 54348 54349 54350 54351 54352 54353 54354 54355 54356 54357 54358 54359 54360 54361 54362 54363 54364 54365 54366 54367 54368 54369 54370 54371 54372 54373 54374 54375 54376 54377 54378 54379 54380 54381 54382 54383 54384 54385 54386 54387 54388 54389 54390 54391 54392 54393 54394 54395 54396 54397 54398 54399 54400 54401 54402 54403 54404 54405 54406 54407 54408 54409 54410 54411 54412 54413 54414 54415 54416 54417 54418 54419 54420 54421 54422 54423 54424 54425 54426 54427 54428 54429 54430 54431 54432 54433 54434 54435 54436 54437 54438 54439 54440 54441 54442 54443 54444 54445 54446 54447 54448 54449 54450 54451 54452 54453 54454 54455 54456 54457 54458 54459 54460 54461 54462 54463 54464 54465 54466 54467 54468 54469 54470 54471 54472 54473 54474 54475 54476 54477 54478 54479 54480 54481 54482 54483 54484 54485 54486 54487 54488 54489 54490 54491 54492 54493 54494 54495 54496 54497 54498 54499 54500 54501 54502 54503 54504 54505 54506 54507 54508 54509 54510 54511 54512 54513 54514 54515 54516 54517 54518 54519 54520 54521 54522 54523 54524 54525 54526 54527 54528 54529 54530 54531 54532 54533 54534 54535 54536 54537 54538 54539 54540 54541 54542 54543 54544 54545 54546 54547 54548 54549 54550 54551 54552 54553 54554 54555 54556 54557 54558 54559 54560 54561 54562 54563 54564 54565 54566 54567 54568 54569 54570 54571 54572 54573 54574 54575 54576 54577 54578 54579 54580 54581 54582 54583 54584 54585 54586 54587 54588 54589 54590 54591 54592 54593 54594 54595 54596 54597 54598 54599 54600 54601 54602 54603 54604 54605 54606 54607 54608 54609 54610 54611 54612 54613 54614 54615 54616 54617 54618 54619 54620 54621 54622 54623 54624 54625 54626 54627 54628 54629 54630 54631 54632 54633 54634 54635 54636 54637 54638 54639 54640 54641 54642 54643 54644 54645 54646 54647 54648 54649 54650 54651 54652 54653 54654 54655 54656 54657 54658 54659 54660 54661 54662 54663 54664 54665 54666 54667 54668 54669 54670 54671 54672 54673 54674 54675 54676 54677 54678 54679 54680 54681 54682 54683 54684 54685 54686 54687 54688 54689 54690 54691 54692 54693 54694 54695 54696 54697 54698 54699 54700 54701 54702 54703 54704 54705 54706 54707 54708 54709 54710 54711 54712 54713 54714 54715 54716 54717 54718 54719 54720 54721 54722 54723 54724 54725 54726 54727 54728 54729 54730 54731 54732 54733 54734 54735 54736 54737 54738 54739 54740 54741 54742 54743 54744 54745 54746 54747 54748 54749 54750 54751 54752 54753 54754 54755 54756 54757 54758 54759 54760 54761 54762 54763 54764 54765 54766 54767 54768 54769 54770 54771 54772 54773 54774 54775 54776 54777 54778 54779 54780 54781 54782 54783 54784 54785 54786 54787 54788 54789 54790 54791 54792 54793 54794 54795 54796 54797 54798 54799 54800 54801 54802 54803 54804 54805 54806 54807 54808 54809 54810 54811 54812 54813 54814 54815 54816 54817 54818 54819 54820 54821 54822 54823 54824 54825 54826 54827 54828 54829 54830 54831 54832 54833 54834 54835 54836 54837 54838 54839 54840 54841 54842 54843 54844 54845 54846 54847 54848 54849 54850 54851 54852 54853 54854 54855 54856 54857 54858 54859 54860 54861 54862 54863 54864 54865 54866 54867 54868 54869 54870 54871 54872 54873 54874 54875 54876 54877 54878 54879 54880 54881 54882 54883 54884 54885 54886 54887 54888 54889 54890 54891 54892 54893 54894 54895 54896 54897 54898 54899 54900 54901 54902 54903 54904 54905 54906 54907 54908 54909 54910 54911 54912 54913 54914 54915 54916 54917 54918 54919 54920 54921 54922 54923 54924 54925 54926 54927 54928 54929 54930 54931 54932 54933 54934 54935 54936 54937 54938 54939 54940 54941 54942 54943 54944 54945 54946 54947 54948 54949 54950 54951 54952 54953 54954 54955 54956 54957 54958 54959 54960 54961 54962 54963 54964 54965 54966 54967 54968 54969 54970 54971 54972 54973 54974 54975 54976 54977 54978 54979 54980 54981 54982 54983 54984 54985 54986 54987 54988 54989 54990 54991 54992 54993 54994 54995 54996 54997 54998 54999 55000 55001 55002 55003 55004 55005 55006 55007 55008 55009 55010 55011 55012 55013 55014 55015 55016 55017 55018 55019 55020 55021 55022 55023 55024 55025 55026 55027 55028 55029 55030 55031 55032 55033 55034 55035 55036 55037 55038 55039 55040 55041 55042 55043 55044 55045 55046 55047 55048 55049 55050 55051 55052 55053 55054 55055 55056 55057 55058 55059 55060 55061 55062 55063 55064 55065 55066 55067 55068 55069 55070 55071 55072 55073 55074 55075 55076 55077 55078 55079 55080 55081 55082 55083 55084 55085 55086 55087 55088 55089 55090 55091 55092 55093 55094 55095 55096 55097 55098 55099 55100 55101 55102 55103 55104 55105 55106 55107 55108 55109 55110 55111 55112 55113 55114 55115 55116 55117 55118 55119 55120 55121 55122 55123 55124 55125 55126 55127 55128 55129 55130 55131 55132 55133 55134 55135 55136 55137 55138 55139 55140 55141 55142 55143 55144 55145 55146 55147 55148 55149 55150 55151 55152 55153 55154 55155 55156 55157 55158 55159 55160 55161 55162 55163 55164 55165 55166 55167 55168 55169 55170 55171 55172 55173 55174 55175 55176 55177 55178 55179 55180 55181 55182 55183 55184 55185 55186 55187 55188 55189 55190 55191 55192 55193 55194 55195 55196 55197 55198 55199 55200 55201 55202 55203 55204 55205 55206 55207 55208 55209 55210 55211 55212 55213 55214 55215 55216 55217 55218 55219 55220 55221 55222 55223 55224 55225 55226 55227 55228 55229 55230 55231 55232 55233 55234 55235 55236 55237 55238 55239 55240 55241 55242 55243 55244 55245 55246 55247 55248 55249 55250 55251 55252 55253 55254 55255 55256 55257 55258 55259 55260 55261 55262 55263 55264 55265 55266 55267 55268 55269 55270 55271 55272 55273 55274 55275 55276 55277 55278 55279 55280 55281 55282 55283 55284 55285 55286 55287 55288 55289 55290 55291 55292 55293 55294 55295 55296 55297 55298 55299 55300 55301 55302 55303 55304 55305 55306 55307 55308 55309 55310 55311 55312 55313 55314 55315 55316 55317 55318 55319 55320 55321 55322 55323 55324 55325 55326 55327 55328 55329 55330 55331 55332 55333 55334 55335 55336 55337 55338 55339 55340 55341 55342 55343 55344 55345 55346 55347 55348 55349 55350 55351 55352 55353 55354 55355 55356 55357 55358 55359 55360 55361 55362 55363 55364 55365 55366 55367 55368 55369 55370 55371 55372 55373 55374 55375 55376 55377 55378 55379 55380 55381 55382 55383 55384 55385 55386 55387 55388 55389 55390 55391 55392 55393 55394 55395 55396 55397 55398 55399 55400 55401 55402 55403 55404 55405 55406 55407 55408 55409 55410 55411 55412 55413 55414 55415 55416 55417 55418 55419 55420 55421 55422 55423 55424 55425 55426 55427 55428 55429 55430 55431 55432 55433 55434 55435 55436 55437 55438 55439 55440 55441 55442 55443 55444 55445 55446 55447 55448 55449 55450 55451 55452 55453 55454 55455 55456 55457 55458 55459 55460 55461 55462 55463 55464 55465 55466 55467 55468 55469 55470 55471 55472 55473 55474 55475 55476 55477 55478 55479 55480 55481 55482 55483 55484 55485 55486 55487 55488 55489 55490 55491 55492 55493 55494 55495 55496 55497 55498 55499 55500 55501 55502 55503 55504 55505 55506 55507 55508 55509 55510 55511 55512 55513 55514 55515 55516 55517 55518 55519 55520 55521 55522 55523 55524 55525 55526 55527 55528 55529 55530 55531 55532 55533 55534 55535 55536 55537 55538 55539 55540 55541 55542 55543 55544 55545 55546 55547 55548 55549 55550 55551 55552 55553 55554 55555 55556 55557 55558 55559 55560 55561 55562 55563 55564 55565 55566 55567 55568 55569 55570 55571 55572 55573 55574 55575 55576 55577 55578 55579 55580 55581 55582 55583 55584 55585 55586 55587 55588 55589 55590 55591 55592 55593 55594 55595 55596 55597 55598 55599 55600 55601 55602 55603 55604 55605 55606 55607 55608 55609 55610 55611 55612 55613 55614 55615 55616 55617 55618 55619 55620 55621 55622 55623 55624 55625 55626 55627 55628 55629 55630 55631 55632 55633 55634 55635 55636 55637 55638 55639 55640 55641 55642 55643 55644 55645 55646 55647 55648 55649 55650 55651 55652 55653 55654 55655 55656 55657 55658 55659 55660 55661 55662 55663 55664 55665 55666 55667 55668 55669 55670 55671 55672 55673 55674 55675 55676 55677 55678 55679 55680 55681 55682 55683 55684 55685 55686 55687 55688 55689 55690 55691 55692 55693 55694 55695 55696 55697 55698 55699 55700 55701 55702 55703 55704 55705 55706 55707 55708 55709 55710 55711 55712 55713 55714 55715 55716 55717 55718 55719 55720 55721 55722 55723 55724 55725 55726 55727 55728 55729 55730 55731 55732 55733 55734 55735 55736 55737 55738 55739 55740 55741 55742 55743 55744 55745 55746 55747 55748 55749 55750 55751 55752 55753 55754 55755 55756 55757 55758 55759 55760 55761 55762 55763 55764 55765 55766 55767 55768 55769 55770 55771 55772 55773 55774 55775 55776 55777 55778 55779 55780 55781 55782 55783 55784 55785 55786 55787 55788 55789 55790 55791 55792 55793 55794 55795 55796 55797 55798 55799 55800 55801 55802 55803 55804 55805 55806 55807 55808 55809 55810 55811 55812 55813 55814 55815 55816 55817 55818 55819 55820 55821 55822 55823 55824 55825 55826 55827 55828 55829 55830 55831 55832 55833 55834 55835 55836 55837 55838 55839 55840 55841 55842 55843 55844 55845 55846 55847 55848 55849 55850 55851 55852 55853 55854 55855 55856 55857 55858 55859 55860 55861 55862 55863 55864 55865 55866 55867 55868 55869 55870 55871 55872 55873 55874 55875 55876 55877 55878 55879 55880 55881 55882 55883 55884 55885 55886 55887 55888 55889 55890 55891 55892 55893 55894 55895 55896 55897 55898 55899 55900 55901 55902 55903 55904 55905 55906 55907 55908 55909 55910 55911 55912 55913 55914 55915 55916 55917 55918 55919 55920 55921 55922 55923 55924 55925 55926 55927 55928 55929 55930 55931 55932 55933 55934 55935 55936 55937 55938 55939 55940 55941 55942 55943 55944 55945 55946 55947 55948 55949 55950 55951 55952 55953 55954 55955 55956 55957 55958 55959 55960 55961 55962 55963 55964 55965 55966 55967 55968 55969 55970 55971 55972 55973 55974 55975 55976 55977 55978 55979 55980 55981 55982 55983 55984 55985 55986 55987 55988 55989 55990 55991 55992 55993 55994 55995 55996 55997 55998 55999 56000 56001 56002 56003 56004 56005 56006 56007 56008 56009 56010 56011 56012 56013 56014 56015 56016 56017 56018 56019 56020 56021 56022 56023 56024 56025 56026 56027 56028 56029 56030 56031 56032 56033 56034 56035 56036 56037 56038 56039 56040 56041 56042 56043 56044 56045 56046 56047 56048 56049 56050 56051 56052 56053 56054 56055 56056 56057 56058 56059 56060 56061 56062 56063 56064 56065 56066 56067 56068 56069 56070 56071 56072 56073 56074 56075 56076 56077 56078 56079 56080 56081 56082 56083 56084 56085 56086 56087 56088 56089 56090 56091 56092 56093 56094 56095 56096 56097 56098 56099 56100 56101 56102 56103 56104 56105 56106 56107 56108 56109 56110 56111 56112 56113 56114 56115 56116 56117 56118 56119 56120 56121 56122 56123 56124 56125 56126 56127 56128 56129 56130 56131 56132 56133 56134 56135 56136 56137 56138 56139 56140 56141 56142 56143 56144 56145 56146 56147 56148 56149 56150 56151 56152 56153 56154 56155 56156 56157 56158 56159 56160 56161 56162 56163 56164 56165 56166 56167 56168 56169 56170 56171 56172 56173 56174 56175 56176 56177 56178 56179 56180 56181 56182 56183 56184 56185 56186 56187 56188 56189 56190 56191 56192 56193 56194 56195 56196 56197 56198 56199 56200 56201 56202 56203 56204 56205 56206 56207 56208 56209 56210 56211 56212 56213 56214 56215 56216 56217 56218 56219 56220 56221 56222 56223 56224 56225 56226 56227 56228 56229 56230 56231 56232 56233 56234 56235 56236 56237 56238 56239 56240 56241 56242 56243 56244 56245 56246 56247 56248 56249 56250 56251 56252 56253 56254 56255 56256 56257 56258 56259 56260 56261 56262 56263 56264 56265 56266 56267 56268 56269 56270 56271 56272 56273 56274 56275 56276 56277 56278 56279 56280 56281 56282 56283 56284 56285 56286 56287 56288 56289 56290 56291 56292 56293 56294 56295 56296 56297 56298 56299 56300 56301 56302 56303 56304 56305 56306 56307 56308 56309 56310 56311 56312 56313 56314 56315 56316 56317 56318 56319 56320 56321 56322 56323 56324 56325 56326 56327 56328 56329 56330 56331 56332 56333 56334 56335 56336 56337 56338 56339 56340 56341 56342 56343 56344 56345 56346 56347 56348 56349 56350 56351 56352 56353 56354 56355 56356 56357 56358 56359 56360 56361 56362 56363 56364 56365 56366 56367 56368 56369 56370 56371 56372 56373 56374 56375 56376 56377 56378 56379 56380 56381 56382 56383 56384 56385 56386 56387 56388 56389 56390 56391 56392 56393 56394 56395 56396 56397 56398 56399 56400 56401 56402 56403 56404 56405 56406 56407 56408 56409 56410 56411 56412 56413 56414 56415 56416 56417 56418 56419 56420 56421 56422 56423 56424 56425 56426 56427 56428 56429 56430 56431 56432 56433 56434 56435 56436 56437 56438 56439 56440 56441 56442 56443 56444 56445 56446 56447 56448 56449 56450 56451 56452 56453 56454 56455 56456 56457 56458 56459 56460 56461 56462 56463 56464 56465 56466 56467 56468 56469 56470 56471 56472 56473 56474 56475 56476 56477 56478 56479 56480 56481 56482 56483 56484 56485 56486 56487 56488 56489 56490 56491 56492 56493 56494 56495 56496 56497 56498 56499 56500 56501 56502 56503 56504 56505 56506 56507 56508 56509 56510 56511 56512 56513 56514 56515 56516 56517 56518 56519 56520 56521 56522 56523 56524 56525 56526 56527 56528 56529 56530 56531 56532 56533 56534 56535 56536 56537 56538 56539 56540 56541 56542 56543 56544 56545 56546 56547 56548 56549 56550 56551 56552 56553 56554 56555 56556 56557 56558 56559 56560 56561 56562 56563 56564 56565 56566 56567 56568 56569 56570 56571 56572 56573 56574 56575 56576 56577 56578 56579 56580 56581 56582 56583 56584 56585 56586 56587 56588 56589 56590 56591 56592 56593 56594 56595 56596 56597 56598 56599 56600 56601 56602 56603 56604 56605 56606 56607 56608 56609 56610 56611 56612 56613 56614 56615 56616 56617 56618 56619 56620 56621 56622 56623 56624 56625 56626 56627 56628 56629 56630 56631 56632 56633 56634 56635 56636 56637 56638 56639 56640 56641 56642 56643 56644 56645 56646 56647 56648 56649 56650 56651 56652 56653 56654 56655 56656 56657 56658 56659 56660 56661 56662 56663 56664 56665 56666 56667 56668 56669 56670 56671 56672 56673 56674 56675 56676 56677 56678 56679 56680 56681 56682 56683 56684 56685 56686 56687 56688 56689 56690 56691 56692 56693 56694 56695 56696 56697 56698 56699 56700 56701 56702 56703 56704 56705 56706 56707 56708 56709 56710 56711 56712 56713 56714 56715 56716 56717 56718 56719 56720 56721 56722 56723 56724 56725 56726 56727 56728 56729 56730 56731 56732 56733 56734 56735 56736 56737 56738 56739 56740 56741 56742 56743 56744 56745 56746 56747 56748 56749 56750 56751 56752 56753 56754 56755 56756 56757 56758 56759 56760 56761 56762 56763 56764 56765 56766 56767 56768 56769 56770 56771 56772 56773 56774 56775 56776 56777 56778 56779 56780 56781 56782 56783 56784 56785 56786 56787 56788 56789 56790 56791 56792 56793 56794 56795 56796 56797 56798 56799 56800 56801 56802 56803 56804 56805 56806 56807 56808 56809 56810 56811 56812 56813 56814 56815 56816 56817 56818 56819 56820 56821 56822 56823 56824 56825 56826 56827 56828 56829 56830 56831 56832 56833 56834 56835 56836 56837 56838 56839 56840 56841 56842 56843 56844 56845 56846 56847 56848 56849 56850 56851 56852 56853 56854 56855 56856 56857 56858 56859 56860 56861 56862 56863 56864 56865 56866 56867 56868 56869 56870 56871 56872 56873 56874 56875 56876 56877 56878 56879 56880 56881 56882 56883 56884 56885 56886 56887 56888 56889 56890 56891 56892 56893 56894 56895 56896 56897 56898 56899 56900 56901 56902 56903 56904 56905 56906 56907 56908 56909 56910 56911 56912 56913 56914 56915 56916 56917 56918 56919 56920 56921 56922 56923 56924 56925 56926 56927 56928 56929 56930 56931 56932 56933 56934 56935 56936 56937 56938 56939 56940 56941 56942 56943 56944 56945 56946 56947 56948 56949 56950 56951 56952 56953 56954 56955 56956 56957 56958 56959 56960 56961 56962 56963 56964 56965 56966 56967 56968 56969 56970 56971 56972 56973 56974 56975 56976 56977 56978 56979 56980 56981 56982 56983 56984 56985 56986 56987 56988 56989 56990 56991 56992 56993 56994 56995 56996 56997 56998 56999 57000 57001 57002 57003 57004 57005 57006 57007 57008 57009 57010 57011 57012 57013 57014 57015 57016 57017 57018 57019 57020 57021 57022 57023 57024 57025 57026 57027 57028 57029 57030 57031 57032 57033 57034 57035 57036 57037 57038 57039 57040 57041 57042 57043 57044 57045 57046 57047 57048 57049 57050 57051 57052 57053 57054 57055 57056 57057 57058 57059 57060 57061 57062 57063 57064 57065 57066 57067 57068 57069 57070 57071 57072 57073 57074 57075 57076 57077 57078 57079 57080 57081 57082 57083 57084 57085 57086 57087 57088 57089 57090 57091 57092 57093 57094 57095 57096 57097 57098 57099 57100 57101 57102 57103 57104 57105 57106 57107 57108 57109 57110 57111 57112 57113 57114 57115 57116 57117 57118 57119 57120 57121 57122 57123 57124 57125 57126 57127 57128 57129 57130 57131 57132 57133 57134 57135 57136 57137 57138 57139 57140 57141 57142 57143 57144 57145 57146 57147 57148 57149 57150 57151 57152 57153 57154 57155 57156 57157 57158 57159 57160 57161 57162 57163 57164 57165 57166 57167 57168 57169 57170 57171 57172 57173 57174 57175 57176 57177 57178 57179 57180 57181 57182 57183 57184 57185 57186 57187 57188 57189 57190 57191 57192 57193 57194 57195 57196 57197 57198 57199 57200 57201 57202 57203 57204 57205 57206 57207 57208 57209 57210 57211 57212 57213 57214 57215 57216 57217 57218 57219 57220 57221 57222 57223 57224 57225 57226 57227 57228 57229 57230 57231 57232 57233 57234 57235 57236 57237 57238 57239 57240 57241 57242 57243 57244 57245 57246 57247 57248 57249 57250 57251 57252 57253 57254 57255 57256 57257 57258 57259 57260 57261 57262 57263 57264 57265 57266 57267 57268 57269 57270 57271 57272 57273 57274 57275 57276 57277 57278 57279 57280 57281 57282 57283 57284 57285 57286 57287 57288 57289 57290 57291 57292 57293 57294 57295 57296 57297 57298 57299 57300 57301 57302 57303 57304 57305 57306 57307 57308 57309 57310 57311 57312 57313 57314 57315 57316 57317 57318 57319 57320 57321 57322 57323 57324 57325 57326 57327 57328 57329 57330 57331 57332 57333 57334 57335 57336 57337 57338 57339 57340 57341 57342 57343 57344 57345 57346 57347 57348 57349 57350 57351 57352 57353 57354 57355 57356 57357 57358 57359 57360 57361 57362 57363 57364 57365 57366 57367 57368 57369 57370 57371 57372 57373 57374 57375 57376 57377 57378 57379 57380 57381 57382 57383 57384 57385 57386 57387 57388 57389 57390 57391 57392 57393 57394 57395 57396 57397 57398 57399 57400 57401 57402 57403 57404 57405 57406 57407 57408 57409 57410 57411 57412 57413 57414 57415 57416 57417 57418 57419 57420 57421 57422 57423 57424 57425 57426 57427 57428 57429 57430 57431 57432 57433 57434 57435 57436 57437 57438 57439 57440 57441 57442 57443 57444 57445 57446 57447 57448 57449 57450 57451 57452 57453 57454 57455 57456 57457 57458 57459 57460 57461 57462 57463 57464 57465 57466 57467 57468 57469 57470 57471 57472 57473 57474 57475 57476 57477 57478 57479 57480 57481 57482 57483 57484 57485 57486 57487 57488 57489 57490 57491 57492 57493 57494 57495 57496 57497 57498 57499 57500 57501 57502 57503 57504 57505 57506 57507 57508 57509 57510 57511 57512 57513 57514 57515 57516 57517 57518 57519 57520 57521 57522 57523 57524 57525 57526 57527 57528 57529 57530 57531 57532 57533 57534 57535 57536 57537 57538 57539 57540 57541 57542 57543 57544 57545 57546 57547 57548 57549 57550 57551 57552 57553 57554 57555 57556 57557 57558 57559 57560 57561 57562 57563 57564 57565 57566 57567 57568 57569 57570 57571 57572 57573 57574 57575 57576 57577 57578 57579 57580 57581 57582 57583 57584 57585 57586 57587 57588 57589 57590 57591 57592 57593 57594 57595 57596 57597 57598 57599 57600 57601 57602 57603 57604 57605 57606 57607 57608 57609 57610 57611 57612 57613 57614 57615 57616 57617 57618 57619 57620 57621 57622 57623 57624 57625 57626 57627 57628 57629 57630 57631 57632 57633 57634 57635 57636 57637 57638 57639 57640 57641 57642 57643 57644 57645 57646 57647 57648 57649 57650 57651 57652 57653 57654 57655 57656 57657 57658 57659 57660 57661 57662 57663 57664 57665 57666 57667 57668 57669 57670 57671 57672 57673 57674 57675 57676 57677 57678 57679 57680 57681 57682 57683 57684 57685 57686 57687 57688 57689 57690 57691 57692 57693 57694 57695 57696 57697 57698 57699 57700 57701 57702 57703 57704 57705 57706 57707 57708 57709 57710 57711 57712 57713 57714 57715 57716 57717 57718 57719 57720 57721 57722 57723 57724 57725 57726 57727 57728 57729 57730 57731 57732 57733 57734 57735 57736 57737 57738 57739 57740 57741 57742 57743 57744 57745 57746 57747 57748 57749 57750 57751 57752 57753 57754 57755 57756 57757 57758 57759 57760 57761 57762 57763 57764 57765 57766 57767 57768 57769 57770 57771 57772 57773 57774 57775 57776 57777 57778 57779 57780 57781 57782 57783 57784 57785 57786 57787 57788 57789 57790 57791 57792 57793 57794 57795 57796 57797 57798 57799 57800 57801 57802 57803 57804 57805 57806 57807 57808 57809 57810 57811 57812 57813 57814 57815 57816 57817 57818 57819 57820 57821 57822 57823 57824 57825 57826 57827 57828 57829 57830 57831 57832 57833 57834 57835 57836 57837 57838 57839 57840 57841 57842 57843 57844 57845 57846 57847 57848 57849 57850 57851 57852 57853 57854 57855 57856 57857 57858 57859 57860 57861 57862 57863 57864 57865 57866 57867 57868 57869 57870 57871 57872 57873 57874 57875 57876 57877 57878 57879 57880 57881 57882 57883 57884 57885 57886 57887 57888 57889 57890 57891 57892 57893 57894 57895 57896 57897 57898 57899 57900 57901 57902 57903 57904 57905 57906 57907 57908 57909 57910 57911 57912 57913 57914 57915 57916 57917 57918 57919 57920 57921 57922 57923 57924 57925 57926 57927 57928 57929 57930 57931 57932 57933 57934 57935 57936 57937 57938 57939 57940 57941 57942 57943 57944 57945 57946 57947 57948 57949 57950 57951 57952 57953 57954 57955 57956 57957 57958 57959 57960 57961 57962 57963 57964 57965 57966 57967 57968 57969 57970 57971 57972 57973 57974 57975 57976 57977 57978 57979 57980 57981 57982 57983 57984 57985 57986 57987 57988 57989 57990 57991 57992 57993 57994 57995 57996 57997 57998 57999 58000 58001 58002 58003 58004 58005 58006 58007 58008 58009 58010 58011 58012 58013 58014 58015 58016 58017 58018 58019 58020 58021 58022 58023 58024 58025 58026 58027 58028 58029 58030 58031 58032 58033 58034 58035 58036 58037 58038 58039 58040 58041 58042 58043 58044 58045 58046 58047 58048 58049 58050 58051 58052 58053 58054 58055 58056 58057 58058 58059 58060 58061 58062 58063 58064 58065 58066 58067 58068 58069 58070 58071 58072 58073 58074 58075 58076 58077 58078 58079 58080 58081 58082 58083 58084 58085 58086 58087 58088 58089 58090 58091 58092 58093 58094 58095 58096 58097 58098 58099 58100 58101 58102 58103 58104 58105 58106 58107 58108 58109 58110 58111 58112 58113 58114 58115 58116 58117 58118 58119 58120 58121 58122 58123 58124 58125 58126 58127 58128 58129 58130 58131 58132 58133 58134 58135 58136 58137 58138 58139 58140 58141 58142 58143 58144 58145 58146 58147 58148 58149 58150 58151 58152 58153 58154 58155 58156 58157 58158 58159 58160 58161 58162 58163 58164 58165 58166 58167 58168 58169 58170 58171 58172 58173 58174 58175 58176 58177 58178 58179 58180 58181 58182 58183 58184 58185 58186 58187 58188 58189 58190 58191 58192 58193 58194 58195 58196 58197 58198 58199 58200 58201 58202 58203 58204 58205 58206 58207 58208 58209 58210 58211 58212 58213 58214 58215 58216 58217 58218 58219 58220 58221 58222 58223 58224 58225 58226 58227 58228 58229 58230 58231 58232 58233 58234 58235 58236 58237 58238 58239 58240 58241 58242 58243 58244 58245 58246 58247 58248 58249 58250 58251 58252 58253 58254 58255 58256 58257 58258 58259 58260 58261 58262 58263 58264 58265 58266 58267 58268 58269 58270 58271 58272 58273 58274 58275 58276 58277 58278 58279 58280 58281 58282 58283 58284 58285 58286 58287 58288 58289 58290 58291 58292 58293 58294 58295 58296 58297 58298 58299 58300 58301 58302 58303 58304 58305 58306 58307 58308 58309 58310 58311 58312 58313 58314 58315 58316 58317 58318 58319 58320 58321 58322 58323 58324 58325 58326 58327 58328 58329 58330 58331 58332 58333 58334 58335 58336 58337 58338 58339 58340 58341 58342 58343 58344 58345 58346 58347 58348 58349 58350 58351 58352 58353 58354 58355 58356 58357 58358 58359 58360 58361 58362 58363 58364 58365 58366 58367 58368 58369 58370 58371 58372 58373 58374 58375 58376 58377 58378 58379 58380 58381 58382 58383 58384 58385 58386 58387 58388 58389 58390 58391 58392 58393 58394 58395 58396 58397 58398 58399 58400 58401 58402 58403 58404 58405 58406 58407 58408 58409 58410 58411 58412 58413 58414 58415 58416 58417 58418 58419 58420 58421 58422 58423 58424 58425 58426 58427 58428 58429 58430 58431 58432 58433 58434 58435 58436 58437 58438 58439 58440 58441 58442 58443 58444 58445 58446 58447 58448 58449 58450 58451 58452 58453 58454 58455 58456 58457 58458 58459 58460 58461 58462 58463 58464 58465 58466 58467 58468 58469 58470 58471 58472 58473 58474 58475 58476 58477 58478 58479 58480 58481 58482 58483 58484 58485 58486 58487 58488 58489 58490 58491 58492 58493 58494 58495 58496 58497 58498 58499 58500 58501 58502 58503 58504 58505 58506 58507 58508 58509 58510 58511 58512 58513 58514 58515 58516 58517 58518 58519 58520 58521 58522 58523 58524 58525 58526 58527 58528 58529 58530 58531 58532 58533 58534 58535 58536 58537 58538 58539 58540 58541 58542 58543 58544 58545 58546 58547 58548 58549 58550 58551 58552 58553 58554 58555 58556 58557 58558 58559 58560 58561 58562 58563 58564 58565 58566 58567 58568 58569 58570 58571 58572 58573 58574 58575 58576 58577 58578 58579 58580 58581 58582 58583 58584 58585 58586 58587 58588 58589 58590 58591 58592 58593 58594 58595 58596 58597 58598 58599 58600 58601 58602 58603 58604 58605 58606 58607 58608 58609 58610 58611 58612 58613 58614 58615 58616 58617 58618 58619 58620 58621 58622 58623 58624 58625 58626 58627 58628 58629 58630 58631 58632 58633 58634 58635 58636 58637 58638 58639 58640 58641 58642 58643 58644 58645 58646 58647 58648 58649 58650 58651 58652 58653 58654 58655 58656 58657 58658 58659 58660 58661 58662 58663 58664 58665 58666 58667 58668 58669 58670 58671 58672 58673 58674 58675 58676 58677 58678 58679 58680 58681 58682 58683 58684 58685 58686 58687 58688 58689 58690 58691 58692 58693 58694 58695 58696 58697 58698 58699 58700 58701 58702 58703 58704 58705 58706 58707 58708 58709 58710 58711 58712 58713 58714 58715 58716 58717 58718 58719 58720 58721 58722 58723 58724 58725 58726 58727 58728 58729 58730 58731 58732 58733 58734 58735 58736 58737 58738 58739 58740 58741 58742 58743 58744 58745 58746 58747 58748 58749 58750 58751 58752 58753 58754 58755 58756 58757 58758 58759 58760 58761 58762 58763 58764 58765 58766 58767 58768 58769 58770 58771 58772 58773 58774 58775 58776 58777 58778 58779 58780 58781 58782 58783 58784 58785 58786 58787 58788 58789 58790 58791 58792 58793 58794 58795 58796 58797 58798 58799 58800 58801 58802 58803 58804 58805 58806 58807 58808 58809 58810 58811 58812 58813 58814 58815 58816 58817 58818 58819 58820 58821 58822 58823 58824 58825 58826 58827 58828 58829 58830 58831 58832 58833 58834 58835 58836 58837 58838 58839 58840 58841 58842 58843 58844 58845 58846 58847 58848 58849 58850 58851 58852 58853 58854 58855 58856 58857 58858 58859 58860 58861 58862 58863 58864 58865 58866 58867 58868 58869 58870 58871 58872 58873 58874 58875 58876 58877 58878 58879 58880 58881 58882 58883 58884 58885 58886 58887 58888 58889 58890 58891 58892 58893 58894 58895 58896 58897 58898 58899 58900 58901 58902 58903 58904 58905 58906 58907 58908 58909 58910 58911 58912 58913 58914 58915 58916 58917 58918 58919 58920 58921 58922 58923 58924 58925 58926 58927 58928 58929 58930 58931 58932 58933 58934 58935 58936 58937 58938 58939 58940 58941 58942 58943 58944 58945 58946 58947 58948 58949 58950 58951 58952 58953 58954 58955 58956 58957 58958 58959 58960 58961 58962 58963 58964 58965 58966 58967 58968 58969 58970 58971 58972 58973 58974 58975 58976 58977 58978 58979 58980 58981 58982 58983 58984 58985 58986 58987 58988 58989 58990 58991 58992 58993 58994 58995 58996 58997 58998 58999 59000 59001 59002 59003 59004 59005 59006 59007 59008 59009 59010 59011 59012 59013 59014 59015 59016 59017 59018 59019 59020 59021 59022 59023 59024 59025 59026 59027 59028 59029 59030 59031 59032 59033 59034 59035 59036 59037 59038 59039 59040 59041 59042 59043 59044 59045 59046 59047 59048 59049 59050 59051 59052 59053 59054 59055 59056 59057 59058 59059 59060 59061 59062 59063 59064 59065 59066 59067 59068 59069 59070 59071 59072 59073 59074 59075 59076 59077 59078 59079 59080 59081 59082 59083 59084 59085 59086 59087 59088 59089 59090 59091 59092 59093 59094 59095 59096 59097 59098 59099 59100 59101 59102 59103 59104 59105 59106 59107 59108 59109 59110 59111 59112 59113 59114 59115 59116 59117 59118 59119 59120 59121 59122 59123 59124 59125 59126 59127 59128 59129 59130 59131 59132 59133 59134 59135 59136 59137 59138 59139 59140 59141 59142 59143 59144 59145 59146 59147 59148 59149 59150 59151 59152 59153 59154 59155 59156 59157 59158 59159 59160 59161 59162 59163 59164 59165 59166 59167 59168 59169 59170 59171 59172 59173 59174 59175 59176 59177 59178 59179 59180 59181 59182 59183 59184 59185 59186 59187 59188 59189 59190 59191 59192 59193 59194 59195 59196 59197 59198 59199 59200 59201 59202 59203 59204 59205 59206 59207 59208 59209 59210 59211 59212 59213 59214 59215 59216 59217 59218 59219 59220 59221 59222 59223 59224 59225 59226 59227 59228 59229 59230 59231 59232 59233 59234 59235 59236 59237 59238 59239 59240 59241 59242 59243 59244 59245 59246 59247 59248 59249 59250 59251 59252 59253 59254 59255 59256 59257 59258 59259 59260 59261 59262 59263 59264 59265 59266 59267 59268 59269 59270 59271 59272 59273 59274 59275 59276 59277 59278 59279 59280 59281 59282 59283 59284 59285 59286 59287 59288 59289 59290 59291 59292 59293 59294 59295 59296 59297 59298 59299 59300 59301 59302 59303 59304 59305 59306 59307 59308 59309 59310 59311 59312 59313 59314 59315 59316 59317 59318 59319 59320 59321 59322 59323 59324 59325 59326 59327 59328 59329 59330 59331 59332 59333 59334 59335 59336 59337 59338 59339 59340 59341 59342 59343 59344 59345 59346 59347 59348 59349 59350 59351 59352 59353 59354 59355 59356 59357 59358 59359 59360 59361 59362 59363 59364 59365 59366 59367 59368 59369 59370 59371 59372 59373 59374 59375 59376 59377 59378 59379 59380 59381 59382 59383 59384 59385 59386 59387 59388 59389 59390 59391 59392 59393 59394 59395 59396 59397 59398 59399 59400 59401 59402 59403 59404 59405 59406 59407 59408 59409 59410 59411 59412 59413 59414 59415 59416 59417 59418 59419 59420 59421 59422 59423 59424 59425 59426 59427 59428 59429 59430 59431 59432 59433 59434 59435 59436 59437 59438 59439 59440 59441 59442 59443 59444 59445 59446 59447 59448 59449 59450 59451 59452 59453 59454 59455 59456 59457 59458 59459 59460 59461 59462 59463 59464 59465 59466 59467 59468 59469 59470 59471 59472 59473 59474 59475 59476 59477 59478 59479 59480 59481 59482 59483 59484 59485 59486 59487 59488 59489 59490 59491 59492 59493 59494 59495 59496 59497 59498 59499 59500 59501 59502 59503 59504 59505 59506 59507 59508 59509 59510 59511 59512 59513 59514 59515 59516 59517 59518 59519 59520 59521 59522 59523 59524 59525 59526 59527 59528 59529 59530 59531 59532 59533 59534 59535 59536 59537 59538 59539 59540 59541 59542 59543 59544 59545 59546 59547 59548 59549 59550 59551 59552 59553 59554 59555 59556 59557 59558 59559 59560 59561 59562 59563 59564 59565 59566 59567 59568 59569 59570 59571 59572 59573 59574 59575 59576 59577 59578 59579 59580 59581 59582 59583 59584 59585 59586 59587 59588 59589 59590 59591 59592 59593 59594 59595 59596 59597 59598 59599 59600 59601 59602 59603 59604 59605 59606 59607 59608 59609 59610 59611 59612 59613 59614 59615 59616 59617 59618 59619 59620 59621 59622 59623 59624 59625 59626 59627 59628 59629 59630 59631 59632 59633 59634 59635 59636 59637 59638 59639 59640 59641 59642 59643 59644 59645 59646 59647 59648 59649 59650 59651 59652 59653 59654 59655 59656 59657 59658 59659 59660 59661 59662 59663 59664 59665 59666 59667 59668 59669 59670 59671 59672 59673 59674 59675 59676 59677 59678 59679 59680 59681 59682 59683 59684 59685 59686 59687 59688 59689 59690 59691 59692 59693 59694 59695 59696 59697 59698 59699 59700 59701 59702 59703 59704 59705 59706 59707 59708 59709 59710 59711 59712 59713 59714 59715 59716 59717 59718 59719 59720 59721 59722 59723 59724 59725 59726 59727 59728 59729 59730 59731 59732 59733 59734 59735 59736 59737 59738 59739 59740 59741 59742 59743 59744 59745 59746 59747 59748 59749 59750 59751 59752 59753 59754 59755 59756 59757 59758 59759 59760 59761 59762 59763 59764 59765 59766 59767 59768 59769 59770 59771 59772 59773 59774 59775 59776 59777 59778 59779 59780 59781 59782 59783 59784 59785 59786 59787 59788 59789 59790 59791 59792 59793 59794 59795 59796 59797 59798 59799 59800 59801 59802 59803 59804 59805 59806 59807 59808 59809 59810 59811 59812 59813 59814 59815 59816 59817 59818 59819 59820 59821 59822 59823 59824 59825 59826 59827 59828 59829 59830 59831 59832 59833 59834 59835 59836 59837 59838 59839 59840 59841 59842 59843 59844 59845 59846 59847 59848 59849 59850 59851 59852 59853 59854 59855 59856 59857 59858 59859 59860 59861 59862 59863 59864 59865 59866 59867 59868 59869 59870 59871 59872 59873 59874 59875 59876 59877 59878 59879 59880 59881 59882 59883 59884 59885 59886 59887 59888 59889 59890 59891 59892 59893 59894 59895 59896 59897 59898 59899 59900 59901 59902 59903 59904 59905 59906 59907 59908 59909 59910 59911 59912 59913 59914 59915 59916 59917 59918 59919 59920 59921 59922 59923 59924 59925 59926 59927 59928 59929 59930 59931 59932 59933 59934 59935 59936 59937 59938 59939 59940 59941 59942 59943 59944 59945 59946 59947 59948 59949 59950 59951 59952 59953 59954 59955 59956 59957 59958 59959 59960 59961 59962 59963 59964 59965 59966 59967 59968 59969 59970 59971 59972 59973 59974 59975 59976 59977 59978 59979 59980 59981 59982 59983 59984 59985 59986 59987 59988 59989 59990 59991 59992 59993 59994 59995 59996 59997 59998 59999 60000 60001 60002 60003 60004 60005 60006 60007 60008 60009 60010 60011 60012 60013 60014 60015 60016 60017 60018 60019 60020 60021 60022 60023 60024 60025 60026 60027 60028 60029 60030 60031 60032 60033 60034 60035 60036 60037 60038 60039 60040 60041 60042 60043 60044 60045 60046 60047 60048 60049 60050 60051 60052 60053 60054 60055 60056 60057 60058 60059 60060 60061 60062 60063 60064 60065 60066 60067 60068 60069 60070 60071 60072 60073 60074 60075 60076 60077 60078 60079 60080 60081 60082 60083 60084 60085 60086 60087 60088 60089 60090 60091 60092 60093 60094 60095 60096 60097 60098 60099 60100 60101 60102 60103 60104 60105 60106 60107 60108 60109 60110 60111 60112 60113 60114 60115 60116 60117 60118 60119 60120 60121 60122 60123 60124 60125 60126 60127 60128 60129 60130 60131 60132 60133 60134 60135 60136 60137 60138 60139 60140 60141 60142 60143 60144 60145 60146 60147 60148 60149 60150 60151 60152 60153 60154 60155 60156 60157 60158 60159 60160 60161 60162 60163 60164 60165 60166 60167 60168 60169 60170 60171 60172 60173 60174 60175 60176 60177 60178 60179 60180 60181 60182 60183 60184 60185 60186 60187 60188 60189 60190 60191 60192 60193 60194 60195 60196 60197 60198 60199 60200 60201 60202 60203 60204 60205 60206 60207 60208 60209 60210 60211 60212 60213 60214 60215 60216 60217 60218 60219 60220 60221 60222 60223 60224 60225 60226 60227 60228 60229 60230 60231 60232 60233 60234 60235 60236 60237 60238 60239 60240 60241 60242 60243 60244 60245 60246 60247 60248 60249 60250 60251 60252 60253 60254 60255 60256 60257 60258 60259 60260 60261 60262 60263 60264 60265 60266 60267 60268 60269 60270 60271 60272 60273 60274 60275 60276 60277 60278 60279 60280 60281 60282 60283 60284 60285 60286 60287 60288 60289 60290 60291 60292 60293 60294 60295 60296 60297 60298 60299 60300 60301 60302 60303 60304 60305 60306 60307 60308 60309 60310 60311 60312 60313 60314 60315 60316 60317 60318 60319 60320 60321 60322 60323 60324 60325 60326 60327 60328 60329 60330 60331 60332 60333 60334 60335 60336 60337 60338 60339 60340 60341 60342 60343 60344 60345 60346 60347 60348 60349 60350 60351 60352 60353 60354 60355 60356 60357 60358 60359 60360 60361 60362 60363 60364 60365 60366 60367 60368 60369 60370 60371 60372 60373 60374 60375 60376 60377 60378 60379 60380 60381 60382 60383 60384 60385 60386 60387 60388 60389 60390 60391 60392 60393 60394 60395 60396 60397 60398 60399 60400 60401 60402 60403 60404 60405 60406 60407 60408 60409 60410 60411 60412 60413 60414 60415 60416 60417 60418 60419 60420 60421 60422 60423 60424 60425 60426 60427 60428 60429 60430 60431 60432 60433 60434 60435 60436 60437 60438 60439 60440 60441 60442 60443 60444 60445 60446 60447 60448 60449 60450 60451 60452 60453 60454 60455 60456 60457 60458 60459 60460 60461 60462 60463 60464 60465 60466 60467 60468 60469 60470 60471 60472 60473 60474 60475 60476 60477 60478 60479 60480 60481 60482 60483 60484 60485 60486 60487 60488 60489 60490 60491 60492 60493 60494 60495 60496 60497 60498 60499 60500 60501 60502 60503 60504 60505 60506 60507 60508 60509 60510 60511 60512 60513 60514 60515 60516 60517 60518 60519 60520 60521 60522 60523 60524 60525 60526 60527 60528 60529 60530 60531 60532 60533 60534 60535 60536 60537 60538 60539 60540 60541 60542 60543 60544 60545 60546 60547 60548 60549 60550 60551 60552 60553 60554 60555 60556 60557 60558 60559 60560 60561 60562 60563 60564 60565 60566 60567 60568 60569 60570 60571 60572 60573 60574 60575 60576 60577 60578 60579 60580 60581 60582 60583 60584 60585 60586 60587 60588 60589 60590 60591 60592 60593 60594 60595 60596 60597 60598 60599 60600 60601 60602 60603 60604 60605 60606 60607 60608 60609 60610 60611 60612 60613 60614 60615 60616 60617 60618 60619 60620 60621 60622 60623 60624 60625 60626 60627 60628 60629 60630 60631 60632 60633 60634 60635 60636 60637 60638 60639 60640 60641 60642 60643 60644 60645 60646 60647 60648 60649 60650 60651 60652 60653 60654 60655 60656 60657 60658 60659 60660 60661 60662 60663 60664 60665 60666 60667 60668 60669 60670 60671 60672 60673 60674 60675 60676 60677 60678 60679 60680 60681 60682 60683 60684 60685 60686 60687 60688 60689 60690 60691 60692 60693 60694 60695 60696 60697 60698 60699 60700 60701 60702 60703 60704 60705 60706 60707 60708 60709 60710 60711 60712 60713 60714 60715 60716 60717 60718 60719 60720 60721 60722 60723 60724 60725 60726 60727 60728 60729 60730 60731 60732 60733 60734 60735 60736 60737 60738 60739 60740 60741 60742 60743 60744 60745 60746 60747 60748 60749 60750 60751 60752 60753 60754 60755 60756 60757 60758 60759 60760 60761 60762 60763 60764 60765 60766 60767 60768 60769 60770 60771 60772 60773 60774 60775 60776 60777 60778 60779 60780 60781 60782 60783 60784 60785 60786 60787 60788 60789 60790 60791 60792 60793 60794 60795 60796 60797 60798 60799 60800 60801 60802 60803 60804 60805 60806 60807 60808 60809 60810 60811 60812 60813 60814 60815 60816 60817 60818 60819 60820 60821 60822 60823 60824 60825 60826 60827 60828 60829 60830 60831 60832 60833 60834 60835 60836 60837 60838 60839 60840 60841 60842 60843 60844 60845 60846 60847 60848 60849 60850 60851 60852 60853 60854 60855 60856 60857 60858 60859 60860 60861 60862 60863 60864 60865 60866 60867 60868 60869 60870 60871 60872 60873 60874 60875 60876 60877 60878 60879 60880 60881 60882 60883 60884 60885 60886 60887 60888 60889 60890 60891 60892 60893 60894 60895 60896 60897 60898 60899 60900 60901 60902 60903 60904 60905 60906 60907 60908 60909 60910 60911 60912 60913 60914 60915 60916 60917 60918 60919 60920 60921 60922 60923 60924 60925 60926 60927 60928 60929 60930 60931 60932 60933 60934 60935 60936 60937 60938 60939 60940 60941 60942 60943 60944 60945 60946 60947 60948 60949 60950 60951 60952 60953 60954 60955 60956 60957 60958 60959 60960 60961 60962 60963 60964 60965 60966 60967 60968 60969 60970 60971 60972 60973 60974 60975 60976 60977 60978 60979 60980 60981 60982 60983 60984 60985 60986 60987 60988 60989 60990 60991 60992 60993 60994 60995 60996 60997 60998 60999 61000 61001 61002 61003 61004 61005 61006 61007 61008 61009 61010 61011 61012 61013 61014 61015 61016 61017 61018 61019 61020 61021 61022 61023 61024 61025 61026 61027 61028 61029 61030 61031 61032 61033 61034 61035 61036 61037 61038 61039 61040 61041 61042 61043 61044 61045 61046 61047 61048 61049 61050 61051 61052 61053 61054 61055 61056 61057 61058 61059 61060 61061 61062 61063 61064 61065 61066 61067 61068 61069 61070 61071 61072 61073 61074 61075 61076 61077 61078 61079 61080 61081 61082 61083 61084 61085 61086 61087 61088 61089 61090 61091 61092 61093 61094 61095 61096 61097 61098 61099 61100 61101 61102 61103 61104 61105 61106 61107 61108 61109 61110 61111 61112 61113 61114 61115 61116 61117 61118 61119 61120 61121 61122 61123 61124 61125 61126 61127 61128 61129 61130 61131 61132 61133 61134 61135 61136 61137 61138 61139 61140 61141 61142 61143 61144 61145 61146 61147 61148 61149 61150 61151 61152 61153 61154 61155 61156 61157 61158 61159 61160 61161 61162 61163 61164 61165 61166 61167 61168 61169 61170 61171 61172 61173 61174 61175 61176 61177 61178 61179 61180 61181 61182 61183 61184 61185 61186 61187 61188 61189 61190 61191 61192 61193 61194 61195 61196 61197 61198 61199 61200 61201 61202 61203 61204 61205 61206 61207 61208 61209 61210 61211 61212 61213 61214 61215 61216 61217 61218 61219 61220 61221 61222 61223 61224 61225 61226 61227 61228 61229 61230 61231 61232 61233 61234 61235 61236 61237 61238 61239 61240 61241 61242 61243 61244 61245 61246 61247 61248 61249 61250 61251 61252 61253 61254 61255 61256 61257 61258 61259 61260 61261 61262 61263 61264 61265 61266 61267 61268 61269 61270 61271 61272 61273 61274 61275 61276 61277 61278 61279 61280 61281 61282 61283 61284 61285 61286 61287 61288 61289 61290 61291 61292 61293 61294 61295 61296 61297 61298 61299 61300 61301 61302 61303 61304 61305 61306 61307 61308 61309 61310 61311 61312 61313 61314 61315 61316 61317 61318 61319 61320 61321 61322 61323 61324 61325 61326 61327 61328 61329 61330 61331 61332 61333 61334 61335 61336 61337 61338 61339 61340 61341 61342 61343 61344 61345 61346 61347 61348 61349 61350 61351 61352 61353 61354 61355 61356 61357 61358 61359 61360 61361 61362 61363 61364 61365 61366 61367 61368 61369 61370 61371 61372 61373 61374 61375 61376 61377 61378 61379 61380 61381 61382 61383 61384 61385 61386 61387 61388 61389 61390 61391 61392 61393 61394 61395 61396 61397 61398 61399 61400 61401 61402 61403 61404 61405 61406 61407 61408 61409 61410 61411 61412 61413 61414 61415 61416 61417 61418 61419 61420 61421 61422 61423 61424 61425 61426 61427 61428 61429 61430 61431 61432 61433 61434 61435 61436 61437 61438 61439 61440 61441 61442 61443 61444 61445 61446 61447 61448 61449 61450 61451 61452 61453 61454 61455 61456 61457 61458 61459 61460 61461 61462 61463 61464 61465 61466 61467 61468 61469 61470 61471 61472 61473 61474 61475 61476 61477 61478 61479 61480 61481 61482 61483 61484 61485 61486 61487 61488 61489 61490 61491 61492 61493 61494 61495 61496 61497 61498 61499 61500 61501 61502 61503 61504 61505 61506 61507 61508 61509 61510 61511 61512 61513 61514 61515 61516 61517 61518 61519 61520 61521 61522 61523 61524 61525 61526 61527 61528 61529 61530 61531 61532 61533 61534 61535 61536 61537 61538 61539 61540 61541 61542 61543 61544 61545 61546 61547 61548 61549 61550 61551 61552 61553 61554 61555 61556 61557 61558 61559 61560 61561 61562 61563 61564 61565 61566 61567 61568 61569 61570 61571 61572 61573 61574 61575 61576 61577 61578 61579 61580 61581 61582 61583 61584 61585 61586 61587 61588 61589 61590 61591 61592 61593 61594 61595 61596 61597 61598 61599 61600 61601 61602 61603 61604 61605 61606 61607 61608 61609 61610 61611 61612 61613 61614 61615 61616 61617 61618 61619 61620 61621 61622 61623 61624 61625 61626 61627 61628 61629 61630 61631 61632 61633 61634 61635 61636 61637 61638 61639 61640 61641 61642 61643 61644 61645 61646 61647 61648 61649 61650 61651 61652 61653 61654 61655 61656 61657 61658 61659 61660 61661 61662 61663 61664 61665 61666 61667 61668 61669 61670 61671 61672 61673 61674 61675 61676 61677 61678 61679 61680 61681 61682 61683 61684 61685 61686 61687 61688 61689 61690 61691 61692 61693 61694 61695 61696 61697 61698 61699 61700 61701 61702 61703 61704 61705 61706 61707 61708 61709 61710 61711 61712 61713 61714 61715 61716 61717 61718 61719 61720 61721 61722 61723 61724 61725 61726 61727 61728 61729 61730 61731 61732 61733 61734 61735 61736 61737 61738 61739 61740 61741 61742 61743 61744 61745 61746 61747 61748 61749 61750 61751 61752 61753 61754 61755 61756 61757 61758 61759 61760 61761 61762 61763 61764 61765 61766 61767 61768 61769 61770 61771 61772 61773 61774 61775 61776 61777 61778 61779 61780 61781 61782 61783 61784 61785 61786 61787 61788 61789 61790 61791 61792 61793 61794 61795 61796 61797 61798 61799 61800 61801 61802 61803 61804 61805 61806 61807 61808 61809 61810 61811 61812 61813 61814 61815 61816 61817 61818 61819 61820 61821 61822 61823 61824 61825 61826 61827 61828 61829 61830 61831 61832 61833 61834 61835 61836 61837 61838 61839 61840 61841 61842 61843 61844 61845 61846 61847 61848 61849 61850 61851 61852 61853 61854 61855 61856 61857 61858 61859 61860 61861 61862 61863 61864 61865 61866 61867 61868 61869 61870 61871 61872 61873 61874 61875 61876 61877 61878 61879 61880 61881 61882 61883 61884 61885 61886 61887 61888 61889 61890 61891 61892 61893 61894 61895 61896 61897 61898 61899 61900 61901 61902 61903 61904 61905 61906 61907 61908 61909 61910 61911 61912 61913 61914 61915 61916 61917 61918 61919 61920 61921 61922 61923 61924 61925 61926 61927 61928 61929 61930 61931 61932 61933 61934 61935 61936 61937 61938 61939 61940 61941 61942 61943 61944 61945 61946 61947 61948 61949 61950 61951 61952 61953 61954 61955 61956 61957 61958 61959 61960 61961 61962 61963 61964 61965 61966 61967 61968 61969 61970 61971 61972 61973 61974 61975 61976 61977 61978 61979 61980 61981 61982 61983 61984 61985 61986 61987 61988 61989 61990 61991 61992 61993 61994 61995 61996 61997 61998 61999 62000 62001 62002 62003 62004 62005 62006 62007 62008 62009 62010 62011 62012 62013 62014 62015 62016 62017 62018 62019 62020 62021 62022 62023 62024 62025 62026 62027 62028 62029 62030 62031 62032 62033 62034 62035 62036 62037 62038 62039 62040 62041 62042 62043 62044 62045 62046 62047 62048 62049 62050 62051 62052 62053 62054 62055 62056 62057 62058 62059 62060 62061 62062 62063 62064 62065 62066 62067 62068 62069 62070 62071 62072 62073 62074 62075 62076 62077 62078 62079 62080 62081 62082 62083 62084 62085 62086 62087 62088 62089 62090 62091 62092 62093 62094 62095 62096 62097 62098 62099 62100 62101 62102 62103 62104 62105 62106 62107 62108 62109 62110 62111 62112 62113 62114 62115 62116 62117 62118 62119 62120 62121 62122 62123 62124 62125 62126 62127 62128 62129 62130 62131 62132 62133 62134 62135 62136 62137 62138 62139 62140 62141 62142 62143 62144 62145 62146 62147 62148 62149 62150 62151 62152 62153 62154 62155 62156 62157 62158 62159 62160 62161 62162 62163 62164 62165 62166 62167 62168 62169 62170 62171 62172 62173 62174 62175 62176 62177 62178 62179 62180 62181 62182 62183 62184 62185 62186 62187 62188 62189 62190 62191 62192 62193 62194 62195 62196 62197 62198 62199 62200 62201 62202 62203 62204 62205 62206 62207 62208 62209 62210 62211 62212 62213 62214 62215 62216 62217 62218 62219 62220 62221 62222 62223 62224 62225 62226 62227 62228 62229 62230 62231 62232 62233 62234 62235 62236 62237 62238 62239 62240 62241 62242 62243 62244 62245 62246 62247 62248 62249 62250 62251 62252 62253 62254 62255 62256 62257 62258 62259 62260 62261 62262 62263 62264 62265 62266 62267 62268 62269 62270 62271 62272 62273 62274 62275 62276 62277 62278 62279 62280 62281 62282 62283 62284 62285 62286 62287 62288 62289 62290 62291 62292 62293 62294 62295 62296 62297 62298 62299 62300 62301 62302 62303 62304 62305 62306 62307 62308 62309 62310 62311 62312 62313 62314 62315 62316 62317 62318 62319 62320 62321 62322 62323 62324 62325 62326 62327 62328 62329 62330 62331 62332 62333 62334 62335 62336 62337 62338 62339 62340 62341 62342 62343 62344 62345 62346 62347 62348 62349 62350 62351 62352 62353 62354 62355 62356 62357 62358 62359 62360 62361 62362 62363 62364 62365 62366 62367 62368 62369 62370 62371 62372 62373 62374 62375 62376 62377 62378 62379 62380 62381 62382 62383 62384 62385 62386 62387 62388 62389 62390 62391 62392 62393 62394 62395 62396 62397 62398 62399 62400 62401 62402 62403 62404 62405 62406 62407 62408 62409 62410 62411 62412 62413 62414 62415 62416 62417 62418 62419 62420 62421 62422 62423 62424 62425 62426 62427 62428 62429 62430 62431 62432 62433 62434 62435 62436 62437 62438 62439 62440 62441 62442 62443 62444 62445 62446 62447 62448 62449 62450 62451 62452 62453 62454 62455 62456 62457 62458 62459 62460 62461 62462 62463 62464 62465 62466 62467 62468 62469 62470 62471 62472 62473 62474 62475 62476 62477 62478 62479 62480 62481 62482 62483 62484 62485 62486 62487 62488 62489 62490 62491 62492 62493 62494 62495 62496 62497 62498 62499 62500 62501 62502 62503 62504 62505 62506 62507 62508 62509 62510 62511 62512 62513 62514 62515 62516 62517 62518 62519 62520 62521 62522 62523 62524 62525 62526 62527 62528 62529 62530 62531 62532 62533 62534 62535 62536 62537 62538 62539 62540 62541 62542 62543 62544 62545 62546 62547 62548 62549 62550 62551 62552 62553 62554 62555 62556 62557 62558 62559 62560 62561 62562 62563 62564 62565 62566 62567 62568 62569 62570 62571 62572 62573 62574 62575 62576 62577 62578 62579 62580 62581 62582 62583 62584 62585 62586 62587 62588 62589 62590 62591 62592 62593 62594 62595 62596 62597 62598 62599 62600 62601 62602 62603 62604 62605 62606 62607 62608 62609 62610 62611 62612 62613 62614 62615 62616 62617 62618 62619 62620 62621 62622 62623 62624 62625 62626 62627 62628 62629 62630 62631 62632 62633 62634 62635 62636 62637 62638 62639 62640 62641 62642 62643 62644 62645 62646 62647 62648 62649 62650 62651 62652 62653 62654 62655 62656 62657 62658 62659 62660 62661 62662 62663 62664 62665 62666 62667 62668 62669 62670 62671 62672 62673 62674 62675 62676 62677 62678 62679 62680 62681 62682 62683 62684 62685 62686 62687 62688 62689 62690 62691 62692 62693 62694 62695 62696 62697 62698 62699 62700 62701 62702 62703 62704 62705 62706 62707 62708 62709 62710 62711 62712 62713 62714 62715 62716 62717 62718 62719 62720 62721 62722 62723 62724 62725 62726 62727 62728 62729 62730 62731 62732 62733 62734 62735 62736 62737 62738 62739 62740 62741 62742 62743 62744 62745 62746 62747 62748 62749 62750 62751 62752 62753 62754 62755 62756 62757 62758 62759 62760 62761 62762 62763 62764 62765 62766 62767 62768 62769 62770 62771 62772 62773 62774 62775 62776 62777 62778 62779 62780 62781 62782 62783 62784 62785 62786 62787 62788 62789 62790 62791 62792 62793 62794 62795 62796 62797 62798 62799 62800 62801 62802 62803 62804 62805 62806 62807 62808 62809 62810 62811 62812 62813 62814 62815 62816 62817 62818 62819 62820 62821 62822 62823 62824 62825 62826 62827 62828 62829 62830 62831 62832 62833 62834 62835 62836 62837 62838 62839 62840 62841 62842 62843 62844 62845 62846 62847 62848 62849 62850 62851 62852 62853 62854 62855 62856 62857 62858 62859 62860 62861 62862 62863 62864 62865 62866 62867 62868 62869 62870 62871 62872 62873 62874 62875 62876 62877 62878 62879 62880 62881 62882 62883 62884 62885 62886 62887 62888 62889 62890 62891 62892 62893 62894 62895 62896 62897 62898 62899 62900 62901 62902 62903 62904 62905 62906 62907 62908 62909 62910 62911 62912 62913 62914 62915 62916 62917 62918 62919 62920 62921 62922 62923 62924 62925 62926 62927 62928 62929 62930 62931 62932 62933 62934 62935 62936 62937 62938 62939 62940 62941 62942 62943 62944 62945 62946 62947 62948 62949 62950 62951 62952 62953 62954 62955 62956 62957 62958 62959 62960 62961 62962 62963 62964 62965 62966 62967 62968 62969 62970 62971 62972 62973 62974 62975 62976 62977 62978 62979 62980 62981 62982 62983 62984 62985 62986 62987 62988 62989 62990 62991 62992 62993 62994 62995 62996 62997 62998 62999 63000 63001 63002 63003 63004 63005 63006 63007 63008 63009 63010 63011 63012 63013 63014 63015 63016 63017 63018 63019 63020 63021 63022 63023 63024 63025 63026 63027 63028 63029 63030 63031 63032 63033 63034 63035 63036 63037 63038 63039 63040 63041 63042 63043 63044 63045 63046 63047 63048 63049 63050 63051 63052 63053 63054 63055 63056 63057 63058 63059 63060 63061 63062 63063 63064 63065 63066 63067 63068 63069 63070 63071 63072 63073 63074 63075 63076 63077 63078 63079 63080 63081 63082 63083 63084 63085 63086 63087 63088 63089 63090 63091 63092 63093 63094 63095 63096 63097 63098 63099 63100 63101 63102 63103 63104 63105 63106 63107 63108 63109 63110 63111 63112 63113 63114 63115 63116 63117 63118 63119 63120 63121 63122 63123 63124 63125 63126 63127 63128 63129 63130 63131 63132 63133 63134 63135 63136 63137 63138 63139 63140 63141 63142 63143 63144 63145 63146 63147 63148 63149 63150 63151 63152 63153 63154 63155 63156 63157 63158 63159 63160 63161 63162 63163 63164 63165 63166 63167 63168 63169 63170 63171 63172 63173 63174 63175 63176 63177 63178 63179 63180 63181 63182 63183 63184 63185 63186 63187 63188 63189 63190 63191 63192 63193 63194 63195 63196 63197 63198 63199 63200 63201 63202 63203 63204 63205 63206 63207 63208 63209 63210 63211 63212 63213 63214 63215 63216 63217 63218 63219 63220 63221 63222 63223 63224 63225 63226 63227 63228 63229 63230 63231 63232 63233 63234 63235 63236 63237 63238 63239 63240 63241 63242 63243 63244 63245 63246 63247 63248 63249 63250 63251 63252 63253 63254 63255 63256 63257 63258 63259 63260 63261 63262 63263 63264 63265 63266 63267 63268 63269 63270 63271 63272 63273 63274 63275 63276 63277 63278 63279 63280 63281 63282 63283 63284 63285 63286 63287 63288 63289 63290 63291 63292 63293 63294 63295 63296 63297 63298 63299 63300 63301 63302 63303 63304 63305 63306 63307 63308 63309 63310 63311 63312 63313 63314 63315 63316 63317 63318 63319 63320 63321 63322 63323 63324 63325 63326 63327 63328 63329 63330 63331 63332 63333 63334 63335 63336 63337 63338 63339 63340 63341 63342 63343 63344 63345 63346 63347 63348 63349 63350 63351 63352 63353 63354 63355 63356 63357 63358 63359 63360 63361 63362 63363 63364 63365 63366 63367 63368 63369 63370 63371 63372 63373 63374 63375 63376 63377 63378 63379 63380 63381 63382 63383 63384 63385 63386 63387 63388 63389 63390 63391 63392 63393 63394 63395 63396 63397 63398 63399 63400 63401 63402 63403 63404 63405 63406 63407 63408 63409 63410 63411 63412 63413 63414 63415 63416 63417 63418 63419 63420 63421 63422 63423 63424 63425 63426 63427 63428 63429 63430 63431 63432 63433 63434 63435 63436 63437 63438 63439 63440 63441 63442 63443 63444 63445 63446 63447 63448 63449 63450 63451 63452 63453 63454 63455 63456 63457 63458 63459 63460 63461 63462 63463 63464 63465 63466 63467 63468 63469 63470 63471 63472 63473 63474 63475 63476 63477 63478 63479 63480 63481 63482 63483 63484 63485 63486 63487 63488 63489 63490 63491 63492 63493 63494 63495 63496 63497 63498 63499 63500 63501 63502 63503 63504 63505 63506 63507 63508 63509 63510 63511 63512 63513 63514 63515 63516 63517 63518 63519 63520 63521 63522 63523 63524 63525 63526 63527 63528 63529 63530 63531 63532 63533 63534 63535 63536 63537 63538 63539 63540 63541 63542 63543 63544 63545 63546 63547 63548 63549 63550 63551 63552 63553 63554 63555 63556 63557 63558 63559 63560 63561 63562 63563 63564 63565 63566 63567 63568 63569 63570 63571 63572 63573 63574 63575 63576 63577 63578 63579 63580 63581 63582 63583 63584 63585 63586 63587 63588 63589 63590 63591 63592 63593 63594 63595 63596 63597 63598 63599 63600 63601 63602 63603 63604 63605 63606 63607 63608 63609 63610 63611 63612 63613 63614 63615 63616 63617 63618 63619 63620 63621 63622 63623 63624 63625 63626 63627 63628 63629 63630 63631 63632 63633 63634 63635 63636 63637 63638 63639 63640 63641 63642 63643 63644 63645 63646 63647 63648 63649 63650 63651 63652 63653 63654 63655 63656 63657 63658 63659 63660 63661 63662 63663 63664 63665 63666 63667 63668 63669 63670 63671 63672 63673 63674 63675 63676 63677 63678 63679 63680 63681 63682 63683 63684 63685 63686 63687 63688 63689 63690 63691 63692 63693 63694 63695 63696 63697 63698 63699 63700 63701 63702 63703 63704 63705 63706 63707 63708 63709 63710 63711 63712 63713 63714 63715 63716 63717 63718 63719 63720 63721 63722 63723 63724 63725 63726 63727 63728 63729 63730 63731 63732 63733 63734 63735 63736 63737 63738 63739 63740 63741 63742 63743 63744 63745 63746 63747 63748 63749 63750 63751 63752 63753 63754 63755 63756 63757 63758 63759 63760 63761 63762 63763 63764 63765 63766 63767 63768 63769 63770 63771 63772 63773 63774 63775 63776 63777 63778 63779 63780 63781 63782 63783 63784 63785 63786 63787 63788 63789 63790 63791 63792 63793 63794 63795 63796 63797 63798 63799 63800 63801 63802 63803 63804 63805 63806 63807 63808 63809 63810 63811 63812 63813 63814 63815 63816 63817 63818 63819 63820 63821 63822 63823 63824 63825 63826 63827 63828 63829 63830 63831 63832 63833 63834 63835 63836 63837 63838 63839 63840 63841 63842 63843 63844 63845 63846 63847 63848 63849 63850 63851 63852 63853 63854 63855 63856 63857 63858 63859 63860 63861 63862 63863 63864 63865 63866 63867 63868 63869 63870 63871 63872 63873 63874 63875 63876 63877 63878 63879 63880 63881 63882 63883 63884 63885 63886 63887 63888 63889 63890 63891 63892 63893 63894 63895 63896 63897 63898 63899 63900 63901 63902 63903 63904 63905 63906 63907 63908 63909 63910 63911 63912 63913 63914 63915 63916 63917 63918 63919 63920 63921 63922 63923 63924 63925 63926 63927 63928 63929 63930 63931 63932 63933 63934 63935 63936 63937 63938 63939 63940 63941 63942 63943 63944 63945 63946 63947 63948 63949 63950 63951 63952 63953 63954 63955 63956 63957 63958 63959 63960 63961 63962 63963 63964 63965 63966 63967 63968 63969 63970 63971 63972 63973 63974 63975 63976 63977 63978 63979 63980 63981 63982 63983 63984 63985 63986 63987 63988 63989 63990 63991 63992 63993 63994 63995 63996 63997 63998 63999 64000 64001 64002 64003 64004 64005 64006 64007 64008 64009 64010 64011 64012 64013 64014 64015 64016 64017 64018 64019 64020 64021 64022 64023 64024 64025 64026 64027 64028 64029 64030 64031 64032 64033 64034 64035 64036 64037 64038 64039 64040 64041 64042 64043 64044 64045 64046 64047 64048 64049 64050 64051 64052 64053 64054 64055 64056 64057 64058 64059 64060 64061 64062 64063 64064 64065 64066 64067 64068 64069 64070 64071 64072 64073 64074 64075 64076 64077 64078 64079 64080 64081 64082 64083 64084 64085 64086 64087 64088 64089 64090 64091 64092 64093 64094 64095 64096 64097 64098 64099 64100 64101 64102 64103 64104 64105 64106 64107 64108 64109 64110 64111 64112 64113 64114 64115 64116 64117 64118 64119 64120 64121 64122 64123 64124 64125 64126 64127 64128 64129 64130 64131 64132 64133 64134 64135 64136 64137 64138 64139 64140 64141 64142 64143 64144 64145 64146 64147 64148 64149 64150 64151 64152 64153 64154 64155 64156 64157 64158 64159 64160 64161 64162 64163 64164 64165 64166 64167 64168 64169 64170 64171 64172 64173 64174 64175 64176 64177 64178 64179 64180 64181 64182 64183 64184 64185 64186 64187 64188 64189 64190 64191 64192 64193 64194 64195 64196 64197 64198 64199 64200 64201 64202 64203 64204 64205 64206 64207 64208 64209 64210 64211 64212 64213 64214 64215 64216 64217 64218 64219 64220 64221 64222 64223 64224 64225 64226 64227 64228 64229 64230 64231 64232 64233 64234 64235 64236 64237 64238 64239 64240 64241 64242 64243 64244 64245 64246 64247 64248 64249 64250 64251 64252 64253 64254 64255 64256 64257 64258 64259 64260 64261 64262 64263 64264 64265 64266 64267 64268 64269 64270 64271 64272 64273 64274 64275 64276 64277 64278 64279 64280 64281 64282 64283 64284 64285 64286 64287 64288 64289 64290 64291 64292 64293 64294 64295 64296 64297 64298 64299 64300 64301 64302 64303 64304 64305 64306 64307 64308 64309 64310 64311 64312 64313 64314 64315 64316 64317 64318 64319 64320 64321 64322 64323 64324 64325 64326 64327 64328 64329 64330 64331 64332 64333 64334 64335 64336 64337 64338 64339 64340 64341 64342 64343 64344 64345 64346 64347 64348 64349 64350 64351 64352 64353 64354 64355 64356 64357 64358 64359 64360 64361 64362 64363 64364 64365 64366 64367 64368 64369 64370 64371 64372 64373 64374 64375 64376 64377 64378 64379 64380 64381 64382 64383 64384 64385 64386 64387 64388 64389 64390 64391 64392 64393 64394 64395 64396 64397 64398 64399 64400 64401 64402 64403 64404 64405 64406 64407 64408 64409 64410 64411 64412 64413 64414 64415 64416 64417 64418 64419 64420 64421 64422 64423 64424 64425 64426 64427 64428 64429 64430 64431 64432 64433 64434 64435 64436 64437 64438 64439 64440 64441 64442 64443 64444 64445 64446 64447 64448 64449 64450 64451 64452 64453 64454 64455 64456 64457 64458 64459 64460 64461 64462 64463 64464 64465 64466 64467 64468 64469 64470 64471 64472 64473 64474 64475 64476 64477 64478 64479 64480 64481 64482 64483 64484 64485 64486 64487 64488 64489 64490 64491 64492 64493 64494 64495 64496 64497 64498 64499 64500 64501 64502 64503 64504 64505 64506 64507 64508 64509 64510 64511 64512 64513 64514 64515 64516 64517 64518 64519 64520 64521 64522 64523 64524 64525 64526 64527 64528 64529 64530 64531 64532 64533 64534 64535 64536 64537 64538 64539 64540 64541 64542 64543 64544 64545 64546 64547 64548 64549 64550 64551 64552 64553 64554 64555 64556 64557 64558 64559 64560 64561 64562 64563 64564 64565 64566 64567 64568 64569 64570 64571 64572 64573 64574 64575 64576 64577 64578 64579 64580 64581 64582 64583 64584 64585 64586 64587 64588 64589 64590 64591 64592 64593 64594 64595 64596 64597 64598 64599 64600 64601 64602 64603 64604 64605 64606 64607 64608 64609 64610 64611 64612 64613 64614 64615 64616 64617 64618 64619 64620 64621 64622 64623 64624 64625 64626 64627 64628 64629 64630 64631 64632 64633 64634 64635 64636 64637 64638 64639 64640 64641 64642 64643 64644 64645 64646 64647 64648 64649 64650 64651 64652 64653 64654 64655 64656 64657 64658 64659 64660 64661 64662 64663 64664 64665 64666 64667 64668 64669 64670 64671 64672 64673 64674 64675 64676 64677 64678 64679 64680 64681 64682 64683 64684 64685 64686 64687 64688 64689 64690 64691 64692 64693 64694 64695 64696 64697 64698 64699 64700 64701 64702 64703 64704 64705 64706 64707 64708 64709 64710 64711 64712 64713 64714 64715 64716 64717 64718 64719 64720 64721 64722 64723 64724 64725 64726 64727 64728 64729 64730 64731 64732 64733 64734 64735 64736 64737 64738 64739 64740 64741 64742 64743 64744 64745 64746 64747 64748 64749 64750 64751 64752 64753 64754 64755 64756 64757 64758 64759 64760 64761 64762 64763 64764 64765 64766 64767 64768 64769 64770 64771 64772 64773 64774 64775 64776 64777 64778 64779 64780 64781 64782 64783 64784 64785 64786 64787 64788 64789 64790 64791 64792 64793 64794 64795 64796 64797 64798 64799 64800 64801 64802 64803 64804 64805 64806 64807 64808 64809 64810 64811 64812 64813 64814 64815 64816 64817 64818 64819 64820 64821 64822 64823 64824 64825 64826 64827 64828 64829 64830 64831 64832 64833 64834 64835 64836 64837 64838 64839 64840 64841 64842 64843 64844 64845 64846 64847 64848 64849 64850 64851 64852 64853 64854 64855 64856 64857 64858 64859 64860 64861 64862 64863 64864 64865 64866 64867 64868 64869 64870 64871 64872 64873 64874 64875 64876 64877 64878 64879 64880 64881 64882 64883 64884 64885 64886 64887 64888 64889 64890 64891 64892 64893 64894 64895 64896 64897 64898 64899 64900 64901 64902 64903 64904 64905 64906 64907 64908 64909 64910 64911 64912 64913 64914 64915 64916 64917 64918 64919 64920 64921 64922 64923 64924 64925 64926 64927 64928 64929 64930 64931 64932 64933 64934 64935 64936 64937 64938 64939 64940 64941 64942 64943 64944 64945 64946 64947 64948 64949 64950 64951 64952 64953 64954 64955 64956 64957 64958 64959 64960 64961 64962 64963 64964 64965 64966 64967 64968 64969 64970 64971 64972 64973 64974 64975 64976 64977 64978 64979 64980 64981 64982 64983 64984 64985 64986 64987 64988 64989 64990 64991 64992 64993 64994 64995 64996 64997 64998 64999 65000 65001 65002 65003 65004 65005 65006 65007 65008 65009 65010 65011 65012 65013 65014 65015 65016 65017 65018 65019 65020 65021 65022 65023 65024 65025 65026 65027 65028 65029 65030 65031 65032 65033 65034 65035 65036 65037 65038 65039 65040 65041 65042 65043 65044 65045 65046 65047 65048 65049 65050 65051 65052 65053 65054 65055 65056 65057 65058 65059 65060 65061 65062 65063 65064 65065 65066 65067 65068 65069 65070 65071 65072 65073 65074 65075 65076 65077 65078 65079 65080 65081 65082 65083 65084 65085 65086 65087 65088 65089 65090 65091 65092 65093 65094 65095 65096 65097 65098 65099 65100 65101 65102 65103 65104 65105 65106 65107 65108 65109 65110 65111 65112 65113 65114 65115 65116 65117 65118 65119 65120 65121 65122 65123 65124 65125 65126 65127 65128 65129 65130 65131 65132 65133 65134 65135 65136 65137 65138 65139 65140 65141 65142 65143 65144 65145 65146 65147 65148 65149 65150 65151 65152 65153 65154 65155 65156 65157 65158 65159 65160 65161 65162 65163 65164 65165 65166 65167 65168 65169 65170 65171 65172 65173 65174 65175 65176 65177 65178 65179 65180 65181 65182 65183 65184 65185 65186 65187 65188 65189 65190 65191 65192 65193 65194 65195 65196 65197 65198 65199 65200 65201 65202 65203 65204 65205 65206 65207 65208 65209 65210 65211 65212 65213 65214 65215 65216 65217 65218 65219 65220 65221 65222 65223 65224 65225 65226 65227 65228 65229 65230 65231 65232 65233 65234 65235 65236 65237 65238 65239 65240 65241 65242 65243 65244 65245 65246 65247 65248 65249 65250 65251 65252 65253 65254 65255 65256 65257 65258 65259 65260 65261 65262 65263 65264 65265 65266 65267 65268 65269 65270 65271 65272 65273 65274 65275 65276 65277 65278 65279 65280 65281 65282 65283 65284 65285 65286 65287 65288 65289 65290 65291 65292 65293 65294 65295 65296 65297 65298 65299 65300 65301 65302 65303 65304 65305 65306 65307 65308 65309 65310 65311 65312 65313 65314 65315 65316 65317 65318 65319 65320 65321 65322 65323 65324 65325 65326 65327 65328 65329 65330 65331 65332 65333 65334 65335 65336 65337 65338 65339 65340 65341 65342 65343 65344 65345 65346 65347 65348 65349 65350 65351 65352 65353 65354 65355 65356 65357 65358 65359 65360 65361 65362 65363 65364 65365 65366 65367 65368 65369 65370 65371 65372 65373 65374 65375 65376 65377 65378 65379 65380 65381 65382 65383 65384 65385 65386 65387 65388 65389 65390 65391 65392 65393 65394 65395 65396 65397 65398 65399 65400 65401 65402 65403 65404 65405 65406 65407 65408 65409 65410 65411 65412 65413 65414 65415 65416 65417 65418 65419 65420 65421 65422 65423 65424 65425 65426 65427 65428 65429 65430 65431 65432 65433 65434 65435 65436 65437 65438 65439 65440 65441 65442 65443 65444 65445 65446 65447 65448 65449 65450 65451 65452 65453 65454 65455 65456 65457 65458 65459 65460 65461 65462 65463 65464 65465 65466 65467 65468 65469 65470 65471 65472 65473 65474 65475 65476 65477 65478 65479 65480 65481 65482 65483 65484 65485 65486 65487 65488 65489 65490 65491 65492 65493 65494 65495 65496 65497 65498 65499 65500 65501 65502 65503 65504 65505 65506 65507 65508 65509 65510 65511 65512 65513 65514 65515 65516 65517 65518 65519 65520 65521 65522 65523 65524 65525 65526 65527 65528 65529 65530 65531 65532 65533 65534 65535 65536 65537 65538 65539 65540 65541 65542 65543 65544 65545 65546 65547 65548 65549 65550 65551 65552 65553 65554 65555 65556 65557 65558 65559 65560 65561 65562 65563 65564 65565 65566 65567 65568 65569 65570 65571 65572 65573 65574 65575 65576 65577 65578 65579 65580 65581 65582 65583 65584 65585 65586 65587 65588 65589 65590 65591 65592 65593 65594 65595 65596 65597 65598 65599 65600 65601 65602 65603 65604 65605 65606 65607 65608 65609 65610 65611 65612 65613 65614 65615 65616 65617 65618 65619 65620 65621 65622 65623 65624 65625 65626 65627 65628 65629 65630 65631 65632 65633 65634 65635 65636 65637 65638 65639 65640 65641 65642 65643 65644 65645 65646 65647 65648 65649 65650 65651 65652 65653 65654 65655 65656 65657 65658 65659 65660 65661 65662 65663 65664 65665 65666 65667 65668 65669 65670 65671 65672 65673 65674 65675 65676 65677 65678 65679 65680 65681 65682 65683 65684 65685 65686 65687 65688 65689 65690 65691 65692 65693 65694 65695 65696 65697 65698 65699 65700 65701 65702 65703 65704 65705 65706 65707 65708 65709 65710 65711 65712 65713 65714 65715 65716 65717 65718 65719 65720 65721 65722 65723 65724 65725 65726 65727 65728 65729 65730 65731 65732 65733 65734 65735 65736 65737 65738 65739 65740 65741 65742 65743 65744 65745 65746 65747 65748 65749 65750 65751 65752 65753 65754 65755 65756 65757 65758 65759 65760 65761 65762 65763 65764 65765 65766 65767 65768 65769 65770 65771 65772 65773 65774 65775 65776 65777 65778 65779 65780 65781 65782 65783 65784 65785 65786 65787 65788 65789 65790 65791 65792 65793 65794 65795 65796 65797 65798 65799 65800 65801 65802 65803 65804 65805 65806 65807 65808 65809 65810 65811 65812 65813 65814 65815 65816 65817 65818 65819 65820 65821 65822 65823 65824 65825 65826 65827 65828 65829 65830 65831 65832 65833 65834 65835 65836 65837 65838 65839 65840 65841 65842 65843 65844 65845 65846 65847 65848 65849 65850 65851 65852 65853 65854 65855 65856 65857 65858 65859 65860 65861 65862 65863 65864 65865 65866 65867 65868 65869 65870 65871 65872 65873 65874 65875 65876 65877 65878 65879 65880 65881 65882 65883 65884 65885 65886 65887 65888 65889 65890 65891 65892 65893 65894 65895 65896 65897 65898 65899 65900 65901 65902 65903 65904 65905 65906 65907 65908 65909 65910 65911 65912 65913 65914 65915 65916 65917 65918 65919 65920 65921 65922 65923 65924 65925 65926 65927 65928 65929 65930 65931 65932 65933 65934 65935 65936 65937 65938 65939 65940 65941 65942 65943 65944 65945 65946 65947 65948 65949 65950 65951 65952 65953 65954 65955 65956 65957 65958 65959 65960 65961 65962 65963 65964 65965 65966 65967 65968 65969 65970 65971 65972 65973 65974 65975 65976 65977 65978 65979 65980 65981 65982 65983 65984 65985 65986 65987 65988 65989 65990 65991 65992 65993 65994 65995 65996 65997 65998 65999 66000 66001 66002 66003 66004 66005 66006 66007 66008 66009 66010 66011 66012 66013 66014 66015 66016 66017 66018 66019 66020 66021 66022 66023 66024 66025 66026 66027 66028 66029 66030 66031 66032 66033 66034 66035 66036 66037 66038 66039 66040 66041 66042 66043 66044 66045 66046 66047 66048 66049 66050 66051 66052 66053 66054 66055 66056 66057 66058 66059 66060 66061 66062 66063 66064 66065 66066 66067 66068 66069 66070 66071 66072 66073 66074 66075 66076 66077 66078 66079 66080 66081 66082 66083 66084 66085 66086 66087 66088 66089 66090 66091 66092 66093 66094 66095 66096 66097 66098 66099 66100 66101 66102 66103 66104 66105 66106 66107 66108 66109 66110 66111 66112 66113 66114 66115 66116 66117 66118 66119 66120 66121 66122 66123 66124 66125 66126 66127 66128 66129 66130 66131 66132 66133 66134 66135 66136 66137 66138 66139 66140 66141 66142 66143 66144 66145 66146 66147 66148 66149 66150 66151 66152 66153 66154 66155 66156 66157 66158 66159 66160 66161 66162 66163 66164 66165 66166 66167 66168 66169 66170 66171 66172 66173 66174 66175 66176 66177 66178 66179 66180 66181 66182 66183 66184 66185 66186 66187 66188 66189 66190 66191 66192 66193 66194 66195 66196 66197 66198 66199 66200 66201 66202 66203 66204 66205 66206 66207 66208 66209 66210 66211 66212 66213 66214 66215 66216 66217 66218 66219 66220 66221 66222 66223 66224 66225 66226 66227 66228 66229 66230 66231 66232 66233 66234 66235 66236 66237 66238 66239 66240 66241 66242 66243 66244 66245 66246 66247 66248 66249 66250 66251 66252 66253 66254 66255 66256 66257 66258 66259 66260 66261 66262 66263 66264 66265 66266 66267 66268 66269 66270 66271 66272 66273 66274 66275 66276 66277 66278 66279 66280 66281 66282 66283 66284 66285 66286 66287 66288 66289 66290 66291 66292 66293 66294 66295 66296 66297 66298 66299 66300 66301 66302 66303 66304 66305 66306 66307 66308 66309 66310 66311 66312 66313 66314 66315 66316 66317 66318 66319 66320 66321 66322 66323 66324 66325 66326 66327 66328 66329 66330 66331 66332 66333 66334 66335 66336 66337 66338 66339 66340 66341 66342 66343 66344 66345 66346 66347 66348 66349 66350 66351 66352 66353 66354 66355 66356 66357 66358 66359 66360 66361 66362 66363 66364 66365 66366 66367 66368 66369 66370 66371 66372 66373 66374 66375 66376 66377 66378 66379 66380 66381 66382 66383 66384 66385 66386 66387 66388 66389 66390 66391 66392 66393 66394 66395 66396 66397 66398 66399 66400 66401 66402 66403 66404 66405 66406 66407 66408 66409 66410 66411 66412 66413 66414 66415 66416 66417 66418 66419 66420 66421 66422 66423 66424 66425 66426 66427 66428 66429 66430 66431 66432 66433 66434 66435 66436 66437 66438 66439 66440 66441 66442 66443 66444 66445 66446 66447 66448 66449 66450 66451 66452 66453 66454 66455 66456 66457 66458 66459 66460 66461 66462 66463 66464 66465 66466 66467 66468 66469 66470 66471 66472 66473 66474 66475 66476 66477 66478 66479 66480 66481 66482 66483 66484 66485 66486 66487 66488 66489 66490 66491 66492 66493 66494 66495 66496 66497 66498 66499 66500 66501 66502 66503 66504 66505 66506 66507 66508 66509 66510 66511 66512 66513 66514 66515 66516 66517 66518 66519 66520 66521 66522 66523 66524 66525 66526 66527 66528 66529 66530 66531 66532 66533 66534 66535 66536 66537 66538 66539 66540 66541 66542 66543 66544 66545 66546 66547 66548 66549 66550 66551 66552 66553 66554 66555 66556 66557 66558 66559 66560 66561 66562 66563 66564 66565 66566 66567 66568 66569 66570 66571 66572 66573 66574 66575 66576 66577 66578 66579 66580 66581 66582 66583 66584 66585 66586 66587 66588 66589 66590 66591 66592 66593 66594 66595 66596 66597 66598 66599 66600 66601 66602 66603 66604 66605 66606 66607 66608 66609 66610 66611 66612 66613 66614 66615 66616 66617 66618 66619 66620 66621 66622 66623 66624 66625 66626 66627 66628 66629 66630 66631 66632 66633 66634 66635 66636 66637 66638 66639 66640 66641 66642 66643 66644 66645 66646 66647 66648 66649 66650 66651 66652 66653 66654 66655 66656 66657 66658 66659 66660 66661 66662 66663 66664 66665 66666 66667 66668 66669 66670 66671 66672 66673 66674 66675 66676 66677 66678 66679 66680 66681 66682 66683 66684 66685 66686 66687 66688 66689 66690 66691 66692 66693 66694 66695 66696 66697 66698 66699 66700 66701 66702 66703 66704 66705 66706 66707 66708 66709 66710 66711 66712 66713 66714 66715 66716 66717 66718 66719 66720 66721 66722 66723 66724 66725 66726 66727 66728 66729 66730 66731 66732 66733 66734 66735 66736 66737 66738 66739 66740 66741 66742 66743 66744 66745 66746 66747 66748 66749 66750 66751 66752 66753 66754 66755 66756 66757 66758 66759 66760 66761 66762 66763 66764 66765 66766 66767 66768 66769 66770 66771 66772 66773 66774 66775 66776 66777 66778 66779 66780 66781 66782 66783 66784 66785 66786 66787 66788 66789 66790 66791 66792 66793 66794 66795 66796 66797 66798 66799 66800 66801 66802 66803 66804 66805 66806 66807 66808 66809 66810 66811 66812 66813 66814 66815 66816 66817 66818 66819 66820 66821 66822 66823 66824 66825 66826 66827 66828 66829 66830 66831 66832 66833 66834 66835 66836 66837 66838 66839 66840 66841 66842 66843 66844 66845 66846 66847 66848 66849 66850 66851 66852 66853 66854 66855 66856 66857 66858 66859 66860 66861 66862 66863 66864 66865 66866 66867 66868 66869 66870 66871 66872 66873 66874 66875 66876 66877 66878 66879 66880 66881 66882 66883 66884 66885 66886 66887 66888 66889 66890 66891 66892 66893 66894 66895 66896 66897 66898 66899 66900 66901 66902 66903 66904 66905 66906 66907 66908 66909 66910 66911 66912 66913 66914 66915 66916 66917 66918 66919 66920 66921 66922 66923 66924 66925 66926 66927 66928 66929 66930 66931 66932 66933 66934 66935 66936 66937 66938 66939 66940 66941 66942 66943 66944 66945 66946 66947 66948 66949 66950 66951 66952 66953 66954 66955 66956 66957 66958 66959 66960 66961 66962 66963 66964 66965 66966 66967 66968 66969 66970 66971 66972 66973 66974 66975 66976 66977 66978 66979 66980 66981 66982 66983 66984 66985 66986 66987 66988 66989 66990 66991 66992 66993 66994 66995 66996 66997 66998 66999 67000 67001 67002 67003 67004 67005 67006 67007 67008 67009 67010 67011 67012 67013 67014 67015 67016 67017 67018 67019 67020 67021 67022 67023 67024 67025 67026 67027 67028 67029 67030 67031 67032 67033 67034 67035 67036 67037 67038 67039 67040 67041 67042 67043 67044 67045 67046 67047 67048 67049 67050 67051 67052 67053 67054 67055 67056 67057 67058 67059 67060 67061 67062 67063 67064 67065 67066 67067 67068 67069 67070 67071 67072 67073 67074 67075 67076 67077 67078 67079 67080 67081 67082 67083 67084 67085 67086 67087 67088 67089 67090 67091 67092 67093 67094 67095 67096 67097 67098 67099 67100 67101 67102 67103 67104 67105 67106 67107 67108 67109 67110 67111 67112 67113 67114 67115 67116 67117 67118 67119 67120 67121 67122 67123 67124 67125 67126 67127 67128 67129 67130 67131 67132 67133 67134 67135 67136 67137 67138 67139 67140 67141 67142 67143 67144 67145 67146 67147 67148 67149 67150 67151 67152 67153 67154 67155 67156 67157 67158 67159 67160 67161 67162 67163 67164 67165 67166 67167 67168 67169 67170 67171 67172 67173 67174 67175 67176 67177 67178 67179 67180 67181 67182 67183 67184 67185 67186 67187 67188 67189 67190 67191 67192 67193 67194 67195 67196 67197 67198 67199 67200 67201 67202 67203 67204 67205 67206 67207 67208 67209 67210 67211 67212 67213 67214 67215 67216 67217 67218 67219 67220 67221 67222 67223 67224 67225 67226 67227 67228 67229 67230 67231 67232 67233 67234 67235 67236 67237 67238 67239 67240 67241 67242 67243 67244 67245 67246 67247 67248 67249 67250 67251 67252 67253 67254 67255 67256 67257 67258 67259 67260 67261 67262 67263 67264 67265 67266 67267 67268 67269 67270 67271 67272 67273 67274 67275 67276 67277 67278 67279 67280 67281 67282 67283 67284 67285 67286 67287 67288 67289 67290 67291 67292 67293 67294 67295 67296 67297 67298 67299 67300 67301 67302 67303 67304 67305 67306 67307 67308 67309 67310 67311 67312 67313 67314 67315 67316 67317 67318 67319 67320 67321 67322 67323 67324 67325 67326 67327 67328 67329 67330 67331 67332 67333 67334 67335 67336 67337 67338 67339 67340 67341 67342 67343 67344 67345 67346 67347 67348 67349 67350 67351 67352 67353 67354 67355 67356 67357 67358 67359 67360 67361 67362 67363 67364 67365 67366 67367 67368 67369 67370 67371 67372 67373 67374 67375 67376 67377 67378 67379 67380 67381 67382 67383 67384 67385 67386 67387 67388 67389 67390 67391 67392 67393 67394 67395 67396 67397 67398 67399 67400 67401 67402 67403 67404 67405 67406 67407 67408 67409 67410 67411 67412 67413 67414 67415 67416 67417 67418 67419 67420 67421 67422 67423 67424 67425 67426 67427 67428 67429 67430 67431 67432 67433 67434 67435 67436 67437 67438 67439 67440 67441 67442 67443 67444 67445 67446 67447 67448 67449 67450 67451 67452 67453 67454 67455 67456 67457 67458 67459 67460 67461 67462 67463 67464 67465 67466 67467 67468 67469 67470 67471 67472 67473 67474 67475 67476 67477 67478 67479 67480 67481 67482 67483 67484 67485 67486 67487 67488 67489 67490 67491 67492 67493 67494 67495 67496 67497 67498 67499 67500 67501 67502 67503 67504 67505 67506 67507 67508 67509 67510 67511 67512 67513 67514 67515 67516 67517 67518 67519 67520 67521 67522 67523 67524 67525 67526 67527 67528 67529 67530 67531 67532 67533 67534 67535 67536 67537 67538 67539 67540 67541 67542 67543 67544 67545 67546 67547 67548 67549 67550 67551 67552 67553 67554 67555 67556 67557 67558 67559 67560 67561 67562 67563 67564 67565 67566 67567 67568 67569 67570 67571 67572 67573 67574 67575 67576 67577 67578 67579 67580 67581 67582 67583 67584 67585 67586 67587 67588 67589 67590 67591 67592 67593 67594 67595 67596 67597 67598 67599 67600 67601 67602 67603 67604 67605 67606 67607 67608 67609 67610 67611 67612 67613 67614 67615 67616 67617 67618 67619 67620 67621 67622 67623 67624 67625 67626 67627 67628 67629 67630 67631 67632 67633 67634 67635 67636 67637 67638 67639 67640 67641 67642 67643 67644 67645 67646 67647 67648 67649 67650 67651 67652 67653 67654 67655 67656 67657 67658 67659 67660 67661 67662 67663 67664 67665 67666 67667 67668 67669 67670 67671 67672 67673 67674 67675 67676 67677 67678 67679 67680 67681 67682 67683 67684 67685 67686 67687 67688 67689 67690 67691 67692 67693 67694 67695 67696 67697 67698 67699 67700 67701 67702 67703 67704 67705 67706 67707 67708 67709 67710 67711 67712 67713 67714 67715 67716 67717 67718 67719 67720 67721 67722 67723 67724 67725 67726 67727 67728 67729 67730 67731 67732 67733 67734 67735 67736 67737 67738 67739 67740 67741 67742 67743 67744 67745 67746 67747 67748 67749 67750 67751 67752 67753 67754 67755 67756 67757 67758 67759 67760 67761 67762 67763 67764 67765 67766 67767 67768 67769 67770 67771 67772 67773 67774 67775 67776 67777 67778 67779 67780 67781 67782 67783 67784 67785 67786 67787 67788 67789 67790 67791 67792 67793 67794 67795 67796 67797 67798 67799 67800 67801 67802 67803 67804 67805 67806 67807 67808 67809 67810 67811 67812 67813 67814 67815 67816 67817 67818 67819 67820 67821 67822 67823 67824 67825 67826 67827 67828 67829 67830 67831 67832 67833 67834 67835 67836 67837 67838 67839 67840 67841 67842 67843 67844 67845 67846 67847 67848 67849 67850 67851 67852 67853 67854 67855 67856 67857 67858 67859 67860 67861 67862 67863 67864 67865 67866 67867 67868 67869 67870 67871 67872 67873 67874 67875 67876 67877 67878 67879 67880 67881 67882 67883 67884 67885 67886 67887 67888 67889 67890 67891 67892 67893 67894 67895 67896 67897 67898 67899 67900 67901 67902 67903 67904 67905 67906 67907 67908 67909 67910 67911 67912 67913 67914 67915 67916 67917 67918 67919 67920 67921 67922 67923 67924 67925 67926 67927 67928 67929 67930 67931 67932 67933 67934 67935 67936 67937 67938 67939 67940 67941 67942 67943 67944 67945 67946 67947 67948 67949 67950 67951 67952 67953 67954 67955 67956 67957 67958 67959 67960 67961 67962 67963 67964 67965 67966 67967 67968 67969 67970 67971 67972 67973 67974 67975 67976 67977 67978 67979 67980 67981 67982 67983 67984 67985 67986 67987 67988 67989 67990 67991 67992 67993 67994 67995 67996 67997 67998 67999 68000 68001 68002 68003 68004 68005 68006 68007 68008 68009 68010 68011 68012 68013 68014 68015 68016 68017 68018 68019 68020 68021 68022 68023 68024 68025 68026 68027 68028 68029 68030 68031 68032 68033 68034 68035 68036 68037 68038 68039 68040 68041 68042 68043 68044 68045 68046 68047 68048 68049 68050 68051 68052 68053 68054 68055 68056 68057 68058 68059 68060 68061 68062 68063 68064 68065 68066 68067 68068 68069 68070 68071 68072 68073 68074 68075 68076 68077 68078 68079 68080 68081 68082 68083 68084 68085 68086 68087 68088 68089 68090 68091 68092 68093 68094 68095 68096 68097 68098 68099 68100 68101 68102 68103 68104 68105 68106 68107 68108 68109 68110 68111 68112 68113 68114 68115 68116 68117 68118 68119 68120 68121 68122 68123 68124 68125 68126 68127 68128 68129 68130 68131 68132 68133 68134 68135 68136 68137 68138 68139 68140 68141 68142 68143 68144 68145 68146 68147 68148 68149 68150 68151 68152 68153 68154 68155 68156 68157 68158 68159 68160 68161 68162 68163 68164 68165 68166 68167 68168 68169 68170 68171 68172 68173 68174 68175 68176 68177 68178 68179 68180 68181 68182 68183 68184 68185 68186 68187 68188 68189 68190 68191 68192 68193 68194 68195 68196 68197 68198 68199 68200 68201 68202 68203 68204 68205 68206 68207 68208 68209 68210 68211 68212 68213 68214 68215 68216 68217 68218 68219 68220 68221 68222 68223 68224 68225 68226 68227 68228 68229 68230 68231 68232 68233 68234 68235 68236 68237 68238 68239 68240 68241 68242 68243 68244 68245 68246 68247 68248 68249 68250 68251 68252 68253 68254 68255 68256 68257 68258 68259 68260 68261 68262 68263 68264 68265 68266 68267 68268 68269 68270 68271 68272 68273 68274 68275 68276 68277 68278 68279 68280 68281 68282 68283 68284 68285 68286 68287 68288 68289 68290 68291 68292 68293 68294 68295 68296 68297 68298 68299 68300 68301 68302 68303 68304 68305 68306 68307 68308 68309 68310 68311 68312 68313 68314 68315 68316 68317 68318 68319 68320 68321 68322 68323 68324 68325 68326 68327 68328 68329 68330 68331 68332 68333 68334 68335 68336 68337 68338 68339 68340 68341 68342 68343 68344 68345 68346 68347 68348 68349 68350 68351 68352 68353 68354 68355 68356 68357 68358 68359 68360 68361 68362 68363 68364 68365 68366 68367 68368 68369 68370 68371 68372 68373 68374 68375 68376 68377 68378 68379 68380 68381 68382 68383 68384 68385 68386 68387 68388 68389 68390 68391 68392 68393 68394 68395 68396 68397 68398 68399 68400 68401 68402 68403 68404 68405 68406 68407 68408 68409 68410 68411 68412 68413 68414 68415 68416 68417 68418 68419 68420 68421 68422 68423 68424 68425 68426 68427 68428 68429 68430 68431 68432 68433 68434 68435 68436 68437 68438 68439 68440 68441 68442 68443 68444 68445 68446 68447 68448 68449 68450 68451 68452 68453 68454 68455 68456 68457 68458 68459 68460 68461 68462 68463 68464 68465 68466 68467 68468 68469 68470 68471 68472 68473 68474 68475 68476 68477 68478 68479 68480 68481 68482 68483 68484 68485 68486 68487 68488 68489 68490 68491 68492 68493 68494 68495 68496 68497 68498 68499 68500 68501 68502 68503 68504 68505 68506 68507 68508 68509 68510 68511 68512 68513 68514 68515 68516 68517 68518 68519 68520 68521 68522 68523 68524 68525 68526 68527 68528 68529 68530 68531 68532 68533 68534 68535 68536 68537 68538 68539 68540 68541 68542 68543 68544 68545 68546 68547 68548 68549 68550 68551 68552 68553 68554 68555 68556 68557 68558 68559 68560 68561 68562 68563 68564 68565 68566 68567 68568 68569 68570 68571 68572 68573 68574 68575 68576 68577 68578 68579 68580 68581 68582 68583 68584 68585 68586 68587 68588 68589 68590 68591 68592 68593 68594 68595 68596 68597 68598 68599 68600 68601 68602 68603 68604 68605 68606 68607 68608 68609 68610 68611 68612 68613 68614 68615 68616 68617 68618 68619 68620 68621 68622 68623 68624 68625 68626 68627 68628 68629 68630 68631 68632 68633 68634 68635 68636 68637 68638 68639 68640 68641 68642 68643 68644 68645 68646 68647 68648 68649 68650 68651 68652 68653 68654 68655 68656 68657 68658 68659 68660 68661 68662 68663 68664 68665 68666 68667 68668 68669 68670 68671 68672 68673 68674 68675 68676 68677 68678 68679 68680 68681 68682 68683 68684 68685 68686 68687 68688 68689 68690 68691 68692 68693 68694 68695 68696 68697 68698 68699 68700 68701 68702 68703 68704 68705 68706 68707 68708 68709 68710 68711 68712 68713 68714 68715 68716 68717 68718 68719 68720 68721 68722 68723 68724 68725 68726 68727 68728 68729 68730 68731 68732 68733 68734 68735 68736 68737 68738 68739 68740 68741 68742 68743 68744 68745 68746 68747 68748 68749 68750 68751 68752 68753 68754 68755 68756 68757 68758 68759 68760 68761 68762 68763 68764 68765 68766 68767 68768 68769 68770 68771 68772 68773 68774 68775 68776 68777 68778 68779 68780 68781 68782 68783 68784 68785 68786 68787 68788 68789 68790 68791 68792 68793 68794 68795 68796 68797 68798 68799 68800 68801 68802 68803 68804 68805 68806 68807 68808 68809 68810 68811 68812 68813 68814 68815 68816 68817 68818 68819 68820 68821 68822 68823 68824 68825 68826 68827 68828 68829 68830 68831 68832 68833 68834 68835 68836 68837 68838 68839 68840 68841 68842 68843 68844 68845 68846 68847 68848 68849 68850 68851 68852 68853 68854 68855 68856 68857 68858 68859 68860 68861 68862 68863 68864 68865 68866 68867 68868 68869 68870 68871 68872 68873 68874 68875 68876 68877 68878 68879 68880 68881 68882 68883 68884 68885 68886 68887 68888 68889 68890 68891 68892 68893 68894 68895 68896 68897 68898 68899 68900 68901 68902 68903 68904 68905 68906 68907 68908 68909 68910 68911 68912 68913 68914 68915 68916 68917 68918 68919 68920 68921 68922 68923 68924 68925 68926 68927 68928 68929 68930 68931 68932 68933 68934 68935 68936 68937 68938 68939 68940 68941 68942 68943 68944 68945 68946 68947 68948 68949 68950 68951 68952 68953 68954 68955 68956 68957 68958 68959 68960 68961 68962 68963 68964 68965 68966 68967 68968 68969 68970 68971 68972 68973 68974 68975 68976 68977 68978 68979 68980 68981 68982 68983 68984 68985 68986 68987 68988 68989 68990 68991 68992 68993 68994 68995 68996 68997 68998 68999 69000 69001 69002 69003 69004 69005 69006 69007 69008 69009 69010 69011 69012 69013 69014 69015 69016 69017 69018 69019 69020 69021 69022 69023 69024 69025 69026 69027 69028 69029 69030 69031 69032 69033 69034 69035 69036 69037 69038 69039 69040 69041 69042 69043 69044 69045 69046 69047 69048 69049 69050 69051 69052 69053 69054 69055 69056 69057 69058 69059 69060 69061 69062 69063 69064 69065 69066 69067 69068 69069 69070 69071 69072 69073 69074 69075 69076 69077 69078 69079 69080 69081 69082 69083 69084 69085 69086 69087 69088 69089 69090 69091 69092 69093 69094 69095 69096 69097 69098 69099 69100 69101 69102 69103 69104 69105 69106 69107 69108 69109 69110 69111 69112 69113 69114 69115 69116 69117 69118 69119 69120 69121 69122 69123 69124 69125 69126 69127 69128 69129 69130 69131 69132 69133 69134 69135 69136 69137 69138 69139 69140 69141 69142 69143 69144 69145 69146 69147 69148 69149 69150 69151 69152 69153 69154 69155 69156 69157 69158 69159 69160 69161 69162 69163 69164 69165 69166 69167 69168 69169 69170 69171 69172 69173 69174 69175 69176 69177 69178 69179 69180 69181 69182 69183 69184 69185 69186 69187 69188 69189 69190 69191 69192 69193 69194 69195 69196 69197 69198 69199 69200 69201 69202 69203 69204 69205 69206 69207 69208 69209 69210 69211 69212 69213 69214 69215 69216 69217 69218 69219 69220 69221 69222 69223 69224 69225 69226 69227 69228 69229 69230 69231 69232 69233 69234 69235 69236 69237 69238 69239 69240 69241 69242 69243 69244 69245 69246 69247 69248 69249 69250 69251 69252 69253 69254 69255 69256 69257 69258 69259 69260 69261 69262 69263 69264 69265 69266 69267 69268 69269 69270 69271 69272 69273 69274 69275 69276 69277 69278 69279 69280 69281 69282 69283 69284 69285 69286 69287 69288 69289 69290 69291 69292 69293 69294 69295 69296 69297 69298 69299 69300 69301 69302 69303 69304 69305 69306 69307 69308 69309 69310 69311 69312 69313 69314 69315 69316 69317 69318 69319 69320 69321 69322 69323 69324 69325 69326 69327 69328 69329 69330 69331 69332 69333 69334 69335 69336 69337 69338 69339 69340 69341 69342 69343 69344 69345 69346 69347 69348 69349 69350 69351 69352 69353 69354 69355 69356 69357 69358 69359 69360 69361 69362 69363 69364 69365 69366 69367 69368 69369 69370 69371 69372 69373 69374 69375 69376 69377 69378 69379 69380 69381 69382 69383 69384 69385 69386 69387 69388 69389 69390 69391 69392 69393 69394 69395 69396 69397 69398 69399 69400 69401 69402 69403 69404 69405 69406 69407 69408 69409 69410 69411 69412 69413 69414 69415 69416 69417 69418 69419 69420 69421 69422 69423 69424 69425 69426 69427 69428 69429 69430 69431 69432 69433 69434 69435 69436 69437 69438 69439 69440 69441 69442 69443 69444 69445 69446 69447 69448 69449 69450 69451 69452 69453 69454 69455 69456 69457 69458 69459 69460 69461 69462 69463 69464 69465 69466 69467 69468 69469 69470 69471 69472 69473 69474 69475 69476 69477 69478 69479 69480 69481 69482 69483 69484 69485 69486 69487 69488 69489 69490 69491 69492 69493 69494 69495 69496 69497 69498 69499 69500 69501 69502 69503 69504 69505 69506 69507 69508 69509 69510 69511 69512 69513 69514 69515 69516 69517 69518 69519 69520 69521 69522 69523 69524 69525 69526 69527 69528 69529 69530 69531 69532 69533 69534 69535 69536 69537 69538 69539 69540 69541 69542 69543 69544 69545 69546 69547 69548 69549 69550 69551 69552 69553 69554 69555 69556 69557 69558 69559 69560 69561 69562 69563 69564 69565 69566 69567 69568 69569 69570 69571 69572 69573 69574 69575 69576 69577 69578 69579 69580 69581 69582 69583 69584 69585 69586 69587 69588 69589 69590 69591 69592 69593 69594 69595 69596 69597 69598 69599 69600 69601 69602 69603 69604 69605 69606 69607 69608 69609 69610 69611 69612 69613 69614 69615 69616 69617 69618 69619 69620 69621 69622 69623 69624 69625 69626 69627 69628 69629 69630 69631 69632 69633 69634 69635 69636 69637 69638 69639 69640 69641 69642 69643 69644 69645 69646 69647 69648 69649 69650 69651 69652 69653 69654 69655 69656 69657 69658 69659 69660 69661 69662 69663 69664 69665 69666 69667 69668 69669 69670 69671 69672 69673 69674 69675 69676 69677 69678 69679 69680 69681 69682 69683 69684 69685 69686 69687 69688 69689 69690 69691 69692 69693 69694 69695 69696 69697 69698 69699 69700 69701 69702 69703 69704 69705 69706 69707 69708 69709 69710 69711 69712 69713 69714 69715 69716 69717 69718 69719 69720 69721 69722 69723 69724 69725 69726 69727 69728 69729 69730 69731 69732 69733 69734 69735 69736 69737 69738 69739 69740 69741 69742 69743 69744 69745 69746 69747 69748 69749 69750 69751 69752 69753 69754 69755 69756 69757 69758 69759 69760 69761 69762 69763 69764 69765 69766 69767 69768 69769 69770 69771 69772 69773 69774 69775 69776 69777 69778 69779 69780 69781 69782 69783 69784 69785 69786 69787 69788 69789 69790 69791 69792 69793 69794 69795 69796 69797 69798 69799 69800 69801 69802 69803 69804 69805 69806 69807 69808 69809 69810 69811 69812 69813 69814 69815 69816 69817 69818 69819 69820 69821 69822 69823 69824 69825 69826 69827 69828 69829 69830 69831 69832 69833 69834 69835 69836 69837 69838 69839 69840 69841 69842 69843 69844 69845 69846 69847 69848 69849 69850 69851 69852 69853 69854 69855 69856 69857 69858 69859 69860 69861 69862 69863 69864 69865 69866 69867 69868 69869 69870 69871 69872 69873 69874 69875 69876 69877 69878 69879 69880 69881 69882 69883 69884 69885 69886 69887 69888 69889 69890 69891 69892 69893 69894 69895 69896 69897 69898 69899 69900 69901 69902 69903 69904 69905 69906 69907 69908 69909 69910 69911 69912 69913 69914 69915 69916 69917 69918 69919 69920 69921 69922 69923 69924 69925 69926 69927 69928 69929 69930 69931 69932 69933 69934 69935 69936 69937 69938 69939 69940 69941 69942 69943 69944 69945 69946 69947 69948 69949 69950 69951 69952 69953 69954 69955 69956 69957 69958 69959 69960 69961 69962 69963 69964 69965 69966 69967 69968 69969 69970 69971 69972 69973 69974 69975 69976 69977 69978 69979 69980 69981 69982 69983 69984 69985 69986 69987 69988 69989 69990 69991 69992 69993 69994 69995 69996 69997 69998 69999 70000 70001 70002 70003 70004 70005 70006 70007 70008 70009 70010 70011 70012 70013 70014 70015 70016 70017 70018 70019 70020 70021 70022 70023 70024 70025 70026 70027 70028 70029 70030 70031 70032 70033 70034 70035 70036 70037 70038 70039 70040 70041 70042 70043 70044 70045 70046 70047 70048 70049 70050 70051 70052 70053 70054 70055 70056 70057 70058 70059 70060 70061 70062 70063 70064 70065 70066 70067 70068 70069 70070 70071 70072 70073 70074 70075 70076 70077 70078 70079 70080 70081 70082 70083 70084 70085 70086 70087 70088 70089 70090 70091 70092 70093 70094 70095 70096 70097 70098 70099 70100 70101 70102 70103 70104 70105 70106 70107 70108 70109 70110 70111 70112 70113 70114 70115 70116 70117 70118 70119 70120 70121 70122 70123 70124 70125 70126 70127 70128 70129 70130 70131 70132 70133 70134 70135 70136 70137 70138 70139 70140 70141 70142 70143 70144 70145 70146 70147 70148 70149 70150 70151 70152 70153 70154 70155 70156 70157 70158 70159 70160 70161 70162 70163 70164 70165 70166 70167 70168 70169 70170 70171 70172 70173 70174 70175 70176 70177 70178 70179 70180 70181 70182 70183 70184 70185 70186 70187 70188 70189 70190 70191 70192 70193 70194 70195 70196 70197 70198 70199 70200 70201 70202 70203 70204 70205 70206 70207 70208 70209 70210 70211 70212 70213 70214 70215 70216 70217 70218 70219 70220 70221 70222 70223 70224 70225 70226 70227 70228 70229 70230 70231 70232 70233 70234 70235 70236 70237 70238 70239 70240 70241 70242 70243 70244 70245 70246 70247 70248 70249 70250 70251 70252 70253 70254 70255 70256 70257 70258 70259 70260 70261 70262 70263 70264 70265 70266 70267 70268 70269 70270 70271 70272 70273 70274 70275 70276 70277 70278 70279 70280 70281 70282 70283 70284 70285 70286 70287 70288 70289 70290 70291 70292 70293 70294 70295 70296 70297 70298 70299 70300 70301 70302 70303 70304 70305 70306 70307 70308 70309 70310 70311 70312 70313 70314 70315 70316 70317 70318 70319 70320 70321 70322 70323 70324 70325 70326 70327 70328 70329 70330 70331 70332 70333 70334 70335 70336 70337 70338 70339 70340 70341 70342 70343 70344 70345 70346 70347 70348 70349 70350 70351 70352 70353 70354 70355 70356 70357 70358 70359 70360 70361 70362 70363 70364 70365 70366 70367 70368 70369 70370 70371 70372 70373 70374 70375 70376 70377 70378 70379 70380 70381 70382 70383 70384 70385 70386 70387 70388 70389 70390 70391 70392 70393 70394 70395 70396 70397 70398 70399 70400 70401 70402 70403 70404 70405 70406 70407 70408 70409 70410 70411 70412 70413 70414 70415 70416 70417 70418 70419 70420 70421 70422 70423 70424 70425 70426 70427 70428 70429 70430 70431 70432 70433 70434 70435 70436 70437 70438 70439 70440 70441 70442 70443 70444 70445 70446 70447 70448 70449 70450 70451 70452 70453 70454 70455 70456 70457 70458 70459 70460 70461 70462 70463 70464 70465 70466 70467 70468 70469 70470 70471 70472 70473 70474 70475 70476 70477 70478 70479 70480 70481 70482 70483 70484 70485 70486 70487 70488 70489 70490 70491 70492 70493 70494 70495 70496 70497 70498 70499 70500 70501 70502 70503 70504 70505 70506 70507 70508 70509 70510 70511 70512 70513 70514 70515 70516 70517 70518 70519 70520 70521 70522 70523 70524 70525 70526 70527 70528 70529 70530 70531 70532 70533 70534 70535 70536 70537 70538 70539 70540 70541 70542 70543 70544 70545 70546 70547 70548 70549 70550 70551 70552 70553 70554 70555 70556 70557 70558 70559 70560 70561 70562 70563 70564 70565 70566 70567 70568 70569 70570 70571 70572 70573 70574 70575 70576 70577 70578 70579 70580 70581 70582 70583 70584 70585 70586 70587 70588 70589 70590 70591 70592 70593 70594 70595 70596 70597 70598 70599 70600 70601 70602 70603 70604 70605 70606 70607 70608 70609 70610 70611 70612 70613 70614 70615 70616 70617 70618 70619 70620 70621 70622 70623 70624 70625 70626 70627 70628 70629 70630 70631 70632 70633 70634 70635 70636 70637 70638 70639 70640 70641 70642 70643 70644 70645 70646 70647 70648 70649 70650 70651 70652 70653 70654 70655 70656 70657 70658 70659 70660 70661 70662 70663 70664 70665 70666 70667 70668 70669 70670 70671 70672 70673 70674 70675 70676 70677 70678 70679 70680 70681 70682 70683 70684 70685 70686 70687 70688 70689 70690 70691 70692 70693 70694 70695 70696 70697 70698 70699 70700 70701 70702 70703 70704 70705 70706 70707 70708 70709 70710 70711 70712 70713 70714 70715 70716 70717 70718 70719 70720 70721 70722 70723 70724 70725 70726 70727 70728 70729 70730 70731 70732 70733 70734 70735 70736 70737 70738 70739 70740 70741 70742 70743 70744 70745 70746 70747 70748 70749 70750 70751 70752 70753 70754 70755 70756 70757 70758 70759 70760 70761 70762 70763 70764 70765 70766 70767 70768 70769 70770 70771 70772 70773 70774 70775 70776 70777 70778 70779 70780 70781 70782 70783 70784 70785 70786 70787 70788 70789 70790 70791 70792 70793 70794 70795 70796 70797 70798 70799 70800 70801 70802 70803 70804 70805 70806 70807 70808 70809 70810 70811 70812 70813 70814 70815 70816 70817 70818 70819 70820 70821 70822 70823 70824 70825 70826 70827 70828 70829 70830 70831 70832 70833 70834 70835 70836 70837 70838 70839 70840 70841 70842 70843 70844 70845 70846 70847 70848 70849 70850 70851 70852 70853 70854 70855 70856 70857 70858 70859 70860 70861 70862 70863 70864 70865 70866 70867 70868 70869 70870 70871 70872 70873 70874 70875 70876 70877 70878 70879 70880 70881 70882 70883 70884 70885 70886 70887 70888 70889 70890 70891 70892 70893 70894 70895 70896 70897 70898 70899 70900 70901 70902 70903 70904 70905 70906 70907 70908 70909 70910 70911 70912 70913 70914 70915 70916 70917 70918 70919 70920 70921 70922 70923 70924 70925 70926 70927 70928 70929 70930 70931 70932 70933 70934 70935 70936 70937 70938 70939 70940 70941 70942 70943 70944 70945 70946 70947 70948 70949 70950 70951 70952 70953 70954 70955 70956 70957 70958 70959 70960 70961 70962 70963 70964 70965 70966 70967 70968 70969 70970 70971 70972 70973 70974 70975 70976 70977 70978 70979 70980 70981 70982 70983 70984 70985 70986 70987 70988 70989 70990 70991 70992 70993 70994 70995 70996 70997 70998 70999 71000 71001 71002 71003 71004 71005 71006 71007 71008 71009 71010 71011 71012 71013 71014 71015 71016 71017 71018 71019 71020 71021 71022 71023 71024 71025 71026 71027 71028 71029 71030 71031 71032 71033 71034 71035 71036 71037 71038 71039 71040 71041 71042 71043 71044 71045 71046 71047 71048 71049 71050 71051 71052 71053 71054 71055 71056 71057 71058 71059 71060 71061 71062 71063 71064 71065 71066 71067 71068 71069 71070 71071 71072 71073 71074 71075 71076 71077 71078 71079 71080 71081 71082 71083 71084 71085 71086 71087 71088 71089 71090 71091 71092 71093 71094 71095 71096 71097 71098 71099 71100 71101 71102 71103 71104 71105 71106 71107 71108 71109 71110 71111 71112 71113 71114 71115 71116 71117 71118 71119 71120 71121 71122 71123 71124 71125 71126 71127 71128 71129 71130 71131 71132 71133 71134 71135 71136 71137 71138 71139 71140 71141 71142 71143 71144 71145 71146 71147 71148 71149 71150 71151 71152 71153 71154 71155 71156 71157 71158 71159 71160 71161 71162 71163 71164 71165 71166 71167 71168 71169 71170 71171 71172 71173 71174 71175 71176 71177 71178 71179 71180 71181 71182 71183 71184 71185 71186 71187 71188 71189 71190 71191 71192 71193 71194 71195 71196 71197 71198 71199 71200 71201 71202 71203 71204 71205 71206 71207 71208 71209 71210 71211 71212 71213 71214 71215 71216 71217 71218 71219 71220 71221 71222 71223 71224 71225 71226 71227 71228 71229 71230 71231 71232 71233 71234 71235 71236 71237 71238 71239 71240 71241 71242 71243 71244 71245 71246 71247 71248 71249 71250 71251 71252 71253 71254 71255 71256 71257 71258 71259 71260 71261 71262 71263 71264 71265 71266 71267 71268 71269 71270 71271 71272 71273 71274 71275 71276 71277 71278 71279 71280 71281 71282 71283 71284 71285 71286 71287 71288 71289 71290 71291 71292 71293 71294 71295 71296 71297 71298 71299 71300 71301 71302 71303 71304 71305 71306 71307 71308 71309 71310 71311 71312 71313 71314 71315 71316 71317 71318 71319 71320 71321 71322 71323 71324 71325 71326 71327 71328 71329 71330 71331 71332 71333 71334 71335 71336 71337 71338 71339 71340 71341 71342 71343 71344 71345 71346 71347 71348 71349 71350 71351 71352 71353 71354 71355 71356 71357 71358 71359 71360 71361 71362 71363 71364 71365 71366 71367 71368 71369 71370 71371 71372 71373 71374 71375 71376 71377 71378 71379 71380 71381 71382 71383 71384 71385 71386 71387 71388 71389 71390 71391 71392 71393 71394 71395 71396 71397 71398 71399 71400 71401 71402 71403 71404 71405 71406 71407 71408 71409 71410 71411 71412 71413 71414 71415 71416 71417 71418 71419 71420 71421 71422 71423 71424 71425 71426 71427 71428 71429 71430 71431 71432 71433 71434 71435 71436 71437 71438 71439 71440 71441 71442 71443 71444 71445 71446 71447 71448 71449 71450 71451 71452 71453 71454 71455 71456 71457 71458 71459 71460 71461 71462 71463 71464 71465 71466 71467 71468 71469 71470 71471 71472 71473 71474 71475 71476 71477 71478 71479 71480 71481 71482 71483 71484 71485 71486 71487 71488 71489 71490 71491 71492 71493 71494 71495 71496 71497 71498 71499 71500 71501 71502 71503 71504 71505 71506 71507 71508 71509 71510 71511 71512 71513 71514 71515 71516 71517 71518 71519 71520 71521 71522 71523 71524 71525 71526 71527 71528 71529 71530 71531 71532 71533 71534 71535 71536 71537 71538 71539 71540 71541 71542 71543 71544 71545 71546 71547 71548 71549 71550 71551 71552 71553 71554 71555 71556 71557 71558 71559 71560 71561 71562 71563 71564 71565 71566 71567 71568 71569 71570 71571 71572 71573 71574 71575 71576 71577 71578 71579 71580 71581 71582 71583 71584 71585 71586 71587 71588 71589 71590 71591 71592 71593 71594 71595 71596 71597 71598 71599 71600 71601 71602 71603 71604 71605 71606 71607 71608 71609 71610 71611 71612 71613 71614 71615 71616 71617 71618 71619 71620 71621 71622 71623 71624 71625 71626 71627 71628 71629 71630 71631 71632 71633 71634 71635 71636 71637 71638 71639 71640 71641 71642 71643 71644 71645 71646 71647 71648 71649 71650 71651 71652 71653 71654 71655 71656 71657 71658 71659 71660 71661 71662 71663 71664 71665 71666 71667 71668 71669 71670 71671 71672 71673 71674 71675 71676 71677 71678 71679 71680 71681 71682 71683 71684 71685 71686 71687 71688 71689 71690 71691 71692 71693 71694 71695 71696 71697 71698 71699 71700 71701 71702 71703 71704 71705 71706 71707 71708 71709 71710 71711 71712 71713 71714 71715 71716 71717 71718 71719 71720 71721 71722 71723 71724 71725 71726 71727 71728 71729 71730 71731 71732 71733 71734 71735 71736 71737 71738 71739 71740 71741 71742 71743 71744 71745 71746 71747 71748 71749 71750 71751 71752 71753 71754 71755 71756 71757 71758 71759 71760 71761 71762 71763 71764 71765 71766 71767 71768 71769 71770 71771 71772 71773 71774 71775 71776 71777 71778 71779 71780 71781 71782 71783 71784 71785 71786 71787 71788 71789 71790 71791 71792 71793 71794 71795 71796 71797 71798 71799 71800 71801 71802 71803 71804 71805 71806 71807 71808 71809 71810 71811 71812 71813 71814 71815 71816 71817 71818 71819 71820 71821 71822 71823 71824 71825 71826 71827 71828 71829 71830 71831 71832 71833 71834 71835 71836 71837 71838 71839 71840 71841 71842 71843 71844 71845 71846 71847 71848 71849 71850 71851 71852 71853 71854 71855 71856 71857 71858 71859 71860 71861 71862 71863 71864 71865 71866 71867 71868 71869 71870 71871 71872 71873 71874 71875 71876 71877 71878 71879 71880 71881 71882 71883 71884 71885 71886 71887 71888 71889 71890 71891 71892 71893 71894 71895 71896 71897 71898 71899 71900 71901 71902 71903 71904 71905 71906 71907 71908 71909 71910 71911 71912 71913 71914 71915 71916 71917 71918 71919 71920 71921 71922 71923 71924 71925 71926 71927 71928 71929 71930 71931 71932 71933 71934 71935 71936 71937 71938 71939 71940 71941 71942 71943 71944 71945 71946 71947 71948 71949 71950 71951 71952 71953 71954 71955 71956 71957 71958 71959 71960 71961 71962 71963 71964 71965 71966 71967 71968 71969 71970 71971 71972 71973 71974 71975 71976 71977 71978 71979 71980 71981 71982 71983 71984 71985 71986 71987 71988 71989 71990 71991 71992 71993 71994 71995 71996 71997 71998 71999 72000 72001 72002 72003 72004 72005 72006 72007 72008 72009 72010 72011 72012 72013 72014 72015 72016 72017 72018 72019 72020 72021 72022 72023 72024 72025 72026 72027 72028 72029 72030 72031 72032 72033 72034 72035 72036 72037 72038 72039 72040 72041 72042 72043 72044 72045 72046 72047 72048 72049 72050 72051 72052 72053 72054 72055 72056 72057 72058 72059 72060 72061 72062 72063 72064 72065 72066 72067 72068 72069 72070 72071 72072 72073 72074 72075 72076 72077 72078 72079 72080 72081 72082 72083 72084 72085 72086 72087 72088 72089 72090 72091 72092 72093 72094 72095 72096 72097 72098 72099 72100 72101 72102 72103 72104 72105 72106 72107 72108 72109 72110 72111 72112 72113 72114 72115 72116 72117 72118 72119 72120 72121 72122 72123 72124 72125 72126 72127 72128 72129 72130 72131 72132 72133 72134 72135 72136 72137 72138 72139 72140 72141 72142 72143 72144 72145 72146 72147 72148 72149 72150 72151 72152 72153 72154 72155 72156 72157 72158 72159 72160 72161 72162 72163 72164 72165 72166 72167 72168 72169 72170 72171 72172 72173 72174 72175 72176 72177 72178 72179 72180 72181 72182 72183 72184 72185 72186 72187 72188 72189 72190 72191 72192 72193 72194 72195 72196 72197 72198 72199 72200 72201 72202 72203 72204 72205 72206 72207 72208 72209 72210 72211 72212 72213 72214 72215 72216 72217 72218 72219 72220 72221 72222 72223 72224 72225 72226 72227 72228 72229 72230 72231 72232 72233 72234 72235 72236 72237 72238 72239 72240 72241 72242 72243 72244 72245 72246 72247 72248 72249 72250 72251 72252 72253 72254 72255 72256 72257 72258 72259 72260 72261 72262 72263 72264 72265 72266 72267 72268 72269 72270 72271 72272 72273 72274 72275 72276 72277 72278 72279 72280 72281 72282 72283 72284 72285 72286 72287 72288 72289 72290 72291 72292 72293 72294 72295 72296 72297 72298 72299 72300 72301 72302 72303 72304 72305 72306 72307 72308 72309 72310 72311 72312 72313 72314 72315 72316 72317 72318 72319 72320 72321 72322 72323 72324 72325 72326 72327 72328 72329 72330 72331 72332 72333 72334 72335 72336 72337 72338 72339 72340 72341 72342 72343 72344 72345 72346 72347 72348 72349 72350 72351 72352 72353 72354 72355 72356 72357 72358 72359 72360 72361 72362 72363 72364 72365 72366 72367 72368 72369 72370 72371 72372 72373 72374 72375 72376 72377 72378 72379 72380 72381 72382 72383 72384 72385 72386 72387 72388 72389 72390 72391 72392 72393 72394 72395 72396 72397 72398 72399 72400 72401 72402 72403 72404 72405 72406 72407 72408 72409 72410 72411 72412 72413 72414 72415 72416 72417 72418 72419 72420 72421 72422 72423 72424 72425 72426 72427 72428 72429 72430 72431 72432 72433 72434 72435 72436 72437 72438 72439 72440 72441 72442 72443 72444 72445 72446 72447 72448 72449 72450 72451 72452 72453 72454 72455 72456 72457 72458 72459 72460 72461 72462 72463 72464 72465 72466 72467 72468 72469 72470 72471 72472 72473 72474 72475 72476 72477 72478 72479 72480 72481 72482 72483 72484 72485 72486 72487 72488 72489 72490 72491 72492 72493 72494 72495 72496 72497 72498 72499 72500 72501 72502 72503 72504 72505 72506 72507 72508 72509 72510 72511 72512 72513 72514 72515 72516 72517 72518 72519 72520 72521 72522 72523 72524 72525 72526 72527 72528 72529 72530 72531 72532 72533 72534 72535 72536 72537 72538 72539 72540 72541 72542 72543 72544 72545 72546 72547 72548 72549 72550 72551 72552 72553 72554 72555 72556 72557 72558 72559 72560 72561 72562 72563 72564 72565 72566 72567 72568 72569 72570 72571 72572 72573 72574 72575 72576 72577 72578 72579 72580 72581 72582 72583 72584 72585 72586 72587 72588 72589 72590 72591 72592 72593 72594 72595 72596 72597 72598 72599 72600 72601 72602 72603 72604 72605 72606 72607 72608 72609 72610 72611 72612 72613 72614 72615 72616 72617 72618 72619 72620 72621 72622 72623 72624 72625 72626 72627 72628 72629 72630 72631 72632 72633 72634 72635 72636 72637 72638 72639 72640 72641 72642 72643 72644 72645 72646 72647 72648 72649 72650 72651 72652 72653 72654 72655 72656 72657 72658 72659 72660 72661 72662 72663 72664 72665 72666 72667 72668 72669 72670 72671 72672 72673 72674 72675 72676 72677 72678 72679 72680 72681 72682 72683 72684 72685 72686 72687 72688 72689 72690 72691 72692 72693 72694 72695 72696 72697 72698 72699 72700 72701 72702 72703 72704 72705 72706 72707 72708 72709 72710 72711 72712 72713 72714 72715 72716 72717 72718 72719 72720 72721 72722 72723 72724 72725 72726 72727 72728 72729 72730 72731 72732 72733 72734 72735 72736 72737 72738 72739 72740 72741 72742 72743 72744 72745 72746 72747 72748 72749 72750 72751 72752 72753 72754 72755 72756 72757 72758 72759 72760 72761 72762 72763 72764 72765 72766 72767 72768 72769 72770 72771 72772 72773 72774 72775 72776 72777 72778 72779 72780 72781 72782 72783 72784 72785 72786 72787 72788 72789 72790 72791 72792 72793 72794 72795 72796 72797 72798 72799 72800 72801 72802 72803 72804 72805 72806 72807 72808 72809 72810 72811 72812 72813 72814 72815 72816 72817 72818 72819 72820 72821 72822 72823 72824 72825 72826 72827 72828 72829 72830 72831 72832 72833 72834 72835 72836 72837 72838 72839 72840 72841 72842 72843 72844 72845 72846 72847 72848 72849 72850 72851 72852 72853 72854 72855 72856 72857 72858 72859 72860 72861 72862 72863 72864 72865 72866 72867 72868 72869 72870 72871 72872 72873 72874 72875 72876 72877 72878 72879 72880 72881 72882 72883 72884 72885 72886 72887 72888 72889 72890 72891 72892 72893 72894 72895 72896 72897 72898 72899 72900 72901 72902 72903 72904 72905 72906 72907 72908 72909 72910 72911 72912 72913 72914 72915 72916 72917 72918 72919 72920 72921 72922 72923 72924 72925 72926 72927 72928 72929 72930 72931 72932 72933 72934 72935 72936 72937 72938 72939 72940 72941 72942 72943 72944 72945 72946 72947 72948 72949 72950 72951 72952 72953 72954 72955 72956 72957 72958 72959 72960 72961 72962 72963 72964 72965 72966 72967 72968 72969 72970 72971 72972 72973 72974 72975 72976 72977 72978 72979 72980 72981 72982 72983 72984 72985 72986 72987 72988 72989 72990 72991 72992 72993 72994 72995 72996 72997 72998 72999 73000 73001 73002 73003 73004 73005 73006 73007 73008 73009 73010 73011 73012 73013 73014 73015 73016 73017 73018 73019 73020 73021 73022 73023 73024 73025 73026 73027 73028 73029 73030 73031 73032 73033 73034 73035 73036 73037 73038 73039 73040 73041 73042 73043 73044 73045 73046 73047 73048 73049 73050 73051 73052 73053 73054 73055 73056 73057 73058 73059 73060 73061 73062 73063 73064 73065 73066 73067 73068 73069 73070 73071 73072 73073 73074 73075 73076 73077 73078 73079 73080 73081 73082 73083 73084 73085 73086 73087 73088 73089 73090 73091 73092 73093 73094 73095 73096 73097 73098 73099 73100 73101 73102 73103 73104 73105 73106 73107 73108 73109 73110 73111 73112 73113 73114 73115 73116 73117 73118 73119 73120 73121 73122 73123 73124 73125 73126 73127 73128 73129 73130 73131 73132 73133 73134 73135 73136 73137 73138 73139 73140 73141 73142 73143 73144 73145 73146 73147 73148 73149 73150 73151 73152 73153 73154 73155 73156 73157 73158 73159 73160 73161 73162 73163 73164 73165 73166 73167 73168 73169 73170 73171 73172 73173 73174 73175 73176 73177 73178 73179 73180 73181 73182 73183 73184 73185 73186 73187 73188 73189 73190 73191 73192 73193 73194 73195 73196 73197 73198 73199 73200 73201 73202 73203 73204 73205 73206 73207 73208 73209 73210 73211 73212 73213 73214 73215 73216 73217 73218 73219 73220 73221 73222 73223 73224 73225 73226 73227 73228 73229 73230 73231 73232 73233 73234 73235 73236 73237 73238 73239 73240 73241 73242 73243 73244 73245 73246 73247 73248 73249 73250 73251 73252 73253 73254 73255 73256 73257 73258 73259 73260 73261 73262 73263 73264 73265 73266 73267 73268 73269 73270 73271 73272 73273 73274 73275 73276 73277 73278 73279 73280 73281 73282 73283 73284 73285 73286 73287 73288 73289 73290 73291 73292 73293 73294 73295 73296 73297 73298 73299 73300 73301 73302 73303 73304 73305 73306 73307 73308 73309 73310 73311 73312 73313 73314 73315 73316 73317 73318 73319 73320 73321 73322 73323 73324 73325 73326 73327 73328 73329 73330 73331 73332 73333 73334 73335 73336 73337 73338 73339 73340 73341 73342 73343 73344 73345 73346 73347 73348 73349 73350 73351 73352 73353 73354 73355 73356 73357 73358 73359 73360 73361 73362 73363 73364 73365 73366 73367 73368 73369 73370 73371 73372 73373 73374 73375 73376 73377 73378 73379 73380 73381 73382 73383 73384 73385 73386 73387 73388 73389 73390 73391 73392 73393 73394 73395 73396 73397 73398 73399 73400 73401 73402 73403 73404 73405 73406 73407 73408 73409 73410 73411 73412 73413 73414 73415 73416 73417 73418 73419 73420 73421 73422 73423 73424 73425 73426 73427 73428 73429 73430 73431 73432 73433 73434 73435 73436 73437 73438 73439 73440 73441 73442 73443 73444 73445 73446 73447 73448 73449 73450 73451 73452 73453 73454 73455 73456 73457 73458 73459 73460 73461 73462 73463 73464 73465 73466 73467 73468 73469 73470 73471 73472 73473 73474 73475 73476 73477 73478 73479 73480 73481 73482 73483 73484 73485 73486 73487 73488 73489 73490 73491 73492 73493 73494 73495 73496 73497 73498 73499 73500 73501 73502 73503 73504 73505 73506 73507 73508 73509 73510 73511 73512 73513 73514 73515 73516 73517 73518 73519 73520 73521 73522 73523 73524 73525 73526 73527 73528 73529 73530 73531 73532 73533 73534 73535 73536 73537 73538 73539 73540 73541 73542 73543 73544 73545 73546 73547 73548 73549 73550 73551 73552 73553 73554 73555 73556 73557 73558 73559 73560 73561 73562 73563 73564 73565 73566 73567 73568 73569 73570 73571 73572 73573 73574 73575 73576 73577 73578 73579 73580 73581 73582 73583 73584 73585 73586 73587 73588 73589 73590 73591 73592 73593 73594 73595 73596 73597 73598 73599 73600 73601 73602 73603 73604 73605 73606 73607 73608 73609 73610 73611 73612 73613 73614 73615 73616 73617 73618 73619 73620 73621 73622 73623 73624 73625 73626 73627 73628 73629 73630 73631 73632 73633 73634 73635 73636 73637 73638 73639 73640 73641 73642 73643 73644 73645 73646 73647 73648 73649 73650 73651 73652 73653 73654 73655 73656 73657 73658 73659 73660 73661 73662 73663 73664 73665 73666 73667 73668 73669 73670 73671 73672 73673 73674 73675 73676 73677 73678 73679 73680 73681 73682 73683 73684 73685 73686 73687 73688 73689 73690 73691 73692 73693 73694 73695 73696 73697 73698 73699 73700 73701 73702 73703 73704 73705 73706 73707 73708 73709 73710 73711 73712 73713 73714 73715 73716 73717 73718 73719 73720 73721 73722 73723 73724 73725 73726 73727 73728 73729 73730 73731 73732 73733 73734 73735 73736 73737 73738 73739 73740 73741 73742 73743 73744 73745 73746 73747 73748 73749 73750 73751 73752 73753 73754 73755 73756 73757 73758 73759 73760 73761 73762 73763 73764 73765 73766 73767 73768 73769 73770 73771 73772 73773 73774 73775 73776 73777 73778 73779 73780 73781 73782 73783 73784 73785 73786 73787 73788 73789 73790 73791 73792 73793 73794 73795 73796 73797 73798 73799 73800 73801 73802 73803 73804 73805 73806 73807 73808 73809 73810 73811 73812 73813 73814 73815 73816 73817 73818 73819 73820 73821 73822 73823 73824 73825 73826 73827 73828 73829 73830 73831 73832 73833 73834 73835 73836 73837 73838 73839 73840 73841 73842 73843 73844 73845 73846 73847 73848 73849 73850 73851 73852 73853 73854 73855 73856 73857 73858 73859 73860 73861 73862 73863 73864 73865 73866 73867 73868 73869 73870 73871 73872 73873 73874 73875 73876 73877 73878 73879 73880 73881 73882 73883 73884 73885 73886 73887 73888 73889 73890 73891 73892 73893 73894 73895 73896 73897 73898 73899 73900 73901 73902 73903 73904 73905 73906 73907 73908 73909 73910 73911 73912 73913 73914 73915 73916 73917 73918 73919 73920 73921 73922 73923 73924 73925 73926 73927 73928 73929 73930 73931 73932 73933 73934 73935 73936 73937 73938 73939 73940 73941 73942 73943 73944 73945 73946 73947 73948 73949 73950 73951 73952 73953 73954 73955 73956 73957 73958 73959 73960 73961 73962 73963 73964 73965 73966 73967 73968 73969 73970 73971 73972 73973 73974 73975 73976 73977 73978 73979 73980 73981 73982 73983 73984 73985 73986 73987 73988 73989 73990 73991 73992 73993 73994 73995 73996 73997 73998 73999 74000 74001 74002 74003 74004 74005 74006 74007 74008 74009 74010 74011 74012 74013 74014 74015 74016 74017 74018 74019 74020 74021 74022 74023 74024 74025 74026 74027 74028 74029 74030 74031 74032 74033 74034 74035 74036 74037 74038 74039 74040 74041 74042 74043 74044 74045 74046 74047 74048 74049 74050 74051 74052 74053 74054 74055 74056 74057 74058 74059 74060 74061 74062 74063 74064 74065 74066 74067 74068 74069 74070 74071 74072 74073 74074 74075 74076 74077 74078 74079 74080 74081 74082 74083 74084 74085 74086 74087 74088 74089 74090 74091 74092 74093 74094 74095 74096 74097 74098 74099 74100 74101 74102 74103 74104 74105 74106 74107 74108 74109 74110 74111 74112 74113 74114 74115 74116 74117 74118 74119 74120 74121 74122 74123 74124 74125 74126 74127 74128 74129 74130 74131 74132 74133 74134 74135 74136 74137 74138 74139 74140 74141 74142 74143 74144 74145 74146 74147 74148 74149 74150 74151 74152 74153 74154 74155 74156 74157 74158 74159 74160 74161 74162 74163 74164 74165 74166 74167 74168 74169 74170 74171 74172 74173 74174 74175 74176 74177 74178 74179 74180 74181 74182 74183 74184 74185 74186 74187 74188 74189 74190 74191 74192 74193 74194 74195 74196 74197 74198 74199 74200 74201 74202 74203 74204 74205 74206 74207 74208 74209 74210 74211 74212 74213 74214 74215 74216 74217 74218 74219 74220 74221 74222 74223 74224 74225 74226 74227 74228 74229 74230 74231 74232 74233 74234 74235 74236 74237 74238 74239 74240 74241 74242 74243 74244 74245 74246 74247 74248 74249 74250 74251 74252 74253 74254 74255 74256 74257 74258 74259 74260 74261 74262 74263 74264 74265 74266 74267 74268 74269 74270 74271 74272 74273 74274 74275 74276 74277 74278 74279 74280 74281 74282 74283 74284 74285 74286 74287 74288 74289 74290 74291 74292 74293 74294 74295 74296 74297 74298 74299 74300 74301 74302 74303 74304 74305 74306 74307 74308 74309 74310 74311 74312 74313 74314 74315 74316 74317 74318 74319 74320 74321 74322 74323 74324 74325 74326 74327 74328 74329 74330 74331 74332 74333 74334 74335 74336 74337 74338 74339 74340 74341 74342 74343 74344 74345 74346 74347 74348 74349 74350 74351 74352 74353 74354 74355 74356 74357 74358 74359 74360 74361 74362 74363 74364 74365 74366 74367 74368 74369 74370 74371 74372 74373 74374 74375 74376 74377 74378 74379 74380 74381 74382 74383 74384 74385 74386 74387 74388 74389 74390 74391 74392 74393 74394 74395 74396 74397 74398 74399 74400 74401 74402 74403 74404 74405 74406 74407 74408 74409 74410 74411 74412 74413 74414 74415 74416 74417 74418 74419 74420 74421 74422 74423 74424 74425 74426 74427 74428 74429 74430 74431 74432 74433 74434 74435 74436 74437 74438 74439 74440 74441 74442 74443 74444 74445 74446 74447 74448 74449 74450 74451 74452 74453 74454 74455 74456 74457 74458 74459 74460 74461 74462 74463 74464 74465 74466 74467 74468 74469 74470 74471 74472 74473 74474 74475 74476 74477 74478 74479 74480 74481 74482 74483 74484 74485 74486 74487 74488 74489 74490 74491 74492 74493 74494 74495 74496 74497 74498 74499 74500 74501 74502 74503 74504 74505 74506 74507 74508 74509 74510 74511 74512 74513 74514 74515 74516 74517 74518 74519 74520 74521 74522 74523 74524 74525 74526 74527 74528 74529 74530 74531 74532 74533 74534 74535 74536 74537 74538 74539 74540 74541 74542 74543 74544 74545 74546 74547 74548 74549 74550 74551 74552 74553 74554 74555 74556 74557 74558 74559 74560 74561 74562 74563 74564 74565 74566 74567 74568 74569 74570 74571 74572 74573 74574 74575 74576 74577 74578 74579 74580 74581 74582 74583 74584 74585 74586 74587 74588 74589 74590 74591 74592 74593 74594 74595 74596 74597 74598 74599 74600 74601 74602 74603 74604 74605 74606 74607 74608 74609 74610 74611 74612 74613 74614 74615 74616 74617 74618 74619 74620 74621 74622 74623 74624 74625 74626 74627 74628 74629 74630 74631 74632 74633 74634 74635 74636 74637 74638 74639 74640 74641 74642 74643 74644 74645 74646 74647 74648 74649 74650 74651 74652 74653 74654 74655 74656 74657 74658 74659 74660 74661 74662 74663 74664 74665 74666 74667 74668 74669 74670 74671 74672 74673 74674 74675 74676 74677 74678 74679 74680 74681 74682 74683 74684 74685 74686 74687 74688 74689 74690 74691 74692 74693 74694 74695 74696 74697 74698 74699 74700 74701 74702 74703 74704 74705 74706 74707 74708 74709 74710 74711 74712 74713 74714 74715 74716 74717 74718 74719 74720 74721 74722 74723 74724 74725 74726 74727 74728 74729 74730 74731 74732 74733 74734 74735 74736 74737 74738 74739 74740 74741 74742 74743 74744 74745 74746 74747 74748 74749 74750 74751 74752 74753 74754 74755 74756 74757 74758 74759 74760 74761 74762 74763 74764 74765 74766 74767 74768 74769 74770 74771 74772 74773 74774 74775 74776 74777 74778 74779 74780 74781 74782 74783 74784 74785 74786 74787 74788 74789 74790 74791 74792 74793 74794 74795 74796 74797 74798 74799 74800 74801 74802 74803 74804 74805 74806 74807 74808 74809 74810 74811 74812 74813 74814 74815 74816 74817 74818 74819 74820 74821 74822 74823 74824 74825 74826 74827 74828 74829 74830 74831 74832 74833 74834 74835 74836 74837 74838 74839 74840 74841 74842 74843 74844 74845 74846 74847 74848 74849 74850 74851 74852 74853 74854 74855 74856 74857 74858 74859 74860 74861 74862 74863 74864 74865 74866 74867 74868 74869 74870 74871 74872 74873 74874 74875 74876 74877 74878 74879 74880 74881 74882 74883 74884 74885 74886 74887 74888 74889 74890 74891 74892 74893 74894 74895 74896 74897 74898 74899 74900 74901 74902 74903 74904 74905 74906 74907 74908 74909 74910 74911 74912 74913 74914 74915 74916 74917 74918 74919 74920 74921 74922 74923 74924 74925 74926 74927 74928 74929 74930 74931 74932 74933 74934 74935 74936 74937 74938 74939 74940 74941 74942 74943 74944 74945 74946 74947 74948 74949 74950 74951 74952 74953 74954 74955 74956 74957 74958 74959 74960 74961 74962 74963 74964 74965 74966 74967 74968 74969 74970 74971 74972 74973 74974 74975 74976 74977 74978 74979 74980 74981 74982 74983 74984 74985 74986 74987 74988 74989 74990 74991 74992 74993 74994 74995 74996 74997 74998 74999 75000 75001 75002 75003 75004 75005 75006 75007 75008 75009 75010 75011 75012 75013 75014 75015 75016 75017 75018 75019 75020 75021 75022 75023 75024 75025 75026 75027 75028 75029 75030 75031 75032 75033 75034 75035 75036 75037 75038 75039 75040 75041 75042 75043 75044 75045 75046 75047 75048 75049 75050 75051 75052 75053 75054 75055 75056 75057 75058 75059 75060 75061 75062 75063 75064 75065 75066 75067 75068 75069 75070 75071 75072 75073 75074 75075 75076 75077 75078 75079 75080 75081 75082 75083 75084 75085 75086 75087 75088 75089 75090 75091 75092 75093 75094 75095 75096 75097 75098 75099 75100 75101 75102 75103 75104 75105 75106 75107 75108 75109 75110 75111 75112 75113 75114 75115 75116 75117 75118 75119 75120 75121 75122 75123 75124 75125 75126 75127 75128 75129 75130 75131 75132 75133 75134 75135 75136 75137 75138 75139 75140 75141 75142 75143 75144 75145 75146 75147 75148 75149 75150 75151 75152 75153 75154 75155 75156 75157 75158 75159 75160 75161 75162 75163 75164 75165 75166 75167 75168 75169 75170 75171 75172 75173 75174 75175 75176 75177 75178 75179 75180 75181 75182 75183 75184 75185 75186 75187 75188 75189 75190 75191 75192 75193 75194 75195 75196 75197 75198 75199 75200 75201 75202 75203 75204 75205 75206 75207 75208 75209 75210 75211 75212 75213 75214 75215 75216 75217 75218 75219 75220 75221 75222 75223 75224 75225 75226 75227 75228 75229 75230 75231 75232 75233 75234 75235 75236 75237 75238 75239 75240 75241 75242 75243 75244 75245 75246 75247 75248 75249 75250 75251 75252 75253 75254 75255 75256 75257 75258 75259 75260 75261 75262 75263 75264 75265 75266 75267 75268 75269 75270 75271 75272 75273 75274 75275 75276 75277 75278 75279 75280 75281 75282 75283 75284 75285 75286 75287 75288 75289 75290 75291 75292 75293 75294 75295 75296 75297 75298 75299 75300 75301 75302 75303 75304 75305 75306 75307 75308 75309 75310 75311 75312 75313 75314 75315 75316 75317 75318 75319 75320 75321 75322 75323 75324 75325 75326 75327 75328 75329 75330 75331 75332 75333 75334 75335 75336 75337 75338 75339 75340 75341 75342 75343 75344 75345 75346 75347 75348 75349 75350 75351 75352 75353 75354 75355 75356 75357 75358 75359 75360 75361 75362 75363 75364 75365 75366 75367 75368 75369 75370 75371 75372 75373 75374 75375 75376 75377 75378 75379 75380 75381 75382 75383 75384 75385 75386 75387 75388 75389 75390 75391 75392 75393 75394 75395 75396 75397 75398 75399 75400 75401 75402 75403 75404 75405 75406 75407 75408 75409 75410 75411 75412 75413 75414 75415 75416 75417 75418 75419 75420 75421 75422 75423 75424 75425 75426 75427 75428 75429 75430 75431 75432 75433 75434 75435 75436 75437 75438 75439 75440 75441 75442 75443 75444 75445 75446 75447 75448 75449 75450 75451 75452 75453 75454 75455 75456 75457 75458 75459 75460 75461 75462 75463 75464 75465 75466 75467 75468 75469 75470 75471 75472 75473 75474 75475 75476 75477 75478 75479 75480 75481 75482 75483 75484 75485 75486 75487 75488 75489 75490 75491 75492 75493 75494 75495 75496 75497 75498 75499 75500 75501 75502 75503 75504 75505 75506 75507 75508 75509 75510 75511 75512 75513 75514 75515 75516 75517 75518 75519 75520 75521 75522 75523 75524 75525 75526 75527 75528 75529 75530 75531 75532 75533 75534 75535 75536 75537 75538 75539 75540 75541 75542 75543 75544 75545 75546 75547 75548 75549 75550 75551 75552 75553 75554 75555 75556 75557 75558 75559 75560 75561 75562 75563 75564 75565 75566 75567 75568 75569 75570 75571 75572 75573 75574 75575 75576 75577 75578 75579 75580 75581 75582 75583 75584 75585 75586 75587 75588 75589 75590 75591 75592 75593 75594 75595 75596 75597 75598 75599 75600 75601 75602 75603 75604 75605 75606 75607 75608 75609 75610 75611 75612 75613 75614 75615 75616 75617 75618 75619 75620 75621 75622 75623 75624 75625 75626 75627 75628 75629 75630 75631 75632 75633 75634 75635 75636 75637 75638 75639 75640 75641 75642 75643 75644 75645 75646 75647 75648 75649 75650 75651 75652 75653 75654 75655 75656 75657 75658 75659 75660 75661 75662 75663 75664 75665 75666 75667 75668 75669 75670 75671 75672 75673 75674 75675 75676 75677 75678 75679 75680 75681 75682 75683 75684 75685 75686 75687 75688 75689 75690 75691 75692 75693 75694 75695 75696 75697 75698 75699 75700 75701 75702 75703 75704 75705 75706 75707 75708 75709 75710 75711 75712 75713 75714 75715 75716 75717 75718 75719 75720 75721 75722 75723 75724 75725 75726 75727 75728 75729 75730 75731 75732 75733 75734 75735 75736 75737 75738 75739 75740 75741 75742 75743 75744 75745 75746 75747 75748 75749 75750 75751 75752 75753 75754 75755 75756 75757 75758 75759 75760 75761 75762 75763 75764 75765 75766 75767 75768 75769 75770 75771 75772 75773 75774 75775 75776 75777 75778 75779 75780 75781 75782 75783 75784 75785 75786 75787 75788 75789 75790 75791 75792 75793 75794 75795 75796 75797 75798 75799 75800 75801 75802 75803 75804 75805 75806 75807 75808 75809 75810 75811 75812 75813 75814 75815 75816 75817 75818 75819 75820 75821 75822 75823 75824 75825 75826 75827 75828 75829 75830 75831 75832 75833 75834 75835 75836 75837 75838 75839 75840 75841 75842 75843 75844 75845 75846 75847 75848 75849 75850 75851 75852 75853 75854 75855 75856 75857 75858 75859 75860 75861 75862 75863 75864 75865 75866 75867 75868 75869 75870 75871 75872 75873 75874 75875 75876 75877 75878 75879 75880 75881 75882 75883 75884 75885 75886 75887 75888 75889 75890 75891 75892 75893 75894 75895 75896 75897 75898 75899 75900 75901 75902 75903 75904 75905 75906 75907 75908 75909 75910 75911 75912 75913 75914 75915 75916 75917 75918 75919 75920 75921 75922 75923 75924 75925 75926 75927 75928 75929 75930 75931 75932 75933 75934 75935 75936 75937 75938 75939 75940 75941 75942 75943 75944 75945 75946 75947 75948 75949 75950 75951 75952 75953 75954 75955 75956 75957 75958 75959 75960 75961 75962 75963 75964 75965 75966 75967 75968 75969 75970 75971 75972 75973 75974 75975 75976 75977 75978 75979 75980 75981 75982 75983 75984 75985 75986 75987 75988 75989 75990 75991 75992 75993 75994 75995 75996 75997 75998 75999 76000 76001 76002 76003 76004 76005 76006 76007 76008 76009 76010 76011 76012 76013 76014 76015 76016 76017 76018 76019 76020 76021 76022 76023 76024 76025 76026 76027 76028 76029 76030 76031 76032 76033 76034 76035 76036 76037 76038 76039 76040 76041 76042 76043 76044 76045 76046 76047 76048 76049 76050 76051 76052 76053 76054 76055 76056 76057 76058 76059 76060 76061 76062 76063 76064 76065 76066 76067 76068 76069 76070 76071 76072 76073 76074 76075 76076 76077 76078 76079 76080 76081 76082 76083 76084 76085 76086 76087 76088 76089 76090 76091 76092 76093 76094 76095 76096 76097 76098 76099 76100 76101 76102 76103 76104 76105 76106 76107 76108 76109 76110 76111 76112 76113 76114 76115 76116 76117 76118 76119 76120 76121 76122 76123 76124 76125 76126 76127 76128 76129 76130 76131 76132 76133 76134 76135 76136 76137 76138 76139 76140 76141 76142 76143 76144 76145 76146 76147 76148 76149 76150 76151 76152 76153 76154 76155 76156 76157 76158 76159 76160 76161 76162 76163 76164 76165 76166 76167 76168 76169 76170 76171 76172 76173 76174 76175 76176 76177 76178 76179 76180 76181 76182 76183 76184 76185 76186 76187 76188 76189 76190 76191 76192 76193 76194 76195 76196 76197 76198 76199 76200 76201 76202 76203 76204 76205 76206 76207 76208 76209 76210 76211 76212 76213 76214 76215 76216 76217 76218 76219 76220 76221 76222 76223 76224 76225 76226 76227 76228 76229 76230 76231 76232 76233 76234 76235 76236 76237 76238 76239 76240 76241 76242 76243 76244 76245 76246 76247 76248 76249 76250 76251 76252 76253 76254 76255 76256 76257 76258 76259 76260 76261 76262 76263 76264 76265 76266 76267 76268 76269 76270 76271 76272 76273 76274 76275 76276 76277 76278 76279 76280 76281 76282 76283 76284 76285 76286 76287 76288 76289 76290 76291 76292 76293 76294 76295 76296 76297 76298 76299 76300 76301 76302 76303 76304 76305 76306 76307 76308 76309 76310 76311 76312 76313 76314 76315 76316 76317 76318 76319 76320 76321 76322 76323 76324 76325 76326 76327 76328 76329 76330 76331 76332 76333 76334 76335 76336 76337 76338 76339 76340 76341 76342 76343 76344 76345 76346 76347 76348 76349 76350 76351 76352 76353 76354 76355 76356 76357 76358 76359 76360 76361 76362 76363 76364 76365 76366 76367 76368 76369 76370 76371 76372 76373 76374 76375 76376 76377 76378 76379 76380 76381 76382 76383 76384 76385 76386 76387 76388 76389 76390 76391 76392 76393 76394 76395 76396 76397 76398 76399 76400 76401 76402 76403 76404 76405 76406 76407 76408 76409 76410 76411 76412 76413 76414 76415 76416 76417 76418 76419 76420 76421 76422 76423 76424 76425 76426 76427 76428 76429 76430 76431 76432 76433 76434 76435 76436 76437 76438 76439 76440 76441 76442 76443 76444 76445 76446 76447 76448 76449 76450 76451 76452 76453 76454 76455 76456 76457 76458 76459 76460 76461 76462 76463 76464 76465 76466 76467 76468 76469 76470 76471 76472 76473 76474 76475 76476 76477 76478 76479 76480 76481 76482 76483 76484 76485 76486 76487 76488 76489 76490 76491 76492 76493 76494 76495 76496 76497 76498 76499 76500 76501 76502 76503 76504 76505 76506 76507 76508 76509 76510 76511 76512 76513 76514 76515 76516 76517 76518 76519 76520 76521 76522 76523 76524 76525 76526 76527 76528 76529 76530 76531 76532 76533 76534 76535 76536 76537 76538 76539 76540 76541 76542 76543 76544 76545 76546 76547 76548 76549 76550 76551 76552 76553 76554 76555 76556 76557 76558 76559 76560 76561 76562 76563 76564 76565 76566 76567 76568 76569 76570 76571 76572 76573 76574 76575 76576 76577 76578 76579 76580 76581 76582 76583 76584 76585 76586 76587 76588 76589 76590 76591 76592 76593 76594 76595 76596 76597 76598 76599 76600 76601 76602 76603 76604 76605 76606 76607 76608 76609 76610 76611 76612 76613 76614 76615 76616 76617 76618 76619 76620 76621 76622 76623 76624 76625 76626 76627 76628 76629 76630 76631 76632 76633 76634 76635 76636 76637 76638 76639 76640 76641 76642 76643 76644 76645 76646 76647 76648 76649 76650 76651 76652 76653 76654 76655 76656 76657 76658 76659 76660 76661 76662 76663 76664 76665 76666 76667 76668 76669 76670 76671 76672 76673 76674 76675 76676 76677 76678 76679 76680 76681 76682 76683 76684 76685 76686 76687 76688 76689 76690 76691 76692 76693 76694 76695 76696 76697 76698 76699 76700 76701 76702 76703 76704 76705 76706 76707 76708 76709 76710 76711 76712 76713 76714 76715 76716 76717 76718 76719 76720 76721 76722 76723 76724 76725 76726 76727 76728 76729 76730 76731 76732 76733 76734 76735 76736 76737 76738 76739 76740 76741 76742 76743 76744 76745 76746 76747 76748 76749 76750 76751 76752 76753 76754 76755 76756 76757 76758 76759 76760 76761 76762 76763 76764 76765 76766 76767 76768 76769 76770 76771 76772 76773 76774 76775 76776 76777 76778 76779 76780 76781 76782 76783 76784 76785 76786 76787 76788 76789 76790 76791 76792 76793 76794 76795 76796 76797 76798 76799 76800 76801 76802 76803 76804 76805 76806 76807 76808 76809 76810 76811 76812 76813 76814 76815 76816 76817 76818 76819 76820 76821 76822 76823 76824 76825 76826 76827 76828 76829 76830 76831 76832 76833 76834 76835 76836 76837 76838 76839 76840 76841 76842 76843 76844 76845 76846 76847 76848 76849 76850 76851 76852 76853 76854 76855 76856 76857 76858 76859 76860 76861 76862 76863 76864 76865 76866 76867 76868 76869 76870 76871 76872 76873 76874 76875 76876 76877 76878 76879 76880 76881 76882 76883 76884 76885 76886 76887 76888 76889 76890 76891 76892 76893 76894 76895 76896 76897 76898 76899 76900 76901 76902 76903 76904 76905 76906 76907 76908 76909 76910 76911 76912 76913 76914 76915 76916 76917 76918 76919 76920 76921 76922 76923 76924 76925 76926 76927 76928 76929 76930 76931 76932 76933 76934 76935 76936 76937 76938 76939 76940 76941 76942 76943 76944 76945 76946 76947 76948 76949 76950 76951 76952 76953 76954 76955 76956 76957 76958 76959 76960 76961 76962 76963 76964 76965 76966 76967 76968 76969 76970 76971 76972 76973 76974 76975 76976 76977 76978 76979 76980 76981 76982 76983 76984 76985 76986 76987 76988 76989 76990 76991 76992 76993 76994 76995 76996 76997 76998 76999 77000 77001 77002 77003 77004 77005 77006 77007 77008 77009 77010 77011 77012 77013 77014 77015 77016 77017 77018 77019 77020 77021 77022 77023 77024 77025 77026 77027 77028 77029 77030 77031 77032 77033 77034 77035 77036 77037 77038 77039 77040 77041 77042 77043 77044 77045 77046 77047 77048 77049 77050 77051 77052 77053 77054 77055 77056 77057 77058 77059 77060 77061 77062 77063 77064 77065 77066 77067 77068 77069 77070 77071 77072 77073 77074 77075 77076 77077 77078 77079 77080 77081 77082 77083 77084 77085 77086 77087 77088 77089 77090 77091 77092 77093 77094 77095 77096 77097 77098 77099 77100 77101 77102 77103 77104 77105 77106 77107 77108 77109 77110 77111 77112 77113 77114 77115 77116 77117 77118 77119 77120 77121 77122 77123 77124 77125 77126 77127 77128 77129 77130 77131 77132 77133 77134 77135 77136 77137 77138 77139 77140 77141 77142 77143 77144 77145 77146 77147 77148 77149 77150 77151 77152 77153 77154 77155 77156 77157 77158 77159 77160 77161 77162 77163 77164 77165 77166 77167 77168 77169 77170 77171 77172 77173 77174 77175 77176 77177 77178 77179 77180 77181 77182 77183 77184 77185 77186 77187 77188 77189 77190 77191 77192 77193 77194 77195 77196 77197 77198 77199 77200 77201 77202 77203 77204 77205 77206 77207 77208 77209 77210 77211 77212 77213 77214 77215 77216 77217 77218 77219 77220 77221 77222 77223 77224 77225 77226 77227 77228 77229 77230 77231 77232 77233 77234 77235 77236 77237 77238 77239 77240 77241 77242 77243 77244 77245 77246 77247 77248 77249 77250 77251 77252 77253 77254 77255 77256 77257 77258 77259 77260 77261 77262 77263 77264 77265 77266 77267 77268 77269 77270 77271 77272 77273 77274 77275 77276 77277 77278 77279 77280 77281 77282 77283 77284 77285 77286 77287 77288 77289 77290 77291 77292 77293 77294 77295 77296 77297 77298 77299 77300 77301 77302 77303 77304 77305 77306 77307 77308 77309 77310 77311 77312 77313 77314 77315 77316 77317 77318 77319 77320 77321 77322 77323 77324 77325 77326 77327 77328 77329 77330 77331 77332 77333 77334 77335 77336 77337 77338 77339 77340 77341 77342 77343 77344 77345 77346 77347 77348 77349 77350 77351 77352 77353 77354 77355 77356 77357 77358 77359 77360 77361 77362 77363 77364 77365 77366 77367 77368 77369 77370 77371 77372 77373 77374 77375 77376 77377 77378 77379 77380 77381 77382 77383 77384 77385 77386 77387 77388 77389 77390 77391 77392 77393 77394 77395 77396 77397 77398 77399 77400 77401 77402 77403 77404 77405 77406 77407 77408 77409 77410 77411 77412 77413 77414 77415 77416 77417 77418 77419 77420 77421 77422 77423 77424 77425 77426 77427 77428 77429 77430 77431 77432 77433 77434 77435 77436 77437 77438 77439 77440 77441 77442 77443 77444 77445 77446 77447 77448 77449 77450 77451 77452 77453 77454 77455 77456 77457 77458 77459 77460 77461 77462 77463 77464 77465 77466 77467 77468 77469 77470 77471 77472 77473 77474 77475 77476 77477 77478 77479 77480 77481 77482 77483 77484 77485 77486 77487 77488 77489 77490 77491 77492 77493 77494 77495 77496 77497 77498 77499 77500 77501 77502 77503 77504 77505 77506 77507 77508 77509 77510 77511 77512 77513 77514 77515 77516 77517 77518 77519 77520 77521 77522 77523 77524 77525 77526 77527 77528 77529 77530 77531 77532 77533 77534 77535 77536 77537 77538 77539 77540 77541 77542 77543 77544 77545 77546 77547 77548 77549 77550 77551 77552 77553 77554 77555 77556 77557 77558 77559 77560 77561 77562 77563 77564 77565 77566 77567 77568 77569 77570 77571 77572 77573 77574 77575 77576 77577 77578 77579 77580 77581 77582 77583 77584 77585 77586 77587 77588 77589 77590 77591 77592 77593 77594 77595 77596 77597 77598 77599 77600 77601 77602 77603 77604 77605 77606 77607 77608 77609 77610 77611 77612 77613 77614 77615 77616 77617 77618 77619 77620 77621 77622 77623 77624 77625 77626 77627 77628 77629 77630 77631 77632 77633 77634 77635 77636 77637 77638 77639 77640 77641 77642 77643 77644 77645 77646 77647 77648 77649 77650 77651 77652 77653 77654 77655 77656 77657 77658 77659 77660 77661 77662 77663 77664 77665 77666 77667 77668 77669 77670 77671 77672 77673 77674 77675 77676 77677 77678 77679 77680 77681 77682 77683 77684 77685 77686 77687 77688 77689 77690 77691 77692 77693 77694 77695 77696 77697 77698 77699 77700 77701 77702 77703 77704 77705 77706 77707 77708 77709 77710 77711 77712 77713 77714 77715 77716 77717 77718 77719 77720 77721 77722 77723 77724 77725 77726 77727 77728 77729 77730 77731 77732 77733 77734 77735 77736 77737 77738 77739 77740 77741 77742 77743 77744 77745 77746 77747 77748 77749 77750 77751 77752 77753 77754 77755 77756 77757 77758 77759 77760 77761 77762 77763 77764 77765 77766 77767 77768 77769 77770 77771 77772 77773 77774 77775 77776 77777 77778 77779 77780 77781 77782 77783 77784 77785 77786 77787 77788 77789 77790 77791 77792 77793 77794 77795 77796 77797 77798 77799 77800 77801 77802 77803 77804 77805 77806 77807 77808 77809 77810 77811 77812 77813 77814 77815 77816 77817 77818 77819 77820 77821 77822 77823 77824 77825 77826 77827 77828 77829 77830 77831 77832 77833 77834 77835 77836 77837 77838 77839 77840 77841 77842 77843 77844 77845 77846 77847 77848 77849 77850 77851 77852 77853 77854 77855 77856 77857 77858 77859 77860 77861 77862 77863 77864 77865 77866 77867 77868 77869 77870 77871 77872 77873 77874 77875 77876 77877 77878 77879 77880 77881 77882 77883 77884 77885 77886 77887 77888 77889 77890 77891 77892 77893 77894 77895 77896 77897 77898 77899 77900 77901 77902 77903 77904 77905 77906 77907 77908 77909 77910 77911 77912 77913 77914 77915 77916 77917 77918 77919 77920 77921 77922 77923 77924 77925 77926 77927 77928 77929 77930 77931 77932 77933 77934 77935 77936 77937 77938 77939 77940 77941 77942 77943 77944 77945 77946 77947 77948 77949 77950 77951 77952 77953 77954 77955 77956 77957 77958 77959 77960 77961 77962 77963 77964 77965 77966 77967 77968 77969 77970 77971 77972 77973 77974 77975 77976 77977 77978 77979 77980 77981 77982 77983 77984 77985 77986 77987 77988 77989 77990 77991 77992 77993 77994 77995 77996 77997 77998 77999 78000 78001 78002 78003 78004 78005 78006 78007 78008 78009 78010 78011 78012 78013 78014 78015 78016 78017 78018 78019 78020 78021 78022 78023 78024 78025 78026 78027 78028 78029 78030 78031 78032 78033 78034 78035 78036 78037 78038 78039 78040 78041 78042 78043 78044 78045 78046 78047 78048 78049 78050 78051 78052 78053 78054 78055 78056 78057 78058 78059 78060 78061 78062 78063 78064 78065 78066 78067 78068 78069 78070 78071 78072 78073 78074 78075 78076 78077 78078 78079 78080 78081 78082 78083 78084 78085 78086 78087 78088 78089 78090 78091 78092 78093 78094 78095 78096 78097 78098 78099 78100 78101 78102 78103 78104 78105 78106 78107 78108 78109 78110 78111 78112 78113 78114 78115 78116 78117 78118 78119 78120 78121 78122 78123 78124 78125 78126 78127 78128 78129 78130 78131 78132 78133 78134 78135 78136 78137 78138 78139 78140 78141 78142 78143 78144 78145 78146 78147 78148 78149 78150 78151 78152 78153 78154 78155 78156 78157 78158 78159 78160 78161 78162 78163 78164 78165 78166 78167 78168 78169 78170 78171 78172 78173 78174 78175 78176 78177 78178 78179 78180 78181 78182 78183 78184 78185 78186 78187 78188 78189 78190 78191 78192 78193 78194 78195 78196 78197 78198 78199 78200 78201 78202 78203 78204 78205 78206 78207 78208 78209 78210 78211 78212 78213 78214 78215 78216 78217 78218 78219 78220 78221 78222 78223 78224 78225 78226 78227 78228 78229 78230 78231 78232 78233 78234 78235 78236 78237 78238 78239 78240 78241 78242 78243 78244 78245 78246 78247 78248 78249 78250 78251 78252 78253 78254 78255 78256 78257 78258 78259 78260 78261 78262 78263 78264 78265 78266 78267 78268 78269 78270 78271 78272 78273 78274 78275 78276 78277 78278 78279 78280 78281 78282 78283 78284 78285 78286 78287 78288 78289 78290 78291 78292 78293 78294 78295 78296 78297 78298 78299 78300 78301 78302 78303 78304 78305 78306 78307 78308 78309 78310 78311 78312 78313 78314 78315 78316 78317 78318 78319 78320 78321 78322 78323 78324 78325 78326 78327 78328 78329 78330 78331 78332 78333 78334 78335 78336 78337 78338 78339 78340 78341 78342 78343 78344 78345 78346 78347 78348 78349 78350 78351 78352 78353 78354 78355 78356 78357 78358 78359 78360 78361 78362 78363 78364 78365 78366 78367 78368 78369 78370 78371 78372 78373 78374 78375 78376 78377 78378 78379 78380 78381 78382 78383 78384 78385 78386 78387 78388 78389 78390 78391 78392 78393 78394 78395 78396 78397 78398 78399 78400 78401 78402 78403 78404 78405 78406 78407 78408 78409 78410 78411 78412 78413 78414 78415 78416 78417 78418 78419 78420 78421 78422 78423 78424 78425 78426 78427 78428 78429 78430 78431 78432 78433 78434 78435 78436 78437 78438 78439 78440 78441 78442 78443 78444 78445 78446 78447 78448 78449 78450 78451 78452 78453 78454 78455 78456 78457 78458 78459 78460 78461 78462 78463 78464 78465 78466 78467 78468 78469 78470 78471 78472 78473 78474 78475 78476 78477 78478 78479 78480 78481 78482 78483 78484 78485 78486 78487 78488 78489 78490 78491 78492 78493 78494 78495 78496 78497 78498 78499 78500 78501 78502 78503 78504 78505 78506 78507 78508 78509 78510 78511 78512 78513 78514 78515 78516 78517 78518 78519 78520 78521 78522 78523 78524 78525 78526 78527 78528 78529 78530 78531 78532 78533 78534 78535 78536 78537 78538 78539 78540 78541 78542 78543 78544 78545 78546 78547 78548 78549 78550 78551 78552 78553 78554 78555 78556 78557 78558 78559 78560 78561 78562 78563 78564 78565 78566 78567 78568 78569 78570 78571 78572 78573 78574 78575 78576 78577 78578 78579 78580 78581 78582 78583 78584 78585 78586 78587 78588 78589 78590 78591 78592 78593 78594 78595 78596 78597 78598 78599 78600 78601 78602 78603 78604 78605 78606 78607 78608 78609 78610 78611 78612 78613 78614 78615 78616 78617 78618 78619 78620 78621 78622 78623 78624 78625 78626 78627 78628 78629 78630 78631 78632 78633 78634 78635 78636 78637 78638 78639 78640 78641 78642 78643 78644 78645 78646 78647 78648 78649 78650 78651 78652 78653 78654 78655 78656 78657 78658 78659 78660 78661 78662 78663 78664 78665 78666 78667 78668 78669 78670 78671 78672 78673 78674 78675 78676 78677 78678 78679 78680 78681 78682 78683 78684 78685 78686 78687 78688 78689 78690 78691 78692 78693 78694 78695 78696 78697 78698 78699 78700 78701 78702 78703 78704 78705 78706 78707 78708 78709 78710 78711 78712 78713 78714 78715 78716 78717 78718 78719 78720 78721 78722 78723 78724 78725 78726 78727 78728 78729 78730 78731 78732 78733 78734 78735 78736 78737 78738 78739 78740 78741 78742 78743 78744 78745 78746 78747 78748 78749 78750 78751 78752 78753 78754 78755 78756 78757 78758 78759 78760 78761 78762 78763 78764 78765 78766 78767 78768 78769 78770 78771 78772 78773 78774 78775 78776 78777 78778 78779 78780 78781 78782 78783 78784 78785 78786 78787 78788 78789 78790 78791 78792 78793 78794 78795 78796 78797 78798 78799 78800 78801 78802 78803 78804 78805 78806 78807 78808 78809 78810 78811 78812 78813 78814 78815 78816 78817 78818 78819 78820 78821 78822 78823 78824 78825 78826 78827 78828 78829 78830 78831 78832 78833 78834 78835 78836 78837 78838 78839 78840 78841 78842 78843 78844 78845 78846 78847 78848 78849 78850 78851 78852 78853 78854 78855 78856 78857 78858 78859 78860 78861 78862 78863 78864 78865 78866 78867 78868 78869 78870 78871 78872 78873 78874 78875 78876 78877 78878 78879 78880 78881 78882 78883 78884 78885 78886 78887 78888 78889 78890 78891 78892 78893 78894 78895 78896 78897 78898 78899 78900 78901 78902 78903 78904 78905 78906 78907 78908 78909 78910 78911 78912 78913 78914 78915 78916 78917 78918 78919 78920 78921 78922 78923 78924 78925 78926 78927 78928 78929 78930 78931 78932 78933 78934 78935 78936 78937 78938 78939 78940 78941 78942 78943 78944 78945 78946 78947 78948 78949 78950 78951 78952 78953 78954 78955 78956 78957 78958 78959 78960 78961 78962 78963 78964 78965 78966 78967 78968 78969 78970 78971 78972 78973 78974 78975 78976 78977 78978 78979 78980 78981 78982 78983 78984 78985 78986 78987 78988 78989 78990 78991 78992 78993 78994 78995 78996 78997 78998 78999 79000 79001 79002 79003 79004 79005 79006 79007 79008 79009 79010 79011 79012 79013 79014 79015 79016 79017 79018 79019 79020 79021 79022 79023 79024 79025 79026 79027 79028 79029 79030 79031 79032 79033 79034 79035 79036 79037 79038 79039 79040 79041 79042 79043 79044 79045 79046 79047 79048 79049 79050 79051 79052 79053 79054 79055 79056 79057 79058 79059 79060 79061 79062 79063 79064 79065 79066 79067 79068 79069 79070 79071 79072 79073 79074 79075 79076 79077 79078 79079 79080 79081 79082 79083 79084 79085 79086 79087 79088 79089 79090 79091 79092 79093 79094 79095 79096 79097 79098 79099 79100 79101 79102 79103 79104 79105 79106 79107 79108 79109 79110 79111 79112 79113 79114 79115 79116 79117 79118 79119 79120 79121 79122 79123 79124 79125 79126 79127 79128 79129 79130 79131 79132 79133 79134 79135 79136 79137 79138 79139 79140 79141 79142 79143 79144 79145 79146 79147 79148 79149 79150 79151 79152 79153 79154 79155 79156 79157 79158 79159 79160 79161 79162 79163 79164 79165 79166 79167 79168 79169 79170 79171 79172 79173 79174 79175 79176 79177 79178 79179 79180 79181 79182 79183 79184 79185 79186 79187 79188 79189 79190 79191 79192 79193 79194 79195 79196 79197 79198 79199 79200 79201 79202 79203 79204 79205 79206 79207 79208 79209 79210 79211 79212 79213 79214 79215 79216 79217 79218 79219 79220 79221 79222 79223 79224 79225 79226 79227 79228 79229 79230 79231 79232 79233 79234 79235 79236 79237 79238 79239 79240 79241 79242 79243 79244 79245 79246 79247 79248 79249 79250 79251 79252 79253 79254 79255 79256 79257 79258 79259 79260 79261 79262 79263 79264 79265 79266 79267 79268 79269 79270 79271 79272 79273 79274 79275 79276 79277 79278 79279 79280 79281 79282 79283 79284 79285 79286 79287 79288 79289 79290 79291 79292 79293 79294 79295 79296 79297 79298 79299 79300 79301 79302 79303 79304 79305 79306 79307 79308 79309 79310 79311 79312 79313 79314 79315 79316 79317 79318 79319 79320 79321 79322 79323 79324 79325 79326 79327 79328 79329 79330 79331 79332 79333 79334 79335 79336 79337 79338 79339 79340 79341 79342 79343 79344 79345 79346 79347 79348 79349 79350 79351 79352 79353 79354 79355 79356 79357 79358 79359 79360 79361 79362 79363 79364 79365 79366 79367 79368 79369 79370 79371 79372 79373 79374 79375 79376 79377 79378 79379 79380 79381 79382 79383 79384 79385 79386 79387 79388 79389 79390 79391 79392 79393 79394 79395 79396 79397 79398 79399 79400 79401 79402 79403 79404 79405 79406 79407 79408 79409 79410 79411 79412 79413 79414 79415 79416 79417 79418 79419 79420 79421 79422 79423 79424 79425 79426 79427 79428 79429 79430 79431 79432 79433 79434 79435 79436 79437 79438 79439 79440 79441 79442 79443 79444 79445 79446 79447 79448 79449 79450 79451 79452 79453 79454 79455 79456 79457 79458 79459 79460 79461 79462 79463 79464 79465 79466 79467 79468 79469 79470 79471 79472 79473 79474 79475 79476 79477 79478 79479 79480 79481 79482 79483 79484 79485 79486 79487 79488 79489 79490 79491 79492 79493 79494 79495 79496 79497 79498 79499 79500 79501 79502 79503 79504 79505 79506 79507 79508 79509 79510 79511 79512 79513 79514 79515 79516 79517 79518 79519 79520 79521 79522 79523 79524 79525 79526 79527 79528 79529 79530 79531 79532 79533 79534 79535 79536 79537 79538 79539 79540 79541 79542 79543 79544 79545 79546 79547 79548 79549 79550 79551 79552 79553 79554 79555 79556 79557 79558 79559 79560 79561 79562 79563 79564 79565 79566 79567 79568 79569 79570 79571 79572 79573 79574 79575 79576 79577 79578 79579 79580 79581 79582 79583 79584 79585 79586 79587 79588 79589 79590 79591 79592 79593 79594 79595 79596 79597 79598 79599 79600 79601 79602 79603 79604 79605 79606 79607 79608 79609 79610 79611 79612 79613 79614 79615 79616 79617 79618 79619 79620 79621 79622 79623 79624 79625 79626 79627 79628 79629 79630 79631 79632 79633 79634 79635 79636 79637 79638 79639 79640 79641 79642 79643 79644 79645 79646 79647 79648 79649 79650 79651 79652 79653 79654 79655 79656 79657 79658 79659 79660 79661 79662 79663 79664 79665 79666 79667 79668 79669 79670 79671 79672 79673 79674 79675 79676 79677 79678 79679 79680 79681 79682 79683 79684 79685 79686 79687 79688 79689 79690 79691 79692 79693 79694 79695 79696 79697 79698 79699 79700 79701 79702 79703 79704 79705 79706 79707 79708 79709 79710 79711 79712 79713 79714 79715 79716 79717 79718 79719 79720 79721 79722 79723 79724 79725 79726 79727 79728 79729 79730 79731 79732 79733 79734 79735 79736 79737 79738 79739 79740 79741 79742 79743 79744 79745 79746 79747 79748 79749 79750 79751 79752 79753 79754 79755 79756 79757 79758 79759 79760 79761 79762 79763 79764 79765 79766 79767 79768 79769 79770 79771 79772 79773 79774 79775 79776 79777 79778 79779 79780 79781 79782 79783 79784 79785 79786 79787 79788 79789 79790 79791 79792 79793 79794 79795 79796 79797 79798 79799 79800 79801 79802 79803 79804 79805 79806 79807 79808 79809 79810 79811 79812 79813 79814 79815 79816 79817 79818 79819 79820 79821 79822 79823 79824 79825 79826 79827 79828 79829 79830 79831 79832 79833 79834 79835 79836 79837 79838 79839 79840 79841 79842 79843 79844 79845 79846 79847 79848 79849 79850 79851 79852 79853 79854 79855 79856 79857 79858 79859 79860 79861 79862 79863 79864 79865 79866 79867 79868 79869 79870 79871 79872 79873 79874 79875 79876 79877 79878 79879 79880 79881 79882 79883 79884 79885 79886 79887 79888 79889 79890 79891 79892 79893 79894 79895 79896 79897 79898 79899 79900 79901 79902 79903 79904 79905 79906 79907 79908 79909 79910 79911 79912 79913 79914 79915 79916 79917 79918 79919 79920 79921 79922 79923 79924 79925 79926 79927 79928 79929 79930 79931 79932 79933 79934 79935 79936 79937 79938 79939 79940 79941 79942 79943 79944 79945 79946 79947 79948 79949 79950 79951 79952 79953 79954 79955 79956 79957 79958 79959 79960 79961 79962 79963 79964 79965 79966 79967 79968 79969 79970 79971 79972 79973 79974 79975 79976 79977 79978 79979 79980 79981 79982 79983 79984 79985 79986 79987 79988 79989 79990 79991 79992 79993 79994 79995 79996 79997 79998 79999 80000 80001 80002 80003 80004 80005 80006 80007 80008 80009 80010 80011 80012 80013 80014 80015 80016 80017 80018 80019 80020 80021 80022 80023 80024 80025 80026 80027 80028 80029 80030 80031 80032 80033 80034 80035 80036 80037 80038 80039 80040 80041 80042 80043 80044 80045 80046 80047 80048 80049 80050 80051 80052 80053 80054 80055 80056 80057 80058 80059 80060 80061 80062 80063 80064 80065 80066 80067 80068 80069 80070 80071 80072 80073 80074 80075 80076 80077 80078 80079 80080 80081 80082 80083 80084 80085 80086 80087 80088 80089 80090 80091 80092 80093 80094 80095 80096 80097 80098 80099 80100 80101 80102 80103 80104 80105 80106 80107 80108 80109 80110 80111 80112 80113 80114 80115 80116 80117 80118 80119 80120 80121 80122 80123 80124 80125 80126 80127 80128 80129 80130 80131 80132 80133 80134 80135 80136 80137 80138 80139 80140 80141 80142 80143 80144 80145 80146 80147 80148 80149 80150 80151 80152 80153 80154 80155 80156 80157 80158 80159 80160 80161 80162 80163 80164 80165 80166 80167 80168 80169 80170 80171 80172 80173 80174 80175 80176 80177 80178 80179 80180 80181 80182 80183 80184 80185 80186 80187 80188 80189 80190 80191 80192 80193 80194 80195 80196 80197 80198 80199 80200 80201 80202 80203 80204 80205 80206 80207 80208 80209 80210 80211 80212 80213 80214 80215 80216 80217 80218 80219 80220 80221 80222 80223 80224 80225 80226 80227 80228 80229 80230 80231 80232 80233 80234 80235 80236 80237 80238 80239 80240 80241 80242 80243 80244 80245 80246 80247 80248 80249 80250 80251 80252 80253 80254 80255 80256 80257 80258 80259 80260 80261 80262 80263 80264 80265 80266 80267 80268 80269 80270 80271 80272 80273 80274 80275 80276 80277 80278 80279 80280 80281 80282 80283 80284 80285 80286 80287 80288 80289 80290 80291 80292 80293 80294 80295 80296 80297 80298 80299 80300 80301 80302 80303 80304 80305 80306 80307 80308 80309 80310 80311 80312 80313 80314 80315 80316 80317 80318 80319 80320 80321 80322 80323 80324 80325 80326 80327 80328 80329 80330 80331 80332 80333 80334 80335 80336 80337 80338 80339 80340 80341 80342 80343 80344 80345 80346 80347 80348 80349 80350 80351 80352 80353 80354 80355 80356 80357 80358 80359 80360 80361 80362 80363 80364 80365 80366 80367 80368 80369 80370 80371 80372 80373 80374 80375 80376 80377 80378 80379 80380 80381 80382 80383 80384 80385 80386 80387 80388 80389 80390 80391 80392 80393 80394 80395 80396 80397 80398 80399 80400 80401 80402 80403 80404 80405 80406 80407 80408 80409 80410 80411 80412 80413 80414 80415 80416 80417 80418 80419 80420 80421 80422 80423 80424 80425 80426 80427 80428 80429 80430 80431 80432 80433 80434 80435 80436 80437 80438 80439 80440 80441 80442 80443 80444 80445 80446 80447 80448 80449 80450 80451 80452 80453 80454 80455 80456 80457 80458 80459 80460 80461 80462 80463 80464 80465 80466 80467 80468 80469 80470 80471 80472 80473 80474 80475 80476 80477 80478 80479 80480 80481 80482 80483 80484 80485 80486 80487 80488 80489 80490 80491 80492 80493 80494 80495 80496 80497 80498 80499 80500 80501 80502 80503 80504 80505 80506 80507 80508 80509 80510 80511 80512 80513 80514 80515 80516 80517 80518 80519 80520 80521 80522 80523 80524 80525 80526 80527 80528 80529 80530 80531 80532 80533 80534 80535 80536 80537 80538 80539 80540 80541 80542 80543 80544 80545 80546 80547 80548 80549 80550 80551 80552 80553 80554 80555 80556 80557 80558 80559 80560 80561 80562 80563 80564 80565 80566 80567 80568 80569 80570 80571 80572 80573 80574 80575 80576 80577 80578 80579 80580 80581 80582 80583 80584 80585 80586 80587 80588 80589 80590 80591 80592 80593 80594 80595 80596 80597 80598 80599 80600 80601 80602 80603 80604 80605 80606 80607 80608 80609 80610 80611 80612 80613 80614 80615 80616 80617 80618 80619 80620 80621 80622 80623 80624 80625 80626 80627 80628 80629 80630 80631 80632 80633 80634 80635 80636 80637 80638 80639 80640 80641 80642 80643 80644 80645 80646 80647 80648 80649 80650 80651 80652 80653 80654 80655 80656 80657 80658 80659 80660 80661 80662 80663 80664 80665 80666 80667 80668 80669 80670 80671 80672 80673 80674 80675 80676 80677 80678 80679 80680 80681 80682 80683 80684 80685 80686 80687 80688 80689 80690 80691 80692 80693 80694 80695 80696 80697 80698 80699 80700 80701 80702 80703 80704 80705 80706 80707 80708 80709 80710 80711 80712 80713 80714 80715 80716 80717 80718 80719 80720 80721 80722 80723 80724 80725 80726 80727 80728 80729 80730 80731 80732 80733 80734 80735 80736 80737 80738 80739 80740 80741 80742 80743 80744 80745 80746 80747 80748 80749 80750 80751 80752 80753 80754 80755 80756 80757 80758 80759 80760 80761 80762 80763 80764 80765 80766 80767 80768 80769 80770 80771 80772 80773 80774 80775 80776 80777 80778 80779 80780 80781 80782 80783 80784 80785 80786 80787 80788 80789 80790 80791 80792 80793 80794 80795 80796 80797 80798 80799 80800 80801 80802 80803 80804 80805 80806 80807 80808 80809 80810 80811 80812 80813 80814 80815 80816 80817 80818 80819 80820 80821 80822 80823 80824 80825 80826 80827 80828 80829 80830 80831 80832 80833 80834 80835 80836 80837 80838 80839 80840 80841 80842 80843 80844 80845 80846 80847 80848 80849 80850 80851 80852 80853 80854 80855 80856 80857 80858 80859 80860 80861 80862 80863 80864 80865 80866 80867 80868 80869 80870 80871 80872 80873 80874 80875 80876 80877 80878 80879 80880 80881 80882 80883 80884 80885 80886 80887 80888 80889 80890 80891 80892 80893 80894 80895 80896 80897 80898 80899 80900 80901 80902 80903 80904 80905 80906 80907 80908 80909 80910 80911 80912 80913 80914 80915 80916 80917 80918 80919 80920 80921 80922 80923 80924 80925 80926 80927 80928 80929 80930 80931 80932 80933 80934 80935 80936 80937 80938 80939 80940 80941 80942 80943 80944 80945 80946 80947 80948 80949 80950 80951 80952 80953 80954 80955 80956 80957 80958 80959 80960 80961 80962 80963 80964 80965 80966 80967 80968 80969 80970 80971 80972 80973 80974 80975 80976 80977 80978 80979 80980 80981 80982 80983 80984 80985 80986 80987 80988 80989 80990 80991 80992 80993 80994 80995 80996 80997 80998 80999 81000 81001 81002 81003 81004 81005 81006 81007 81008 81009 81010 81011 81012 81013 81014 81015 81016 81017 81018 81019 81020 81021 81022 81023 81024 81025 81026 81027 81028 81029 81030 81031 81032 81033 81034 81035 81036 81037 81038 81039 81040 81041 81042 81043 81044 81045 81046 81047 81048 81049 81050 81051 81052 81053 81054 81055 81056 81057 81058 81059 81060 81061 81062 81063 81064 81065 81066 81067 81068 81069 81070 81071 81072 81073 81074 81075 81076 81077 81078 81079 81080 81081 81082 81083 81084 81085 81086 81087 81088 81089 81090 81091 81092 81093 81094 81095 81096 81097 81098 81099 81100 81101 81102 81103 81104 81105 81106 81107 81108 81109 81110 81111 81112 81113 81114 81115 81116 81117 81118 81119 81120 81121 81122 81123 81124 81125 81126 81127 81128 81129 81130 81131 81132 81133 81134 81135 81136 81137 81138 81139 81140 81141 81142 81143 81144 81145 81146 81147 81148 81149 81150 81151 81152 81153 81154 81155 81156 81157 81158 81159 81160 81161 81162 81163 81164 81165 81166 81167 81168 81169 81170 81171 81172 81173 81174 81175 81176 81177 81178 81179 81180 81181 81182 81183 81184 81185 81186 81187 81188 81189 81190 81191 81192 81193 81194 81195 81196 81197 81198 81199 81200 81201 81202 81203 81204 81205 81206 81207 81208 81209 81210 81211 81212 81213 81214 81215 81216 81217 81218 81219 81220 81221 81222 81223 81224 81225 81226 81227 81228 81229 81230 81231 81232 81233 81234 81235 81236 81237 81238 81239 81240 81241 81242 81243 81244 81245 81246 81247 81248 81249 81250 81251 81252 81253 81254 81255 81256 81257 81258 81259 81260 81261 81262 81263 81264 81265 81266 81267 81268 81269 81270 81271 81272 81273 81274 81275 81276 81277 81278 81279 81280 81281 81282 81283 81284 81285 81286 81287 81288 81289 81290 81291 81292 81293 81294 81295 81296 81297 81298 81299 81300 81301 81302 81303 81304 81305 81306 81307 81308 81309 81310 81311 81312 81313 81314 81315 81316 81317 81318 81319 81320 81321 81322 81323 81324 81325 81326 81327 81328 81329 81330 81331 81332 81333 81334 81335 81336 81337 81338 81339 81340 81341 81342 81343 81344 81345 81346 81347 81348 81349 81350 81351 81352 81353 81354 81355 81356 81357 81358 81359 81360 81361 81362 81363 81364 81365 81366 81367 81368 81369 81370 81371 81372 81373 81374 81375 81376 81377 81378 81379 81380 81381 81382 81383 81384 81385 81386 81387 81388 81389 81390 81391 81392 81393 81394 81395 81396 81397 81398 81399 81400 81401 81402 81403 81404 81405 81406 81407 81408 81409 81410 81411 81412 81413 81414 81415 81416 81417 81418 81419 81420 81421 81422 81423 81424 81425 81426 81427 81428 81429 81430 81431 81432 81433 81434 81435 81436 81437 81438 81439 81440 81441 81442 81443 81444 81445 81446 81447 81448 81449 81450 81451 81452 81453 81454 81455 81456 81457 81458 81459 81460 81461 81462 81463 81464 81465 81466 81467 81468 81469 81470 81471 81472 81473 81474 81475 81476 81477 81478 81479 81480 81481 81482 81483 81484 81485 81486 81487 81488 81489 81490 81491 81492 81493 81494 81495 81496 81497 81498 81499 81500 81501 81502 81503 81504 81505 81506 81507 81508 81509 81510 81511 81512 81513 81514 81515 81516 81517 81518 81519 81520 81521 81522 81523 81524 81525 81526 81527 81528 81529 81530 81531 81532 81533 81534 81535 81536 81537 81538 81539 81540 81541 81542 81543 81544 81545 81546 81547 81548 81549 81550 81551 81552 81553 81554 81555 81556 81557 81558 81559 81560 81561 81562 81563 81564 81565 81566 81567 81568 81569 81570 81571 81572 81573 81574 81575 81576 81577 81578 81579 81580 81581 81582 81583 81584 81585 81586 81587 81588 81589 81590 81591 81592 81593 81594 81595 81596 81597 81598 81599 81600 81601 81602 81603 81604 81605 81606 81607 81608 81609 81610 81611 81612 81613 81614 81615 81616 81617 81618 81619 81620 81621 81622 81623 81624 81625 81626 81627 81628 81629 81630 81631 81632 81633 81634 81635 81636 81637 81638 81639 81640 81641 81642 81643 81644 81645 81646 81647 81648 81649 81650 81651 81652 81653 81654 81655 81656 81657 81658 81659 81660 81661 81662 81663 81664 81665 81666 81667 81668 81669 81670 81671 81672 81673 81674 81675 81676 81677 81678 81679 81680 81681 81682 81683 81684 81685 81686 81687 81688 81689 81690 81691 81692 81693 81694 81695 81696 81697 81698 81699 81700 81701 81702 81703 81704 81705 81706 81707 81708 81709 81710 81711 81712 81713 81714 81715 81716 81717 81718 81719 81720 81721 81722 81723 81724 81725 81726 81727 81728 81729 81730 81731 81732 81733 81734 81735 81736 81737 81738 81739 81740 81741 81742 81743 81744 81745 81746 81747 81748 81749 81750 81751 81752 81753 81754 81755 81756 81757 81758 81759 81760 81761 81762 81763 81764 81765 81766 81767 81768 81769 81770 81771 81772 81773 81774 81775 81776 81777 81778 81779 81780 81781 81782 81783 81784 81785 81786 81787 81788 81789 81790 81791 81792 81793 81794 81795 81796 81797 81798 81799 81800 81801 81802 81803 81804 81805 81806 81807 81808 81809 81810 81811 81812 81813 81814 81815 81816 81817 81818 81819 81820 81821 81822 81823 81824 81825 81826 81827 81828 81829 81830 81831 81832 81833 81834 81835 81836 81837 81838 81839 81840 81841 81842 81843 81844 81845 81846 81847 81848 81849 81850 81851 81852 81853 81854 81855 81856 81857 81858 81859 81860 81861 81862 81863 81864 81865 81866 81867 81868 81869 81870 81871 81872 81873 81874 81875 81876 81877 81878 81879 81880 81881 81882 81883 81884 81885 81886 81887 81888 81889 81890 81891 81892 81893 81894 81895 81896 81897 81898 81899 81900 81901 81902 81903 81904 81905 81906 81907 81908 81909 81910 81911 81912 81913 81914 81915 81916 81917 81918 81919 81920 81921 81922 81923 81924 81925 81926 81927 81928 81929 81930 81931 81932 81933 81934 81935 81936 81937 81938 81939 81940 81941 81942 81943 81944 81945 81946 81947 81948 81949 81950 81951 81952 81953 81954 81955 81956 81957 81958 81959 81960 81961 81962 81963 81964 81965 81966 81967 81968 81969 81970 81971 81972 81973 81974 81975 81976 81977 81978 81979 81980 81981 81982 81983 81984 81985 81986 81987 81988 81989 81990 81991 81992 81993 81994 81995 81996 81997 81998 81999 82000 82001 82002 82003 82004 82005 82006 82007 82008 82009 82010 82011 82012 82013 82014 82015 82016 82017 82018 82019 82020 82021 82022 82023 82024 82025 82026 82027 82028 82029 82030 82031 82032 82033 82034 82035 82036 82037 82038 82039 82040 82041 82042 82043 82044 82045 82046 82047 82048 82049 82050 82051 82052 82053 82054 82055 82056 82057 82058 82059 82060 82061 82062 82063 82064 82065 82066 82067 82068 82069 82070 82071 82072 82073 82074 82075 82076 82077 82078 82079 82080 82081 82082 82083 82084 82085 82086 82087 82088 82089 82090 82091 82092 82093 82094 82095 82096 82097 82098 82099 82100 82101 82102 82103 82104 82105 82106 82107 82108 82109 82110 82111 82112 82113 82114 82115 82116 82117 82118 82119 82120 82121 82122 82123 82124 82125 82126 82127 82128 82129 82130 82131 82132 82133 82134 82135 82136 82137 82138 82139 82140 82141 82142 82143 82144 82145 82146 82147 82148 82149 82150 82151 82152 82153 82154 82155 82156 82157 82158 82159 82160 82161 82162 82163 82164 82165 82166 82167 82168 82169 82170 82171 82172 82173 82174 82175 82176 82177 82178 82179 82180 82181 82182 82183 82184 82185 82186 82187 82188 82189 82190 82191 82192 82193 82194 82195 82196 82197 82198 82199 82200 82201 82202 82203 82204 82205 82206 82207 82208 82209 82210 82211 82212 82213 82214 82215 82216 82217 82218 82219 82220 82221 82222 82223 82224 82225 82226 82227 82228 82229 82230 82231 82232 82233 82234 82235 82236 82237 82238 82239 82240 82241 82242 82243 82244 82245 82246 82247 82248 82249 82250 82251 82252 82253 82254 82255 82256 82257 82258 82259 82260 82261 82262 82263 82264 82265 82266 82267 82268 82269 82270 82271 82272 82273 82274 82275 82276 82277 82278 82279 82280 82281 82282 82283 82284 82285 82286 82287 82288 82289 82290 82291 82292 82293 82294 82295 82296 82297 82298 82299 82300 82301 82302 82303 82304 82305 82306 82307 82308 82309 82310 82311 82312 82313 82314 82315 82316 82317 82318 82319 82320 82321 82322 82323 82324 82325 82326 82327 82328 82329 82330 82331 82332 82333 82334 82335 82336 82337 82338 82339 82340 82341 82342 82343 82344 82345 82346 82347 82348 82349 82350 82351 82352 82353 82354 82355 82356 82357 82358 82359 82360 82361 82362 82363 82364 82365 82366 82367 82368 82369 82370 82371 82372 82373 82374 82375 82376 82377 82378 82379 82380 82381 82382 82383 82384 82385 82386 82387 82388 82389 82390 82391 82392 82393 82394 82395 82396 82397 82398 82399 82400 82401 82402 82403 82404 82405 82406 82407 82408 82409 82410 82411 82412 82413 82414 82415 82416 82417 82418 82419 82420 82421 82422 82423 82424 82425 82426 82427 82428 82429 82430 82431 82432 82433 82434 82435 82436 82437 82438 82439 82440 82441 82442 82443 82444 82445 82446 82447 82448 82449 82450 82451 82452 82453 82454 82455 82456 82457 82458 82459 82460 82461 82462 82463 82464 82465 82466 82467 82468 82469 82470 82471 82472 82473 82474 82475 82476 82477 82478 82479 82480 82481 82482 82483 82484 82485 82486 82487 82488 82489 82490 82491 82492 82493 82494 82495 82496 82497 82498 82499 82500 82501 82502 82503 82504 82505 82506 82507 82508 82509 82510 82511 82512 82513 82514 82515 82516 82517 82518 82519 82520 82521 82522 82523 82524 82525 82526 82527 82528 82529 82530 82531 82532 82533 82534 82535 82536 82537 82538 82539 82540 82541 82542 82543 82544 82545 82546 82547 82548 82549 82550 82551 82552 82553 82554 82555 82556 82557 82558 82559 82560 82561 82562 82563 82564 82565 82566 82567 82568 82569 82570 82571 82572 82573 82574 82575 82576 82577 82578 82579 82580 82581 82582 82583 82584 82585 82586 82587 82588 82589 82590 82591 82592 82593 82594 82595 82596 82597 82598 82599 82600 82601 82602 82603 82604 82605 82606 82607 82608 82609 82610 82611 82612 82613 82614 82615 82616 82617 82618 82619 82620 82621 82622 82623 82624 82625 82626 82627 82628 82629 82630 82631 82632 82633 82634 82635 82636 82637 82638 82639 82640 82641 82642 82643 82644 82645 82646 82647 82648 82649 82650 82651 82652 82653 82654 82655 82656 82657 82658 82659 82660 82661 82662 82663 82664 82665 82666 82667 82668 82669 82670 82671 82672 82673 82674 82675 82676 82677 82678 82679 82680 82681 82682 82683 82684 82685 82686 82687 82688 82689 82690 82691 82692 82693 82694 82695 82696 82697 82698 82699 82700 82701 82702 82703 82704 82705 82706 82707 82708 82709 82710 82711 82712 82713 82714 82715 82716 82717 82718 82719 82720 82721 82722 82723 82724 82725 82726 82727 82728 82729 82730 82731 82732 82733 82734 82735 82736 82737 82738 82739 82740 82741 82742 82743 82744 82745 82746 82747 82748 82749 82750 82751 82752 82753 82754 82755 82756 82757 82758 82759 82760 82761 82762 82763 82764 82765 82766 82767 82768 82769 82770 82771 82772 82773 82774 82775 82776 82777 82778 82779 82780 82781 82782 82783 82784 82785 82786 82787 82788 82789 82790 82791 82792 82793 82794 82795 82796 82797 82798 82799 82800 82801 82802 82803 82804 82805 82806 82807 82808 82809 82810 82811 82812 82813 82814 82815 82816 82817 82818 82819 82820 82821 82822 82823 82824 82825 82826 82827 82828 82829 82830 82831 82832 82833 82834 82835 82836 82837 82838 82839 82840 82841 82842 82843 82844 82845 82846 82847 82848 82849 82850 82851 82852 82853 82854 82855 82856 82857 82858 82859 82860 82861 82862 82863 82864 82865 82866 82867 82868 82869 82870 82871 82872 82873 82874 82875 82876 82877 82878 82879 82880 82881 82882 82883 82884 82885 82886 82887 82888 82889 82890 82891 82892 82893 82894 82895 82896 82897 82898 82899 82900 82901 82902 82903 82904 82905 82906 82907 82908 82909 82910 82911 82912 82913 82914 82915 82916 82917 82918 82919 82920 82921 82922 82923 82924 82925 82926 82927 82928 82929 82930 82931 82932 82933 82934 82935 82936 82937 82938 82939 82940 82941 82942 82943 82944 82945 82946 82947 82948 82949 82950 82951 82952 82953 82954 82955 82956 82957 82958 82959 82960 82961 82962 82963 82964 82965 82966 82967 82968 82969 82970 82971 82972 82973 82974 82975 82976 82977 82978 82979 82980 82981 82982 82983 82984 82985 82986 82987 82988 82989 82990 82991 82992 82993 82994 82995 82996 82997 82998 82999 83000 83001 83002 83003 83004 83005 83006 83007 83008 83009 83010 83011 83012 83013 83014 83015 83016 83017 83018 83019 83020 83021 83022 83023 83024 83025 83026 83027 83028 83029 83030 83031 83032 83033 83034 83035 83036 83037 83038 83039 83040 83041 83042 83043 83044 83045 83046 83047 83048 83049 83050 83051 83052 83053 83054 83055 83056 83057 83058 83059 83060 83061 83062 83063 83064 83065 83066 83067 83068 83069 83070 83071 83072 83073 83074 83075 83076 83077 83078 83079 83080 83081 83082 83083 83084 83085 83086 83087 83088 83089 83090 83091 83092 83093 83094 83095 83096 83097 83098 83099 83100 83101 83102 83103 83104 83105 83106 83107 83108 83109 83110 83111 83112 83113 83114 83115 83116 83117 83118 83119 83120 83121 83122 83123 83124 83125 83126 83127 83128 83129 83130 83131 83132 83133 83134 83135 83136 83137 83138 83139 83140 83141 83142 83143 83144 83145 83146 83147 83148 83149 83150 83151 83152 83153 83154 83155 83156 83157 83158 83159 83160 83161 83162 83163 83164 83165 83166 83167 83168 83169 83170 83171 83172 83173 83174 83175 83176 83177 83178 83179 83180 83181 83182 83183 83184 83185 83186 83187 83188 83189 83190 83191 83192 83193 83194 83195 83196 83197 83198 83199 83200 83201 83202 83203 83204 83205 83206 83207 83208 83209 83210 83211 83212 83213 83214 83215 83216 83217 83218 83219 83220 83221 83222 83223 83224 83225 83226 83227 83228 83229 83230 83231 83232 83233 83234 83235 83236 83237 83238 83239 83240 83241 83242 83243 83244 83245 83246 83247 83248 83249 83250 83251 83252 83253 83254 83255 83256 83257 83258 83259 83260 83261 83262 83263 83264 83265 83266 83267 83268 83269 83270 83271 83272 83273 83274 83275 83276 83277 83278 83279 83280 83281 83282 83283 83284 83285 83286 83287 83288 83289 83290 83291 83292 83293 83294 83295 83296 83297 83298 83299 83300 83301 83302 83303 83304 83305 83306 83307 83308 83309 83310 83311 83312 83313 83314 83315 83316 83317 83318 83319 83320 83321 83322 83323 83324 83325 83326 83327 83328 83329 83330 83331 83332 83333 83334 83335 83336 83337 83338 83339 83340 83341 83342 83343 83344 83345 83346 83347 83348 83349 83350 83351 83352 83353 83354 83355 83356 83357 83358 83359 83360 83361 83362 83363 83364 83365 83366 83367 83368 83369 83370 83371 83372 83373 83374 83375 83376 83377 83378 83379 83380 83381 83382 83383 83384 83385 83386 83387 83388 83389 83390 83391 83392 83393 83394 83395 83396 83397 83398 83399 83400 83401 83402 83403 83404 83405 83406 83407 83408 83409 83410 83411 83412 83413 83414 83415 83416 83417 83418 83419 83420 83421 83422 83423 83424 83425 83426 83427 83428 83429 83430 83431 83432 83433 83434 83435 83436 83437 83438 83439 83440 83441 83442 83443 83444 83445 83446 83447 83448 83449 83450 83451 83452 83453 83454 83455 83456 83457 83458 83459 83460 83461 83462 83463 83464 83465 83466 83467 83468 83469 83470 83471 83472 83473 83474 83475 83476 83477 83478 83479 83480 83481 83482 83483 83484 83485 83486 83487 83488 83489 83490 83491 83492 83493 83494 83495 83496 83497 83498 83499 83500 83501 83502 83503 83504 83505 83506 83507 83508 83509 83510 83511 83512 83513 83514 83515 83516 83517 83518 83519 83520 83521 83522 83523 83524 83525 83526 83527 83528 83529 83530 83531 83532 83533 83534 83535 83536 83537 83538 83539 83540 83541 83542 83543 83544 83545 83546 83547 83548 83549 83550 83551 83552 83553 83554 83555 83556 83557 83558 83559 83560 83561 83562 83563 83564 83565 83566 83567 83568 83569 83570 83571 83572 83573 83574 83575 83576 83577 83578 83579 83580 83581 83582 83583 83584 83585 83586 83587 83588 83589 83590 83591 83592 83593 83594 83595 83596 83597 83598 83599 83600 83601 83602 83603 83604 83605 83606 83607 83608 83609 83610 83611 83612 83613 83614 83615 83616 83617 83618 83619 83620 83621 83622 83623 83624 83625 83626 83627 83628 83629 83630 83631 83632 83633 83634 83635 83636 83637 83638 83639 83640 83641 83642 83643 83644 83645 83646 83647 83648 83649 83650 83651 83652 83653 83654 83655 83656 83657 83658 83659 83660 83661 83662 83663 83664 83665 83666 83667 83668 83669 83670 83671 83672 83673 83674 83675 83676 83677 83678 83679 83680 83681 83682 83683 83684 83685 83686 83687 83688 83689 83690 83691 83692 83693 83694 83695 83696 83697 83698 83699 83700 83701 83702 83703 83704 83705 83706 83707 83708 83709 83710 83711 83712 83713 83714 83715 83716 83717 83718 83719 83720 83721 83722 83723 83724 83725 83726 83727 83728 83729 83730 83731 83732 83733 83734 83735 83736 83737 83738 83739 83740 83741 83742 83743 83744 83745 83746 83747 83748 83749 83750 83751 83752 83753 83754 83755 83756 83757 83758 83759 83760 83761 83762 83763 83764 83765 83766 83767 83768 83769 83770 83771 83772 83773 83774 83775 83776 83777 83778 83779 83780 83781 83782 83783 83784 83785 83786 83787 83788 83789 83790 83791 83792 83793 83794 83795 83796 83797 83798 83799 83800 83801 83802 83803 83804 83805 83806 83807 83808 83809 83810 83811 83812 83813 83814 83815 83816 83817 83818 83819 83820 83821 83822 83823 83824 83825 83826 83827 83828 83829 83830 83831 83832 83833 83834 83835 83836 83837 83838 83839 83840 83841 83842 83843 83844 83845 83846 83847 83848 83849 83850 83851 83852 83853 83854 83855 83856 83857 83858 83859 83860 83861 83862 83863 83864 83865 83866 83867 83868 83869 83870 83871 83872 83873 83874 83875 83876 83877 83878 83879 83880 83881 83882 83883 83884 83885 83886 83887 83888 83889 83890 83891 83892 83893 83894 83895 83896 83897 83898 83899 83900 83901 83902 83903 83904 83905 83906 83907 83908 83909 83910 83911 83912 83913 83914 83915 83916 83917 83918 83919 83920 83921 83922 83923 83924 83925 83926 83927 83928 83929 83930 83931 83932 83933 83934 83935 83936 83937 83938 83939 83940 83941 83942 83943 83944 83945 83946 83947 83948 83949 83950 83951 83952 83953 83954 83955 83956 83957 83958 83959 83960 83961 83962 83963 83964 83965 83966 83967 83968 83969 83970 83971 83972 83973 83974 83975 83976 83977 83978 83979 83980 83981 83982 83983 83984 83985 83986 83987 83988 83989 83990 83991 83992 83993 83994 83995 83996 83997 83998 83999 84000 84001 84002 84003 84004 84005 84006 84007 84008 84009 84010 84011 84012 84013 84014 84015 84016 84017 84018 84019 84020 84021 84022 84023 84024 84025 84026 84027 84028 84029 84030 84031 84032 84033 84034 84035 84036 84037 84038 84039 84040 84041 84042 84043 84044 84045 84046 84047 84048 84049 84050 84051 84052 84053 84054 84055 84056 84057 84058 84059 84060 84061 84062 84063 84064 84065 84066 84067 84068 84069 84070 84071 84072 84073 84074 84075 84076 84077 84078 84079 84080 84081 84082 84083 84084 84085 84086 84087 84088 84089 84090 84091 84092 84093 84094 84095 84096 84097 84098 84099 84100 84101 84102 84103 84104 84105 84106 84107 84108 84109 84110 84111 84112 84113 84114 84115 84116 84117 84118 84119 84120 84121 84122 84123 84124 84125 84126 84127 84128 84129 84130 84131 84132 84133 84134 84135 84136 84137 84138 84139 84140 84141 84142 84143 84144 84145 84146 84147 84148 84149 84150 84151 84152 84153 84154 84155 84156 84157 84158 84159 84160 84161 84162 84163 84164 84165 84166 84167 84168 84169 84170 84171 84172 84173 84174 84175 84176 84177 84178 84179 84180 84181 84182 84183 84184 84185 84186 84187 84188 84189 84190 84191 84192 84193 84194 84195 84196 84197 84198 84199 84200 84201 84202 84203 84204 84205 84206 84207 84208 84209 84210 84211 84212 84213 84214 84215 84216 84217 84218 84219 84220 84221 84222 84223 84224 84225 84226 84227 84228 84229 84230 84231 84232 84233 84234 84235 84236 84237 84238 84239 84240 84241 84242 84243 84244 84245 84246 84247 84248 84249 84250 84251 84252 84253 84254 84255 84256 84257 84258 84259 84260 84261 84262 84263 84264 84265 84266 84267 84268 84269 84270 84271 84272 84273 84274 84275 84276 84277 84278 84279 84280 84281 84282 84283 84284 84285 84286 84287 84288 84289 84290 84291 84292 84293 84294 84295 84296 84297 84298 84299 84300 84301 84302 84303 84304 84305 84306 84307 84308 84309 84310 84311 84312 84313 84314 84315 84316 84317 84318 84319 84320 84321 84322 84323 84324 84325 84326 84327 84328 84329 84330 84331 84332 84333 84334 84335 84336 84337 84338 84339 84340 84341 84342 84343 84344 84345 84346 84347 84348 84349 84350 84351 84352 84353 84354 84355 84356 84357 84358 84359 84360 84361 84362 84363 84364 84365 84366 84367 84368 84369 84370 84371 84372 84373 84374 84375 84376 84377 84378 84379 84380 84381 84382 84383 84384 84385 84386 84387 84388 84389 84390 84391 84392 84393 84394 84395 84396 84397 84398 84399 84400 84401 84402 84403 84404 84405 84406 84407 84408 84409 84410 84411 84412 84413 84414 84415 84416 84417 84418 84419 84420 84421 84422 84423 84424 84425 84426 84427 84428 84429 84430 84431 84432 84433 84434 84435 84436 84437 84438 84439 84440 84441 84442 84443 84444 84445 84446 84447 84448 84449 84450 84451 84452 84453 84454 84455 84456 84457 84458 84459 84460 84461 84462 84463 84464 84465 84466 84467 84468 84469 84470 84471 84472 84473 84474 84475 84476 84477 84478 84479 84480 84481 84482 84483 84484 84485 84486 84487 84488 84489 84490 84491 84492 84493 84494 84495 84496 84497 84498 84499 84500 84501 84502 84503 84504 84505 84506 84507 84508 84509 84510 84511 84512 84513 84514 84515 84516 84517 84518 84519 84520 84521 84522 84523 84524 84525 84526 84527 84528 84529 84530 84531 84532 84533 84534 84535 84536 84537 84538 84539 84540 84541 84542 84543 84544 84545 84546 84547 84548 84549 84550 84551 84552 84553 84554 84555 84556 84557 84558 84559 84560 84561 84562 84563 84564 84565 84566 84567 84568 84569 84570 84571 84572 84573 84574 84575 84576 84577 84578 84579 84580 84581 84582 84583 84584 84585 84586 84587 84588 84589 84590 84591 84592 84593 84594 84595 84596 84597 84598 84599 84600 84601 84602 84603 84604 84605 84606 84607 84608 84609 84610 84611 84612 84613 84614 84615 84616 84617 84618 84619 84620 84621 84622 84623 84624 84625 84626 84627 84628 84629 84630 84631 84632 84633 84634 84635 84636 84637 84638 84639 84640 84641 84642 84643 84644 84645 84646 84647 84648 84649 84650 84651 84652 84653 84654 84655 84656 84657 84658 84659 84660 84661 84662 84663 84664 84665 84666 84667 84668 84669 84670 84671 84672 84673 84674 84675 84676 84677 84678 84679 84680 84681 84682 84683 84684 84685 84686 84687 84688 84689 84690 84691 84692 84693 84694 84695 84696 84697 84698 84699 84700 84701 84702 84703 84704 84705 84706 84707 84708 84709 84710 84711 84712 84713 84714 84715 84716 84717 84718 84719 84720 84721 84722 84723 84724 84725 84726 84727 84728 84729 84730 84731 84732 84733 84734 84735 84736 84737 84738 84739 84740 84741 84742 84743 84744 84745 84746 84747 84748 84749 84750 84751 84752 84753 84754 84755 84756 84757 84758 84759 84760 84761 84762 84763 84764 84765 84766 84767 84768 84769 84770 84771 84772 84773 84774 84775 84776 84777 84778 84779 84780 84781 84782 84783 84784 84785 84786 84787 84788 84789 84790 84791 84792 84793 84794 84795 84796 84797 84798 84799 84800 84801 84802 84803 84804 84805 84806 84807 84808 84809 84810 84811 84812 84813 84814 84815 84816 84817 84818 84819 84820 84821 84822 84823 84824 84825 84826 84827 84828 84829 84830 84831 84832 84833 84834 84835 84836 84837 84838 84839 84840 84841 84842 84843 84844 84845 84846 84847 84848 84849 84850 84851 84852 84853 84854 84855 84856 84857 84858 84859 84860 84861 84862 84863 84864 84865 84866 84867 84868 84869 84870 84871 84872 84873 84874 84875 84876 84877 84878 84879 84880 84881 84882 84883 84884 84885 84886 84887 84888 84889 84890 84891 84892 84893 84894 84895 84896 84897 84898 84899 84900 84901 84902 84903 84904 84905 84906 84907 84908 84909 84910 84911 84912 84913 84914 84915 84916 84917 84918 84919 84920 84921 84922 84923 84924 84925 84926 84927 84928 84929 84930 84931 84932 84933 84934 84935 84936 84937 84938 84939 84940 84941 84942 84943 84944 84945 84946 84947 84948 84949 84950 84951 84952 84953 84954 84955 84956 84957 84958 84959 84960 84961 84962 84963 84964 84965 84966 84967 84968 84969 84970 84971 84972 84973 84974 84975 84976 84977 84978 84979 84980 84981 84982 84983 84984 84985 84986 84987 84988 84989 84990 84991 84992 84993 84994 84995 84996 84997 84998 84999 85000 85001 85002 85003 85004 85005 85006 85007 85008 85009 85010 85011 85012 85013 85014 85015 85016 85017 85018 85019 85020 85021 85022 85023 85024 85025 85026 85027 85028 85029 85030 85031 85032 85033 85034 85035 85036 85037 85038 85039 85040 85041 85042 85043 85044 85045 85046 85047 85048 85049 85050 85051 85052 85053 85054 85055 85056 85057 85058 85059 85060 85061 85062 85063 85064 85065 85066 85067 85068 85069 85070 85071 85072 85073 85074 85075 85076 85077 85078 85079 85080 85081 85082 85083 85084 85085 85086 85087 85088 85089 85090 85091 85092 85093 85094 85095 85096 85097 85098 85099 85100 85101 85102 85103 85104 85105 85106 85107 85108 85109 85110 85111 85112 85113 85114 85115 85116 85117 85118 85119 85120 85121 85122 85123 85124 85125 85126 85127 85128 85129 85130 85131 85132 85133 85134 85135 85136 85137 85138 85139 85140 85141 85142 85143 85144 85145 85146 85147 85148 85149 85150 85151 85152 85153 85154 85155 85156 85157 85158 85159 85160 85161 85162 85163 85164 85165 85166 85167 85168 85169 85170 85171 85172 85173 85174 85175 85176 85177 85178 85179 85180 85181 85182 85183 85184 85185 85186 85187 85188 85189 85190 85191 85192 85193 85194 85195 85196 85197 85198 85199 85200 85201 85202 85203 85204 85205 85206 85207 85208 85209 85210 85211 85212 85213 85214 85215 85216 85217 85218 85219 85220 85221 85222 85223 85224 85225 85226 85227 85228 85229 85230 85231 85232 85233 85234 85235 85236 85237 85238 85239 85240 85241 85242 85243 85244 85245 85246 85247 85248 85249 85250 85251 85252 85253 85254 85255 85256 85257 85258 85259 85260 85261 85262 85263 85264 85265 85266 85267 85268 85269 85270 85271 85272 85273 85274 85275 85276 85277 85278 85279 85280 85281 85282 85283 85284 85285 85286 85287 85288 85289 85290 85291 85292 85293 85294 85295 85296 85297 85298 85299 85300 85301 85302 85303 85304 85305 85306 85307 85308 85309 85310 85311 85312 85313 85314 85315 85316 85317 85318 85319 85320 85321 85322 85323 85324 85325 85326 85327 85328 85329 85330 85331 85332 85333 85334 85335 85336 85337 85338 85339 85340 85341 85342 85343 85344 85345 85346 85347 85348 85349 85350 85351 85352 85353 85354 85355 85356 85357 85358 85359 85360 85361 85362 85363 85364 85365 85366 85367 85368 85369 85370 85371 85372 85373 85374 85375 85376 85377 85378 85379 85380 85381 85382 85383 85384 85385 85386 85387 85388 85389 85390 85391 85392 85393 85394 85395 85396 85397 85398 85399 85400 85401 85402 85403 85404 85405 85406 85407 85408 85409 85410 85411 85412 85413 85414 85415 85416 85417 85418 85419 85420 85421 85422 85423 85424 85425 85426 85427 85428 85429 85430 85431 85432 85433 85434 85435 85436 85437 85438 85439 85440 85441 85442 85443 85444 85445 85446 85447 85448 85449 85450 85451 85452 85453 85454 85455 85456 85457 85458 85459 85460 85461 85462 85463 85464 85465 85466 85467 85468 85469 85470 85471 85472 85473 85474 85475 85476 85477 85478 85479 85480 85481 85482 85483 85484 85485 85486 85487 85488 85489 85490 85491 85492 85493 85494 85495 85496 85497 85498 85499 85500 85501 85502 85503 85504 85505 85506 85507 85508 85509 85510 85511 85512 85513 85514 85515 85516 85517 85518 85519 85520 85521 85522 85523 85524 85525 85526 85527 85528 85529 85530 85531 85532 85533 85534 85535 85536 85537 85538 85539 85540 85541 85542 85543 85544 85545 85546 85547 85548 85549 85550 85551 85552 85553 85554 85555 85556 85557 85558 85559 85560 85561 85562 85563 85564 85565 85566 85567 85568 85569 85570 85571 85572 85573 85574 85575 85576 85577 85578 85579 85580 85581 85582 85583 85584 85585 85586 85587 85588 85589 85590 85591 85592 85593 85594 85595 85596 85597 85598 85599 85600 85601 85602 85603 85604 85605 85606 85607 85608 85609 85610 85611 85612 85613 85614 85615 85616 85617 85618 85619 85620 85621 85622 85623 85624 85625 85626 85627 85628 85629 85630 85631 85632 85633 85634 85635 85636 85637 85638 85639 85640 85641 85642 85643 85644 85645 85646 85647 85648 85649 85650 85651 85652 85653 85654 85655 85656 85657 85658 85659 85660 85661 85662 85663 85664 85665 85666 85667 85668 85669 85670 85671 85672 85673 85674 85675 85676 85677 85678 85679 85680 85681 85682 85683 85684 85685 85686 85687 85688 85689 85690 85691 85692 85693 85694 85695 85696 85697 85698 85699 85700 85701 85702 85703 85704 85705 85706 85707 85708 85709 85710 85711 85712 85713 85714 85715 85716 85717 85718 85719 85720 85721 85722 85723 85724 85725 85726 85727 85728 85729 85730 85731 85732 85733 85734 85735 85736 85737 85738 85739 85740 85741 85742 85743 85744 85745 85746 85747 85748 85749 85750 85751 85752 85753 85754 85755 85756 85757 85758 85759 85760 85761 85762 85763 85764 85765 85766 85767 85768 85769 85770 85771 85772 85773 85774 85775 85776 85777 85778 85779 85780 85781 85782 85783 85784 85785 85786 85787 85788 85789 85790 85791 85792 85793 85794 85795 85796 85797 85798 85799 85800 85801 85802 85803 85804 85805 85806 85807 85808 85809 85810 85811 85812 85813 85814 85815 85816 85817 85818 85819 85820 85821 85822 85823 85824 85825 85826 85827 85828 85829 85830 85831 85832 85833 85834 85835 85836 85837 85838 85839 85840 85841 85842 85843 85844 85845 85846 85847 85848 85849 85850 85851 85852 85853 85854 85855 85856 85857 85858 85859 85860 85861 85862 85863 85864 85865 85866 85867 85868 85869 85870 85871 85872 85873 85874 85875 85876 85877 85878 85879 85880 85881 85882 85883 85884 85885 85886 85887 85888 85889 85890 85891 85892 85893 85894 85895 85896 85897 85898 85899 85900 85901 85902 85903 85904 85905 85906 85907 85908 85909 85910 85911 85912 85913 85914 85915 85916 85917 85918 85919 85920 85921 85922 85923 85924 85925 85926 85927 85928 85929 85930 85931 85932 85933 85934 85935 85936 85937 85938 85939 85940 85941 85942 85943 85944 85945 85946 85947 85948 85949 85950 85951 85952 85953 85954 85955 85956 85957 85958 85959 85960 85961 85962 85963 85964 85965 85966 85967 85968 85969 85970 85971 85972 85973 85974 85975 85976 85977 85978 85979 85980 85981 85982 85983 85984 85985 85986 85987 85988 85989 85990 85991 85992 85993 85994 85995 85996 85997 85998 85999 86000 86001 86002 86003 86004 86005 86006 86007 86008 86009 86010 86011 86012 86013 86014 86015 86016 86017 86018 86019 86020 86021 86022 86023 86024 86025 86026 86027 86028 86029 86030 86031 86032 86033 86034 86035 86036 86037 86038 86039 86040 86041 86042 86043 86044 86045 86046 86047 86048 86049 86050 86051 86052 86053 86054 86055 86056 86057 86058 86059 86060 86061 86062 86063 86064 86065 86066 86067 86068 86069 86070 86071 86072 86073 86074 86075 86076 86077 86078 86079 86080 86081 86082 86083 86084 86085 86086 86087 86088 86089 86090 86091 86092 86093 86094 86095 86096 86097 86098 86099 86100 86101 86102 86103 86104 86105 86106 86107 86108 86109 86110 86111 86112 86113 86114 86115 86116 86117 86118 86119 86120 86121 86122 86123 86124 86125 86126 86127 86128 86129 86130 86131 86132 86133 86134 86135 86136 86137 86138 86139 86140 86141 86142 86143 86144 86145 86146 86147 86148 86149 86150 86151 86152 86153 86154 86155 86156 86157 86158 86159 86160 86161 86162 86163 86164 86165 86166 86167 86168 86169 86170 86171 86172 86173 86174 86175 86176 86177 86178 86179 86180 86181 86182 86183 86184 86185 86186 86187 86188 86189 86190 86191 86192 86193 86194 86195 86196 86197 86198 86199 86200 86201 86202 86203 86204 86205 86206 86207 86208 86209 86210 86211 86212 86213 86214 86215 86216 86217 86218 86219 86220 86221 86222 86223 86224 86225 86226 86227 86228 86229 86230 86231 86232 86233 86234 86235 86236 86237 86238 86239 86240 86241 86242 86243 86244 86245 86246 86247 86248 86249 86250 86251 86252 86253 86254 86255 86256 86257 86258 86259 86260 86261 86262 86263 86264 86265 86266 86267 86268 86269 86270 86271 86272 86273 86274 86275 86276 86277 86278 86279 86280 86281 86282 86283 86284 86285 86286 86287 86288 86289 86290 86291 86292 86293 86294 86295 86296 86297 86298 86299 86300 86301 86302 86303 86304 86305 86306 86307 86308 86309 86310 86311 86312 86313 86314 86315 86316 86317 86318 86319 86320 86321 86322 86323 86324 86325 86326 86327 86328 86329 86330 86331 86332 86333 86334 86335 86336 86337 86338 86339 86340 86341 86342 86343 86344 86345 86346 86347 86348 86349 86350 86351 86352 86353 86354 86355 86356 86357 86358 86359 86360 86361 86362 86363 86364 86365 86366 86367 86368 86369 86370 86371 86372 86373 86374 86375 86376 86377 86378 86379 86380 86381 86382 86383 86384 86385 86386 86387 86388 86389 86390 86391 86392 86393 86394 86395 86396 86397 86398 86399 86400 86401 86402 86403 86404 86405 86406 86407 86408 86409 86410 86411 86412 86413 86414 86415 86416 86417 86418 86419 86420 86421 86422 86423 86424 86425 86426 86427 86428 86429 86430 86431 86432 86433 86434 86435 86436 86437 86438 86439 86440 86441 86442 86443 86444 86445 86446 86447 86448 86449 86450 86451 86452 86453 86454 86455 86456 86457 86458 86459 86460 86461 86462 86463 86464 86465 86466 86467 86468 86469 86470 86471 86472 86473 86474 86475 86476 86477 86478 86479 86480 86481 86482 86483 86484 86485 86486 86487 86488 86489 86490 86491 86492 86493 86494 86495 86496 86497 86498 86499 86500 86501 86502 86503 86504 86505 86506 86507 86508 86509 86510 86511 86512 86513 86514 86515 86516 86517 86518 86519 86520 86521 86522 86523 86524 86525 86526 86527 86528 86529 86530 86531 86532 86533 86534 86535 86536 86537 86538 86539 86540 86541 86542 86543 86544 86545 86546 86547 86548 86549 86550 86551 86552 86553 86554 86555 86556 86557 86558 86559 86560 86561 86562 86563 86564 86565 86566 86567 86568 86569 86570 86571 86572 86573 86574 86575 86576 86577 86578 86579 86580 86581 86582 86583 86584 86585 86586 86587 86588 86589 86590 86591 86592 86593 86594 86595 86596 86597 86598 86599 86600 86601 86602 86603 86604 86605 86606 86607 86608 86609 86610 86611 86612 86613 86614 86615 86616 86617 86618 86619 86620 86621 86622 86623 86624 86625 86626 86627 86628 86629 86630 86631 86632 86633 86634 86635 86636 86637 86638 86639 86640 86641 86642 86643 86644 86645 86646 86647 86648 86649 86650 86651 86652 86653 86654 86655 86656 86657 86658 86659 86660 86661 86662 86663 86664 86665 86666 86667 86668 86669 86670 86671 86672 86673 86674 86675 86676 86677 86678 86679 86680 86681 86682 86683 86684 86685 86686 86687 86688 86689 86690 86691 86692 86693 86694 86695 86696 86697 86698 86699 86700 86701 86702 86703 86704 86705 86706 86707 86708 86709 86710 86711 86712 86713 86714 86715 86716 86717 86718 86719 86720 86721 86722 86723 86724 86725 86726 86727 86728 86729 86730 86731 86732 86733 86734 86735 86736 86737 86738 86739 86740 86741 86742 86743 86744 86745 86746 86747 86748 86749 86750 86751 86752 86753 86754 86755 86756 86757 86758 86759 86760 86761 86762 86763 86764 86765 86766 86767 86768 86769 86770 86771 86772 86773 86774 86775 86776 86777 86778 86779 86780 86781 86782 86783 86784 86785 86786 86787 86788 86789 86790 86791 86792 86793 86794 86795 86796 86797 86798 86799 86800 86801 86802 86803 86804 86805 86806 86807 86808 86809 86810 86811 86812 86813 86814 86815 86816 86817 86818 86819 86820 86821 86822 86823 86824 86825 86826 86827 86828 86829 86830 86831 86832 86833 86834 86835 86836 86837 86838 86839 86840 86841 86842 86843 86844 86845 86846 86847 86848 86849 86850 86851 86852 86853 86854 86855 86856 86857 86858 86859 86860 86861 86862 86863 86864 86865 86866 86867 86868 86869 86870 86871 86872 86873 86874 86875 86876 86877 86878 86879 86880 86881 86882 86883 86884 86885 86886 86887 86888 86889 86890 86891 86892 86893 86894 86895 86896 86897 86898 86899 86900 86901 86902 86903 86904 86905 86906 86907 86908 86909 86910 86911 86912 86913 86914 86915 86916 86917 86918 86919 86920 86921 86922 86923 86924 86925 86926 86927 86928 86929 86930 86931 86932 86933 86934 86935 86936 86937 86938 86939 86940 86941 86942 86943 86944 86945 86946 86947 86948 86949 86950 86951 86952 86953 86954 86955 86956 86957 86958 86959 86960 86961 86962 86963 86964 86965 86966 86967 86968 86969 86970 86971 86972 86973 86974 86975 86976 86977 86978 86979 86980 86981 86982 86983 86984 86985 86986 86987 86988 86989 86990 86991 86992 86993 86994 86995 86996 86997 86998 86999 87000 87001 87002 87003 87004 87005 87006 87007 87008 87009 87010 87011 87012 87013 87014 87015 87016 87017 87018 87019 87020 87021 87022 87023 87024 87025 87026 87027 87028 87029 87030 87031 87032 87033 87034 87035 87036 87037 87038 87039 87040 87041 87042 87043 87044 87045 87046 87047 87048 87049 87050 87051 87052 87053 87054 87055 87056 87057 87058 87059 87060 87061 87062 87063 87064 87065 87066 87067 87068 87069 87070 87071 87072 87073 87074 87075 87076 87077 87078 87079 87080 87081 87082 87083 87084 87085 87086 87087 87088 87089 87090 87091 87092 87093 87094 87095 87096 87097 87098 87099 87100 87101 87102 87103 87104 87105 87106 87107 87108 87109 87110 87111 87112 87113 87114 87115 87116 87117 87118 87119 87120 87121 87122 87123 87124 87125 87126 87127 87128 87129 87130 87131 87132 87133 87134 87135 87136 87137 87138 87139 87140 87141 87142 87143 87144 87145 87146 87147 87148 87149 87150 87151 87152 87153 87154 87155 87156 87157 87158 87159 87160 87161 87162 87163 87164 87165 87166 87167 87168 87169 87170 87171 87172 87173 87174 87175 87176 87177 87178 87179 87180 87181 87182 87183 87184 87185 87186 87187 87188 87189 87190 87191 87192 87193 87194 87195 87196 87197 87198 87199 87200 87201 87202 87203 87204 87205 87206 87207 87208 87209 87210 87211 87212 87213 87214 87215 87216 87217 87218 87219 87220 87221 87222 87223 87224 87225 87226 87227 87228 87229 87230 87231 87232 87233 87234 87235 87236 87237 87238 87239 87240 87241 87242 87243 87244 87245 87246 87247 87248 87249 87250 87251 87252 87253 87254 87255 87256 87257 87258 87259 87260 87261 87262 87263 87264 87265 87266 87267 87268 87269 87270 87271 87272 87273 87274 87275 87276 87277 87278 87279 87280 87281 87282 87283 87284 87285 87286 87287 87288 87289 87290 87291 87292 87293 87294 87295 87296 87297 87298 87299 87300 87301 87302 87303 87304 87305 87306 87307 87308 87309 87310 87311 87312 87313 87314 87315 87316 87317 87318 87319 87320 87321 87322 87323 87324 87325 87326 87327 87328 87329 87330 87331 87332 87333 87334 87335 87336 87337 87338 87339 87340 87341 87342 87343 87344 87345 87346 87347 87348 87349 87350 87351 87352 87353 87354 87355 87356 87357 87358 87359 87360 87361 87362 87363 87364 87365 87366 87367 87368 87369 87370 87371 87372 87373 87374 87375 87376 87377 87378 87379 87380 87381 87382 87383 87384 87385 87386 87387 87388 87389 87390 87391 87392 87393 87394 87395 87396 87397 87398 87399 87400 87401 87402 87403 87404 87405 87406 87407 87408 87409 87410 87411 87412 87413 87414 87415 87416 87417 87418 87419 87420 87421 87422 87423 87424 87425 87426 87427 87428 87429 87430 87431 87432 87433 87434 87435 87436 87437 87438 87439 87440 87441 87442 87443 87444 87445 87446 87447 87448 87449 87450 87451 87452 87453 87454 87455 87456 87457 87458 87459 87460 87461 87462 87463 87464 87465 87466 87467 87468 87469 87470 87471 87472 87473 87474 87475 87476 87477 87478 87479 87480 87481 87482 87483 87484 87485 87486 87487 87488 87489 87490 87491 87492 87493 87494 87495 87496 87497 87498 87499 87500 87501 87502 87503 87504 87505 87506 87507 87508 87509 87510 87511 87512 87513 87514 87515 87516 87517 87518 87519 87520 87521 87522 87523 87524 87525 87526 87527 87528 87529 87530 87531 87532 87533 87534 87535 87536 87537 87538 87539 87540 87541 87542 87543 87544 87545 87546 87547 87548 87549 87550 87551 87552 87553 87554 87555 87556 87557 87558 87559 87560 87561 87562 87563 87564 87565 87566 87567 87568 87569 87570 87571 87572 87573 87574 87575 87576 87577 87578 87579 87580 87581 87582 87583 87584 87585 87586 87587 87588 87589 87590 87591 87592 87593 87594 87595 87596 87597 87598 87599 87600 87601 87602 87603 87604 87605 87606 87607 87608 87609 87610 87611 87612 87613 87614 87615 87616 87617 87618 87619 87620 87621 87622 87623 87624 87625 87626 87627 87628 87629 87630 87631 87632 87633 87634 87635 87636 87637 87638 87639 87640 87641 87642 87643 87644 87645 87646 87647 87648 87649 87650 87651 87652 87653 87654 87655 87656 87657 87658 87659 87660 87661 87662 87663 87664 87665 87666 87667 87668 87669 87670 87671 87672 87673 87674 87675 87676 87677 87678 87679 87680 87681 87682 87683 87684 87685 87686 87687 87688 87689 87690 87691 87692 87693 87694 87695 87696 87697 87698 87699 87700 87701 87702 87703 87704 87705 87706 87707 87708 87709 87710 87711 87712 87713 87714 87715 87716 87717 87718 87719 87720 87721 87722 87723 87724 87725 87726 87727 87728 87729 87730 87731 87732 87733 87734 87735 87736 87737 87738 87739 87740 87741 87742 87743 87744 87745 87746 87747 87748 87749 87750 87751 87752 87753 87754 87755 87756 87757 87758 87759 87760 87761 87762 87763 87764 87765 87766 87767 87768 87769 87770 87771 87772 87773 87774 87775 87776 87777 87778 87779 87780 87781 87782 87783 87784 87785 87786 87787 87788 87789 87790 87791 87792 87793 87794 87795 87796 87797 87798 87799 87800 87801 87802 87803 87804 87805 87806 87807 87808 87809 87810 87811 87812 87813 87814 87815 87816 87817 87818 87819 87820 87821 87822 87823 87824 87825 87826 87827 87828 87829 87830 87831 87832 87833 87834 87835 87836 87837 87838 87839 87840 87841 87842 87843 87844 87845 87846 87847 87848 87849 87850 87851 87852 87853 87854 87855 87856 87857 87858 87859 87860 87861 87862 87863 87864 87865 87866 87867 87868 87869 87870 87871 87872 87873 87874 87875 87876 87877 87878 87879 87880 87881 87882 87883 87884 87885 87886 87887 87888 87889 87890 87891 87892 87893 87894 87895 87896 87897 87898 87899 87900 87901 87902 87903 87904 87905 87906 87907 87908 87909 87910 87911 87912 87913 87914 87915 87916 87917 87918 87919 87920 87921 87922 87923 87924 87925 87926 87927 87928 87929 87930 87931 87932 87933 87934 87935 87936 87937 87938 87939 87940 87941 87942 87943 87944 87945 87946 87947 87948 87949 87950 87951 87952 87953 87954 87955 87956 87957 87958 87959 87960 87961 87962 87963 87964 87965 87966 87967 87968 87969 87970 87971 87972 87973 87974 87975 87976 87977 87978 87979 87980 87981 87982 87983 87984 87985 87986 87987 87988 87989 87990 87991 87992 87993 87994 87995 87996 87997 87998 87999 88000 88001 88002 88003 88004 88005 88006 88007 88008 88009 88010 88011 88012 88013 88014 88015 88016 88017 88018 88019 88020 88021 88022 88023 88024 88025 88026 88027 88028 88029 88030 88031 88032 88033 88034 88035 88036 88037 88038 88039 88040 88041 88042 88043 88044 88045 88046 88047 88048 88049 88050 88051 88052 88053 88054 88055 88056 88057 88058 88059 88060 88061 88062 88063 88064 88065 88066 88067 88068 88069 88070 88071 88072 88073 88074 88075 88076 88077 88078 88079 88080 88081 88082 88083 88084 88085 88086 88087 88088 88089 88090 88091 88092 88093 88094 88095 88096 88097 88098 88099 88100 88101 88102 88103 88104 88105 88106 88107 88108 88109 88110 88111 88112 88113 88114 88115 88116 88117 88118 88119 88120 88121 88122 88123 88124 88125 88126 88127 88128 88129 88130 88131 88132 88133 88134 88135 88136 88137 88138 88139 88140 88141 88142 88143 88144 88145 88146 88147 88148 88149 88150 88151 88152 88153 88154 88155 88156 88157 88158 88159 88160 88161 88162 88163 88164 88165 88166 88167 88168 88169 88170 88171 88172 88173 88174 88175 88176 88177 88178 88179 88180 88181 88182 88183 88184 88185 88186 88187 88188 88189 88190 88191 88192 88193 88194 88195 88196 88197 88198 88199 88200 88201 88202 88203 88204 88205 88206 88207 88208 88209 88210 88211 88212 88213 88214 88215 88216 88217 88218 88219 88220 88221 88222 88223 88224 88225 88226 88227 88228 88229 88230 88231 88232 88233 88234 88235 88236 88237 88238 88239 88240 88241 88242 88243 88244 88245 88246 88247 88248 88249 88250 88251 88252 88253 88254 88255 88256 88257 88258 88259 88260 88261 88262 88263 88264 88265 88266 88267 88268 88269 88270 88271 88272 88273 88274 88275 88276 88277 88278 88279 88280 88281 88282 88283 88284 88285 88286 88287 88288 88289 88290 88291 88292 88293 88294 88295 88296 88297 88298 88299 88300 88301 88302 88303 88304 88305 88306 88307 88308 88309 88310 88311 88312 88313 88314 88315 88316 88317 88318 88319 88320 88321 88322 88323 88324 88325 88326 88327 88328 88329 88330 88331 88332 88333 88334 88335 88336 88337 88338 88339 88340 88341 88342 88343 88344 88345 88346 88347 88348 88349 88350 88351 88352 88353 88354 88355 88356 88357 88358 88359 88360 88361 88362 88363 88364 88365 88366 88367 88368 88369 88370 88371 88372 88373 88374 88375 88376 88377 88378 88379 88380 88381 88382 88383 88384 88385 88386 88387 88388 88389 88390 88391 88392 88393 88394 88395 88396 88397 88398 88399 88400 88401 88402 88403 88404 88405 88406 88407 88408 88409 88410 88411 88412 88413 88414 88415 88416 88417 88418 88419 88420 88421 88422 88423 88424 88425 88426 88427 88428 88429 88430 88431 88432 88433 88434 88435 88436 88437 88438 88439 88440 88441 88442 88443 88444 88445 88446 88447 88448 88449 88450 88451 88452 88453 88454 88455 88456 88457 88458 88459 88460 88461 88462 88463 88464 88465 88466 88467 88468 88469 88470 88471 88472 88473 88474 88475 88476 88477 88478 88479 88480 88481 88482 88483 88484 88485 88486 88487 88488 88489 88490 88491 88492 88493 88494 88495 88496 88497 88498 88499 88500 88501 88502 88503 88504 88505 88506 88507 88508 88509 88510 88511 88512 88513 88514 88515 88516 88517 88518 88519 88520 88521 88522 88523 88524 88525 88526 88527 88528 88529 88530 88531 88532 88533 88534 88535 88536 88537 88538 88539 88540 88541 88542 88543 88544 88545 88546 88547 88548 88549 88550 88551 88552 88553 88554 88555 88556 88557 88558 88559 88560 88561 88562 88563 88564 88565 88566 88567 88568 88569 88570 88571 88572 88573 88574 88575 88576 88577 88578 88579 88580 88581 88582 88583 88584 88585 88586 88587 88588 88589 88590 88591 88592 88593 88594 88595 88596 88597 88598 88599 88600 88601 88602 88603 88604 88605 88606 88607 88608 88609 88610 88611 88612 88613 88614 88615 88616 88617 88618 88619 88620 88621 88622 88623 88624 88625 88626 88627 88628 88629 88630 88631 88632 88633 88634 88635 88636 88637 88638 88639 88640 88641 88642 88643 88644 88645 88646 88647 88648 88649 88650 88651 88652 88653 88654 88655 88656 88657 88658 88659 88660 88661 88662 88663 88664 88665 88666 88667 88668 88669 88670 88671 88672 88673 88674 88675 88676 88677 88678 88679 88680 88681 88682 88683 88684 88685 88686 88687 88688 88689 88690 88691 88692 88693 88694 88695 88696 88697 88698 88699 88700 88701 88702 88703 88704 88705 88706 88707 88708 88709 88710 88711 88712 88713 88714 88715 88716 88717 88718 88719 88720 88721 88722 88723 88724 88725 88726 88727 88728 88729 88730 88731 88732 88733 88734 88735 88736 88737 88738 88739 88740 88741 88742 88743 88744 88745 88746 88747 88748 88749 88750 88751 88752 88753 88754 88755 88756 88757 88758 88759 88760 88761 88762 88763 88764 88765 88766 88767 88768 88769 88770 88771 88772 88773 88774 88775 88776 88777 88778 88779 88780 88781 88782 88783 88784 88785 88786 88787 88788 88789 88790 88791 88792 88793 88794 88795 88796 88797 88798 88799 88800 88801 88802 88803 88804 88805 88806 88807 88808 88809 88810 88811 88812 88813 88814 88815 88816 88817 88818 88819 88820 88821 88822 88823 88824 88825 88826 88827 88828 88829 88830 88831 88832 88833 88834 88835 88836 88837 88838 88839 88840 88841 88842 88843 88844 88845 88846 88847 88848 88849 88850 88851 88852 88853 88854 88855 88856 88857 88858 88859 88860 88861 88862 88863 88864 88865 88866 88867 88868 88869 88870 88871 88872 88873 88874 88875 88876 88877 88878 88879 88880 88881 88882 88883 88884 88885 88886 88887 88888 88889 88890 88891 88892 88893 88894 88895 88896 88897 88898 88899 88900 88901 88902 88903 88904 88905 88906 88907 88908 88909 88910 88911 88912 88913 88914 88915 88916 88917 88918 88919 88920 88921 88922 88923 88924 88925 88926 88927 88928 88929 88930 88931 88932 88933 88934 88935 88936 88937 88938 88939 88940 88941 88942 88943 88944 88945 88946 88947 88948 88949 88950 88951 88952 88953 88954 88955 88956 88957 88958 88959 88960 88961 88962 88963 88964 88965 88966 88967 88968 88969 88970 88971 88972 88973 88974 88975 88976 88977 88978 88979 88980 88981 88982 88983 88984 88985 88986 88987 88988 88989 88990 88991 88992 88993 88994 88995 88996 88997 88998 88999 89000 89001 89002 89003 89004 89005 89006 89007 89008 89009 89010 89011 89012 89013 89014 89015 89016 89017 89018 89019 89020 89021 89022 89023 89024 89025 89026 89027 89028 89029 89030 89031 89032 89033 89034 89035 89036 89037 89038 89039 89040 89041 89042 89043 89044 89045 89046 89047 89048 89049 89050 89051 89052 89053 89054 89055 89056 89057 89058 89059 89060 89061 89062 89063 89064 89065 89066 89067 89068 89069 89070 89071 89072 89073 89074 89075 89076 89077 89078 89079 89080 89081 89082 89083 89084 89085 89086 89087 89088 89089 89090 89091 89092 89093 89094 89095 89096 89097 89098 89099 89100 89101 89102 89103 89104 89105 89106 89107 89108 89109 89110 89111 89112 89113 89114 89115 89116 89117 89118 89119 89120 89121 89122 89123 89124 89125 89126 89127 89128 89129 89130 89131 89132 89133 89134 89135 89136 89137 89138 89139 89140 89141 89142 89143 89144 89145 89146 89147 89148 89149 89150 89151 89152 89153 89154 89155 89156 89157 89158 89159 89160 89161 89162 89163 89164 89165 89166 89167 89168 89169 89170 89171 89172 89173 89174 89175 89176 89177 89178 89179 89180 89181 89182 89183 89184 89185 89186 89187 89188 89189 89190 89191 89192 89193 89194 89195 89196 89197 89198 89199 89200 89201 89202 89203 89204 89205 89206 89207 89208 89209 89210 89211 89212 89213 89214 89215 89216 89217 89218 89219 89220 89221 89222 89223 89224 89225 89226 89227 89228 89229 89230 89231 89232 89233 89234 89235 89236 89237 89238 89239 89240 89241 89242 89243 89244 89245 89246 89247 89248 89249 89250 89251 89252 89253 89254 89255 89256 89257 89258 89259 89260 89261 89262 89263 89264 89265 89266 89267 89268 89269 89270 89271 89272 89273 89274 89275 89276 89277 89278 89279 89280 89281 89282 89283 89284 89285 89286 89287 89288 89289 89290 89291 89292 89293 89294 89295 89296 89297 89298 89299 89300 89301 89302 89303 89304 89305 89306 89307 89308 89309 89310 89311 89312 89313 89314 89315 89316 89317 89318 89319 89320 89321 89322 89323 89324 89325 89326 89327 89328 89329 89330 89331 89332 89333 89334 89335 89336 89337 89338 89339 89340 89341 89342 89343 89344 89345 89346 89347 89348 89349 89350 89351 89352 89353 89354 89355 89356 89357 89358 89359 89360 89361 89362 89363 89364 89365 89366 89367 89368 89369 89370 89371 89372 89373 89374 89375 89376 89377 89378 89379 89380 89381 89382 89383 89384 89385 89386 89387 89388 89389 89390 89391 89392 89393 89394 89395 89396 89397 89398 89399 89400 89401 89402 89403 89404 89405 89406 89407 89408 89409 89410 89411 89412 89413 89414 89415 89416 89417 89418 89419 89420 89421 89422 89423 89424 89425 89426 89427 89428 89429 89430 89431 89432 89433 89434 89435 89436 89437 89438 89439 89440 89441 89442 89443 89444 89445 89446 89447 89448 89449 89450 89451 89452 89453 89454 89455 89456 89457 89458 89459 89460 89461 89462 89463 89464 89465 89466 89467 89468 89469 89470 89471 89472 89473 89474 89475 89476 89477 89478 89479 89480 89481 89482 89483 89484 89485 89486 89487 89488 89489 89490 89491 89492 89493 89494 89495 89496 89497 89498 89499 89500 89501 89502 89503 89504 89505 89506 89507 89508 89509 89510 89511 89512 89513 89514 89515 89516 89517 89518 89519 89520 89521 89522 89523 89524 89525 89526 89527 89528 89529 89530 89531 89532 89533 89534 89535 89536 89537 89538 89539 89540 89541 89542 89543 89544 89545 89546 89547 89548 89549 89550 89551 89552 89553 89554 89555 89556 89557 89558 89559 89560 89561 89562 89563 89564 89565 89566 89567 89568 89569 89570 89571 89572 89573 89574 89575 89576 89577 89578 89579 89580 89581 89582 89583 89584 89585 89586 89587 89588 89589 89590 89591 89592 89593 89594 89595 89596 89597 89598 89599 89600 89601 89602 89603 89604 89605 89606 89607 89608 89609 89610 89611 89612 89613 89614 89615 89616 89617 89618 89619 89620 89621 89622 89623 89624 89625 89626 89627 89628 89629 89630 89631 89632 89633 89634 89635 89636 89637 89638 89639 89640 89641 89642 89643 89644 89645 89646 89647 89648 89649 89650 89651 89652 89653 89654 89655 89656 89657 89658 89659 89660 89661 89662 89663 89664 89665 89666 89667 89668 89669 89670 89671 89672 89673 89674 89675 89676 89677 89678 89679 89680 89681 89682 89683 89684 89685 89686 89687 89688 89689 89690 89691 89692 89693 89694 89695 89696 89697 89698 89699 89700 89701 89702 89703 89704 89705 89706 89707 89708 89709 89710 89711 89712 89713 89714 89715 89716 89717 89718 89719 89720 89721 89722 89723 89724 89725 89726 89727 89728 89729 89730 89731 89732 89733 89734 89735 89736 89737 89738 89739 89740 89741 89742 89743 89744 89745 89746 89747 89748 89749 89750 89751 89752 89753 89754 89755 89756 89757 89758 89759 89760 89761 89762 89763 89764 89765 89766 89767 89768 89769 89770 89771 89772 89773 89774 89775 89776 89777 89778 89779 89780 89781 89782 89783 89784 89785 89786 89787 89788 89789 89790 89791 89792 89793 89794 89795 89796 89797 89798 89799 89800 89801 89802 89803 89804 89805 89806 89807 89808 89809 89810 89811 89812 89813 89814 89815 89816 89817 89818 89819 89820 89821 89822 89823 89824 89825 89826 89827 89828 89829 89830 89831 89832 89833 89834 89835 89836 89837 89838 89839 89840 89841 89842 89843 89844 89845 89846 89847 89848 89849 89850 89851 89852 89853 89854 89855 89856 89857 89858 89859 89860 89861 89862 89863 89864 89865 89866 89867 89868 89869 89870 89871 89872 89873 89874 89875 89876 89877 89878 89879 89880 89881 89882 89883 89884 89885 89886 89887 89888 89889 89890 89891 89892 89893 89894 89895 89896 89897 89898 89899 89900 89901 89902 89903 89904 89905 89906 89907 89908 89909 89910 89911 89912 89913 89914 89915 89916 89917 89918 89919 89920 89921 89922 89923 89924 89925 89926 89927 89928 89929 89930 89931 89932 89933 89934 89935 89936 89937 89938 89939 89940 89941 89942 89943 89944 89945 89946 89947 89948 89949 89950 89951 89952 89953 89954 89955 89956 89957 89958 89959 89960 89961 89962 89963 89964 89965 89966 89967 89968 89969 89970 89971 89972 89973 89974 89975 89976 89977 89978 89979 89980 89981 89982 89983 89984 89985 89986 89987 89988 89989 89990 89991 89992 89993 89994 89995 89996 89997 89998 89999 90000 90001 90002 90003 90004 90005 90006 90007 90008 90009 90010 90011 90012 90013 90014 90015 90016 90017 90018 90019 90020 90021 90022 90023 90024 90025 90026 90027 90028 90029 90030 90031 90032 90033 90034 90035 90036 90037 90038 90039 90040 90041 90042 90043 90044 90045 90046 90047 90048 90049 90050 90051 90052 90053 90054 90055 90056 90057 90058 90059 90060 90061 90062 90063 90064 90065 90066 90067 90068 90069 90070 90071 90072 90073 90074 90075 90076 90077 90078 90079 90080 90081 90082 90083 90084 90085 90086 90087 90088 90089 90090 90091 90092 90093 90094 90095 90096 90097 90098 90099 90100 90101 90102 90103 90104 90105 90106 90107 90108 90109 90110 90111 90112 90113 90114 90115 90116 90117 90118 90119 90120 90121 90122 90123 90124 90125 90126 90127 90128 90129 90130 90131 90132 90133 90134 90135 90136 90137 90138 90139 90140 90141 90142 90143 90144 90145 90146 90147 90148 90149 90150 90151 90152 90153 90154 90155 90156 90157 90158 90159 90160 90161 90162 90163 90164 90165 90166 90167 90168 90169 90170 90171 90172 90173 90174 90175 90176 90177 90178 90179 90180 90181 90182 90183 90184 90185 90186 90187 90188 90189 90190 90191 90192 90193 90194 90195 90196 90197 90198 90199 90200 90201 90202 90203 90204 90205 90206 90207 90208 90209 90210 90211 90212 90213 90214 90215 90216 90217 90218 90219 90220 90221 90222 90223 90224 90225 90226 90227 90228 90229 90230 90231 90232 90233 90234 90235 90236 90237 90238 90239 90240 90241 90242 90243 90244 90245 90246 90247 90248 90249 90250 90251 90252 90253 90254 90255 90256 90257 90258 90259 90260 90261 90262 90263 90264 90265 90266 90267 90268 90269 90270 90271 90272 90273 90274 90275 90276 90277 90278 90279 90280 90281 90282 90283 90284 90285 90286 90287 90288 90289 90290 90291 90292 90293 90294 90295 90296 90297 90298 90299 90300 90301 90302 90303 90304 90305 90306 90307 90308 90309 90310 90311 90312 90313 90314 90315 90316 90317 90318 90319 90320 90321 90322 90323 90324 90325 90326 90327 90328 90329 90330 90331 90332 90333 90334 90335 90336 90337 90338 90339 90340 90341 90342 90343 90344 90345 90346 90347 90348 90349 90350 90351 90352 90353 90354 90355 90356 90357 90358 90359 90360 90361 90362 90363 90364 90365 90366 90367 90368 90369 90370 90371 90372 90373 90374 90375 90376 90377 90378 90379 90380 90381 90382 90383 90384 90385 90386 90387 90388 90389 90390 90391 90392 90393 90394 90395 90396 90397 90398 90399 90400 90401 90402 90403 90404 90405 90406 90407 90408 90409 90410 90411 90412 90413 90414 90415 90416 90417 90418 90419 90420 90421 90422 90423 90424 90425 90426 90427 90428 90429 90430 90431 90432 90433 90434 90435 90436 90437 90438 90439 90440 90441 90442 90443 90444 90445 90446 90447 90448 90449 90450 90451 90452 90453 90454 90455 90456 90457 90458 90459 90460 90461 90462 90463 90464 90465 90466 90467 90468 90469 90470 90471 90472 90473 90474 90475 90476 90477 90478 90479 90480 90481 90482 90483 90484 90485 90486 90487 90488 90489 90490 90491 90492 90493 90494 90495 90496 90497 90498 90499 90500 90501 90502 90503 90504 90505 90506 90507 90508 90509 90510 90511 90512 90513 90514 90515 90516 90517 90518 90519 90520 90521 90522 90523 90524 90525 90526 90527 90528 90529 90530 90531 90532 90533 90534 90535 90536 90537 90538 90539 90540 90541 90542 90543 90544 90545 90546 90547 90548 90549 90550 90551 90552 90553 90554 90555 90556 90557 90558 90559 90560 90561 90562 90563 90564 90565 90566 90567 90568 90569 90570 90571 90572 90573 90574 90575 90576 90577 90578 90579 90580 90581 90582 90583 90584 90585 90586 90587 90588 90589 90590 90591 90592 90593 90594 90595 90596 90597 90598 90599 90600 90601 90602 90603 90604 90605 90606 90607 90608 90609 90610 90611 90612 90613 90614 90615 90616 90617 90618 90619 90620 90621 90622 90623 90624 90625 90626 90627 90628 90629 90630 90631 90632 90633 90634 90635 90636 90637 90638 90639 90640 90641 90642 90643 90644 90645 90646 90647 90648 90649 90650 90651 90652 90653 90654 90655 90656 90657 90658 90659 90660 90661 90662 90663 90664 90665 90666 90667 90668 90669 90670 90671 90672 90673 90674 90675 90676 90677 90678 90679 90680 90681 90682 90683 90684 90685 90686 90687 90688 90689 90690 90691 90692 90693 90694 90695 90696 90697 90698 90699 90700 90701 90702 90703 90704 90705 90706 90707 90708 90709 90710 90711 90712 90713 90714 90715 90716 90717 90718 90719 90720 90721 90722 90723 90724 90725 90726 90727 90728 90729 90730 90731 90732 90733 90734 90735 90736 90737 90738 90739 90740 90741 90742 90743 90744 90745 90746 90747 90748 90749 90750 90751 90752 90753 90754 90755 90756 90757 90758 90759 90760 90761 90762 90763 90764 90765 90766 90767 90768 90769 90770 90771 90772 90773 90774 90775 90776 90777 90778 90779 90780 90781 90782 90783 90784 90785 90786 90787 90788 90789 90790 90791 90792 90793 90794 90795 90796 90797 90798 90799 90800 90801 90802 90803 90804 90805 90806 90807 90808 90809 90810 90811 90812 90813 90814 90815 90816 90817 90818 90819 90820 90821 90822 90823 90824 90825 90826 90827 90828 90829 90830 90831 90832 90833 90834 90835 90836 90837 90838 90839 90840 90841 90842 90843 90844 90845 90846 90847 90848 90849 90850 90851 90852 90853 90854 90855 90856 90857 90858 90859 90860 90861 90862 90863 90864 90865 90866 90867 90868 90869 90870 90871 90872 90873 90874 90875 90876 90877 90878 90879 90880 90881 90882 90883 90884 90885 90886 90887 90888 90889 90890 90891 90892 90893 90894 90895 90896 90897 90898 90899 90900 90901 90902 90903 90904 90905 90906 90907 90908 90909 90910 90911 90912 90913 90914 90915 90916 90917 90918 90919 90920 90921 90922 90923 90924 90925 90926 90927 90928 90929 90930 90931 90932 90933 90934 90935 90936 90937 90938 90939 90940 90941 90942 90943 90944 90945 90946 90947 90948 90949 90950 90951 90952 90953 90954 90955 90956 90957 90958 90959 90960 90961 90962 90963 90964 90965 90966 90967 90968 90969 90970 90971 90972 90973 90974 90975 90976 90977 90978 90979 90980 90981 90982 90983 90984 90985 90986 90987 90988 90989 90990 90991 90992 90993 90994 90995 90996 90997 90998 90999 91000 91001 91002 91003 91004 91005 91006 91007 91008 91009 91010 91011 91012 91013 91014 91015 91016 91017 91018 91019 91020 91021 91022 91023 91024 91025 91026 91027 91028 91029 91030 91031 91032 91033 91034 91035 91036 91037 91038 91039 91040 91041 91042 91043 91044 91045 91046 91047 91048 91049 91050 91051 91052 91053 91054 91055 91056 91057 91058 91059 91060 91061 91062 91063 91064 91065 91066 91067 91068 91069 91070 91071 91072 91073 91074 91075 91076 91077 91078 91079 91080 91081 91082 91083 91084 91085 91086 91087 91088 91089 91090 91091 91092 91093 91094 91095 91096 91097 91098 91099 91100 91101 91102 91103 91104 91105 91106 91107 91108 91109 91110 91111 91112 91113 91114 91115 91116 91117 91118 91119 91120 91121 91122 91123 91124 91125 91126 91127 91128 91129 91130 91131 91132 91133 91134 91135 91136 91137 91138 91139 91140 91141 91142 91143 91144 91145 91146 91147 91148 91149 91150 91151 91152 91153 91154 91155 91156 91157 91158 91159 91160 91161 91162 91163 91164 91165 91166 91167 91168 91169 91170 91171 91172 91173 91174 91175 91176 91177 91178 91179 91180 91181 91182 91183 91184 91185 91186 91187 91188 91189 91190 91191 91192 91193 91194 91195 91196 91197 91198 91199 91200 91201 91202 91203 91204 91205 91206 91207 91208 91209 91210 91211 91212 91213 91214 91215 91216 91217 91218 91219 91220 91221 91222 91223 91224 91225 91226 91227 91228 91229 91230 91231 91232 91233 91234 91235 91236 91237 91238 91239 91240 91241 91242 91243 91244 91245 91246 91247 91248 91249 91250 91251 91252 91253 91254 91255 91256 91257 91258 91259 91260 91261 91262 91263 91264 91265 91266 91267 91268 91269 91270 91271 91272 91273 91274 91275 91276 91277 91278 91279 91280 91281 91282 91283 91284 91285 91286 91287 91288 91289 91290 91291 91292 91293 91294 91295 91296 91297 91298 91299 91300 91301 91302 91303 91304 91305 91306 91307 91308 91309 91310 91311 91312 91313 91314 91315 91316 91317 91318 91319 91320 91321 91322 91323 91324 91325 91326 91327 91328 91329 91330 91331 91332 91333 91334 91335 91336 91337 91338 91339 91340 91341 91342 91343 91344 91345 91346 91347 91348 91349 91350 91351 91352 91353 91354 91355 91356 91357 91358 91359 91360 91361 91362 91363 91364 91365 91366 91367 91368 91369 91370 91371 91372 91373 91374 91375 91376 91377 91378 91379 91380 91381 91382 91383 91384 91385 91386 91387 91388 91389 91390 91391 91392 91393 91394 91395 91396 91397 91398 91399 91400 91401 91402 91403 91404 91405 91406 91407 91408 91409 91410 91411 91412 91413 91414 91415 91416 91417 91418 91419 91420 91421 91422 91423 91424 91425 91426 91427 91428 91429 91430 91431 91432 91433 91434 91435 91436 91437 91438 91439 91440 91441 91442 91443 91444 91445 91446 91447 91448 91449 91450 91451 91452 91453 91454 91455 91456 91457 91458 91459 91460 91461 91462 91463 91464 91465 91466 91467 91468 91469 91470 91471 91472 91473 91474 91475 91476 91477 91478 91479 91480 91481 91482 91483 91484 91485 91486 91487 91488 91489 91490 91491 91492 91493 91494 91495 91496 91497 91498 91499 91500 91501 91502 91503 91504 91505 91506 91507 91508 91509 91510 91511 91512 91513 91514 91515 91516 91517 91518 91519 91520 91521 91522 91523 91524 91525 91526 91527 91528 91529 91530 91531 91532 91533 91534 91535 91536 91537 91538 91539 91540 91541 91542 91543 91544 91545 91546 91547 91548 91549 91550 91551 91552 91553 91554 91555 91556 91557 91558 91559 91560 91561 91562 91563 91564 91565 91566 91567 91568 91569 91570 91571 91572 91573 91574 91575 91576 91577 91578 91579 91580 91581 91582 91583 91584 91585 91586 91587 91588 91589 91590 91591 91592 91593 91594 91595 91596 91597 91598 91599 91600 91601 91602 91603 91604 91605 91606 91607 91608 91609 91610 91611 91612 91613 91614 91615 91616 91617 91618 91619 91620 91621 91622 91623 91624 91625 91626 91627 91628 91629 91630 91631 91632 91633 91634 91635 91636 91637 91638 91639 91640 91641 91642 91643 91644 91645 91646 91647 91648 91649 91650 91651 91652 91653 91654 91655 91656 91657 91658 91659 91660 91661 91662 91663 91664 91665 91666 91667 91668 91669 91670 91671 91672 91673 91674 91675 91676 91677 91678 91679 91680 91681 91682 91683 91684 91685 91686 91687 91688 91689 91690 91691 91692 91693 91694 91695 91696 91697 91698 91699 91700 91701 91702 91703 91704 91705 91706 91707 91708 91709 91710 91711 91712 91713 91714 91715 91716 91717 91718 91719 91720 91721 91722 91723 91724 91725 91726 91727 91728 91729 91730 91731 91732 91733 91734 91735 91736 91737 91738 91739 91740 91741 91742 91743 91744 91745 91746 91747 91748 91749 91750 91751 91752 91753 91754 91755 91756 91757 91758 91759 91760 91761 91762 91763 91764 91765 91766 91767 91768 91769 91770 91771 91772 91773 91774 91775 91776 91777 91778 91779 91780 91781 91782 91783 91784 91785 91786 91787 91788 91789 91790 91791 91792 91793 91794 91795 91796 91797 91798 91799 91800 91801 91802 91803 91804 91805 91806 91807 91808 91809 91810 91811 91812 91813 91814 91815 91816 91817 91818 91819 91820 91821 91822 91823 91824 91825 91826 91827 91828 91829 91830 91831 91832 91833 91834 91835 91836 91837 91838 91839 91840 91841 91842 91843 91844 91845 91846 91847 91848 91849 91850 91851 91852 91853 91854 91855 91856 91857 91858 91859 91860 91861 91862 91863 91864 91865 91866 91867 91868 91869 91870 91871 91872 91873 91874 91875 91876 91877 91878 91879 91880 91881 91882 91883 91884 91885 91886 91887 91888 91889 91890 91891 91892 91893 91894 91895 91896 91897 91898 91899 91900 91901 91902 91903 91904 91905 91906 91907 91908 91909 91910 91911 91912 91913 91914 91915 91916 91917 91918 91919 91920 91921 91922 91923 91924 91925 91926 91927 91928 91929 91930 91931 91932 91933 91934 91935 91936 91937 91938 91939 91940 91941 91942 91943 91944 91945 91946 91947 91948 91949 91950 91951 91952 91953 91954 91955 91956 91957 91958 91959 91960 91961 91962 91963 91964 91965 91966 91967 91968 91969 91970 91971 91972 91973 91974 91975 91976 91977 91978 91979 91980 91981 91982 91983 91984 91985 91986 91987 91988 91989 91990 91991 91992 91993 91994 91995 91996 91997 91998 91999 92000 92001 92002 92003 92004 92005 92006 92007 92008 92009 92010 92011 92012 92013 92014 92015 92016 92017 92018 92019 92020 92021 92022 92023 92024 92025 92026 92027 92028 92029 92030 92031 92032 92033 92034 92035 92036 92037 92038 92039 92040 92041 92042 92043 92044 92045 92046 92047 92048 92049 92050 92051 92052 92053 92054 92055 92056 92057 92058 92059 92060 92061 92062 92063 92064 92065 92066 92067 92068 92069 92070 92071 92072 92073 92074 92075 92076 92077 92078 92079 92080 92081 92082 92083 92084 92085 92086 92087 92088 92089 92090 92091 92092 92093 92094 92095 92096 92097 92098 92099 92100 92101 92102 92103 92104 92105 92106 92107 92108 92109 92110 92111 92112 92113 92114 92115 92116 92117 92118 92119 92120 92121 92122 92123 92124 92125 92126 92127 92128 92129 92130 92131 92132 92133 92134 92135 92136 92137 92138 92139 92140 92141 92142 92143 92144 92145 92146 92147 92148 92149 92150 92151 92152 92153 92154 92155 92156 92157 92158 92159 92160 92161 92162 92163 92164 92165 92166 92167 92168 92169 92170 92171 92172 92173 92174 92175 92176 92177 92178 92179 92180 92181 92182 92183 92184 92185 92186 92187 92188 92189 92190 92191 92192 92193 92194 92195 92196 92197 92198 92199 92200 92201 92202 92203 92204 92205 92206 92207 92208 92209 92210 92211 92212 92213 92214 92215 92216 92217 92218 92219 92220 92221 92222 92223 92224 92225 92226 92227 92228 92229 92230 92231 92232 92233 92234 92235 92236 92237 92238 92239 92240 92241 92242 92243 92244 92245 92246 92247 92248 92249 92250 92251 92252 92253 92254 92255 92256 92257 92258 92259 92260 92261 92262 92263 92264 92265 92266 92267 92268 92269 92270 92271 92272 92273 92274 92275 92276 92277 92278 92279 92280 92281 92282 92283 92284 92285 92286 92287 92288 92289 92290 92291 92292 92293 92294 92295 92296 92297 92298 92299 92300 92301 92302 92303 92304 92305 92306 92307 92308 92309 92310 92311 92312 92313 92314 92315 92316 92317 92318 92319 92320 92321 92322 92323 92324 92325 92326 92327 92328 92329 92330 92331 92332 92333 92334 92335 92336 92337 92338 92339 92340 92341 92342 92343 92344 92345 92346 92347 92348 92349 92350 92351 92352 92353 92354 92355 92356 92357 92358 92359 92360 92361 92362 92363 92364 92365 92366 92367 92368 92369 92370 92371 92372 92373 92374 92375 92376 92377 92378 92379 92380 92381 92382 92383 92384 92385 92386 92387 92388 92389 92390 92391 92392 92393 92394 92395 92396 92397 92398 92399 92400 92401 92402 92403 92404 92405 92406 92407 92408 92409 92410 92411 92412 92413 92414 92415 92416 92417 92418 92419 92420 92421 92422 92423 92424 92425 92426 92427 92428 92429 92430 92431 92432 92433 92434 92435 92436 92437 92438 92439 92440 92441 92442 92443 92444 92445 92446 92447 92448 92449 92450 92451 92452 92453 92454 92455 92456 92457 92458 92459 92460 92461 92462 92463 92464 92465 92466 92467 92468 92469 92470 92471 92472 92473 92474 92475 92476 92477 92478 92479 92480 92481 92482 92483 92484 92485 92486 92487 92488 92489 92490 92491 92492 92493 92494 92495 92496 92497 92498 92499 92500 92501 92502 92503 92504 92505 92506 92507 92508 92509 92510 92511 92512 92513 92514 92515 92516 92517 92518 92519 92520 92521 92522 92523 92524 92525 92526 92527 92528 92529 92530 92531 92532 92533 92534 92535 92536 92537 92538 92539 92540 92541 92542 92543 92544 92545 92546 92547 92548 92549 92550 92551 92552 92553 92554 92555 92556 92557 92558 92559 92560 92561 92562 92563 92564 92565 92566 92567 92568 92569 92570 92571 92572 92573 92574 92575 92576 92577 92578 92579 92580 92581 92582 92583 92584 92585 92586 92587 92588 92589 92590 92591 92592 92593 92594 92595 92596 92597 92598 92599 92600 92601 92602 92603 92604 92605 92606 92607 92608 92609 92610 92611 92612 92613 92614 92615 92616 92617 92618 92619 92620 92621 92622 92623 92624 92625 92626 92627 92628 92629 92630 92631 92632 92633 92634 92635 92636 92637 92638 92639 92640 92641 92642 92643 92644 92645 92646 92647 92648 92649 92650 92651 92652 92653 92654 92655 92656 92657 92658 92659 92660 92661 92662 92663 92664 92665 92666 92667 92668 92669 92670 92671 92672 92673 92674 92675 92676 92677 92678 92679 92680 92681 92682 92683 92684 92685 92686 92687 92688 92689 92690 92691 92692 92693 92694 92695 92696 92697 92698 92699 92700 92701 92702 92703 92704 92705 92706 92707 92708 92709 92710 92711 92712 92713 92714 92715 92716 92717 92718 92719 92720 92721 92722 92723 92724 92725 92726 92727 92728 92729 92730 92731 92732 92733 92734 92735 92736 92737 92738 92739 92740 92741 92742 92743 92744 92745 92746 92747 92748 92749 92750 92751 92752 92753 92754 92755 92756 92757 92758 92759 92760 92761 92762 92763 92764 92765 92766 92767 92768 92769 92770 92771 92772 92773 92774 92775 92776 92777 92778 92779 92780 92781 92782 92783 92784 92785 92786 92787 92788 92789 92790 92791 92792 92793 92794 92795 92796 92797 92798 92799 92800 92801 92802 92803 92804 92805 92806 92807 92808 92809 92810 92811 92812 92813 92814 92815 92816 92817 92818 92819 92820 92821 92822 92823 92824 92825 92826 92827 92828 92829 92830 92831 92832 92833 92834 92835 92836 92837 92838 92839 92840 92841 92842 92843 92844 92845 92846 92847 92848 92849 92850 92851 92852 92853 92854 92855 92856 92857 92858 92859 92860 92861 92862 92863 92864 92865 92866 92867 92868 92869 92870 92871 92872 92873 92874 92875 92876 92877 92878 92879 92880 92881 92882 92883 92884 92885 92886 92887 92888 92889 92890 92891 92892 92893 92894 92895 92896 92897 92898 92899 92900 92901 92902 92903 92904 92905 92906 92907 92908 92909 92910 92911 92912 92913 92914 92915 92916 92917 92918 92919 92920 92921 92922 92923 92924 92925 92926 92927 92928 92929 92930 92931 92932 92933 92934 92935 92936 92937 92938 92939 92940 92941 92942 92943 92944 92945 92946 92947 92948 92949 92950 92951 92952 92953 92954 92955 92956 92957 92958 92959 92960 92961 92962 92963 92964 92965 92966 92967 92968 92969 92970 92971 92972 92973 92974 92975 92976 92977 92978 92979 92980 92981 92982 92983 92984 92985 92986 92987 92988 92989 92990 92991 92992 92993 92994 92995 92996 92997 92998 92999 93000 93001 93002 93003 93004 93005 93006 93007 93008 93009 93010 93011 93012 93013 93014 93015 93016 93017 93018 93019 93020 93021 93022 93023 93024 93025 93026 93027 93028 93029 93030 93031 93032 93033 93034 93035 93036 93037 93038 93039 93040 93041 93042 93043 93044 93045 93046 93047 93048 93049 93050 93051 93052 93053 93054 93055 93056 93057 93058 93059 93060 93061 93062 93063 93064 93065 93066 93067 93068 93069 93070 93071 93072 93073 93074 93075 93076 93077 93078 93079 93080 93081 93082 93083 93084 93085 93086 93087 93088 93089 93090 93091 93092 93093 93094 93095 93096 93097 93098 93099 93100 93101 93102 93103 93104 93105 93106 93107 93108 93109 93110 93111 93112 93113 93114 93115 93116 93117 93118 93119 93120 93121 93122 93123 93124 93125 93126 93127 93128 93129 93130 93131 93132 93133 93134 93135 93136 93137 93138 93139 93140 93141 93142 93143 93144 93145 93146 93147 93148 93149 93150 93151 93152 93153 93154 93155 93156 93157 93158 93159 93160 93161 93162 93163 93164 93165 93166 93167 93168 93169 93170 93171 93172 93173 93174 93175 93176 93177 93178 93179 93180 93181 93182 93183 93184 93185 93186 93187 93188 93189 93190 93191 93192 93193 93194 93195 93196 93197 93198 93199 93200 93201 93202 93203 93204 93205 93206 93207 93208 93209 93210 93211 93212 93213 93214 93215 93216 93217 93218 93219 93220 93221 93222 93223 93224 93225 93226 93227 93228 93229 93230 93231 93232 93233 93234 93235 93236 93237 93238 93239 93240 93241 93242 93243 93244 93245 93246 93247 93248 93249 93250 93251 93252 93253 93254 93255 93256 93257 93258 93259 93260 93261 93262 93263 93264 93265 93266 93267 93268 93269 93270 93271 93272 93273 93274 93275 93276 93277 93278 93279 93280 93281 93282 93283 93284 93285 93286 93287 93288 93289 93290 93291 93292 93293 93294 93295 93296 93297 93298 93299 93300 93301 93302 93303 93304 93305 93306 93307 93308 93309 93310 93311 93312 93313 93314 93315 93316 93317 93318 93319 93320 93321 93322 93323 93324 93325 93326 93327 93328 93329 93330 93331 93332 93333 93334 93335 93336 93337 93338 93339 93340 93341 93342 93343 93344 93345 93346 93347 93348 93349 93350 93351 93352 93353 93354 93355 93356 93357 93358 93359 93360 93361 93362 93363 93364 93365 93366 93367 93368 93369 93370 93371 93372 93373 93374 93375 93376 93377 93378 93379 93380 93381 93382 93383 93384 93385 93386 93387 93388 93389 93390 93391 93392 93393 93394 93395 93396 93397 93398 93399 93400 93401 93402 93403 93404 93405 93406 93407 93408 93409 93410 93411 93412 93413 93414 93415 93416 93417 93418 93419 93420 93421 93422 93423 93424 93425 93426 93427 93428 93429 93430 93431 93432 93433 93434 93435 93436 93437 93438 93439 93440 93441 93442 93443 93444 93445 93446 93447 93448 93449 93450 93451 93452 93453 93454 93455 93456 93457 93458 93459 93460 93461 93462 93463 93464 93465 93466 93467 93468 93469 93470 93471 93472 93473 93474 93475 93476 93477 93478 93479 93480 93481 93482 93483 93484 93485 93486 93487 93488 93489 93490 93491 93492 93493 93494 93495 93496 93497 93498 93499 93500 93501 93502 93503 93504 93505 93506 93507 93508 93509 93510 93511 93512 93513 93514 93515 93516 93517 93518 93519 93520 93521 93522 93523 93524 93525 93526 93527 93528 93529 93530 93531 93532 93533 93534 93535 93536 93537 93538 93539 93540 93541 93542 93543 93544 93545 93546 93547 93548 93549 93550 93551 93552 93553 93554 93555 93556 93557 93558 93559 93560 93561 93562 93563 93564 93565 93566 93567 93568 93569 93570 93571 93572 93573 93574 93575 93576 93577 93578 93579 93580 93581 93582 93583 93584 93585 93586 93587 93588 93589 93590 93591 93592 93593 93594 93595 93596 93597 93598 93599 93600 93601 93602 93603 93604 93605 93606 93607 93608 93609 93610 93611 93612 93613 93614 93615 93616 93617 93618 93619 93620 93621 93622 93623 93624 93625 93626 93627 93628 93629 93630 93631 93632 93633 93634 93635 93636 93637 93638 93639 93640 93641 93642 93643 93644 93645 93646 93647 93648 93649 93650 93651 93652 93653 93654 93655 93656 93657 93658 93659 93660 93661 93662 93663 93664 93665 93666 93667 93668 93669 93670 93671 93672 93673 93674 93675 93676 93677 93678 93679 93680 93681 93682 93683 93684 93685 93686 93687 93688 93689 93690 93691 93692 93693 93694 93695 93696 93697 93698 93699 93700 93701 93702 93703 93704 93705 93706 93707 93708 93709 93710 93711 93712 93713 93714 93715 93716 93717 93718 93719 93720 93721 93722 93723 93724 93725 93726 93727 93728 93729 93730 93731 93732 93733 93734 93735 93736 93737 93738 93739 93740 93741 93742 93743 93744 93745 93746 93747 93748 93749 93750 93751 93752 93753 93754 93755 93756 93757 93758 93759 93760 93761 93762 93763 93764 93765 93766 93767 93768 93769 93770 93771 93772 93773 93774 93775 93776 93777 93778 93779 93780 93781 93782 93783 93784 93785 93786 93787 93788 93789 93790 93791 93792 93793 93794 93795 93796 93797 93798 93799 93800 93801 93802 93803 93804 93805 93806 93807 93808 93809 93810 93811 93812 93813 93814 93815 93816 93817 93818 93819 93820 93821 93822 93823 93824 93825 93826 93827 93828 93829 93830 93831 93832 93833 93834 93835 93836 93837 93838 93839 93840 93841 93842 93843 93844 93845 93846 93847 93848 93849 93850 93851 93852 93853 93854 93855 93856 93857 93858 93859 93860 93861 93862 93863 93864 93865 93866 93867 93868 93869 93870 93871 93872 93873 93874 93875 93876 93877 93878 93879 93880 93881 93882 93883 93884 93885 93886 93887 93888 93889 93890 93891 93892 93893 93894 93895 93896 93897 93898 93899 93900 93901 93902 93903 93904 93905 93906 93907 93908 93909 93910 93911 93912 93913 93914 93915 93916 93917 93918 93919 93920 93921 93922 93923 93924 93925 93926 93927 93928 93929 93930 93931 93932 93933 93934 93935 93936 93937 93938 93939 93940 93941 93942 93943 93944 93945 93946 93947 93948 93949 93950 93951 93952 93953 93954 93955 93956 93957 93958 93959 93960 93961 93962 93963 93964 93965 93966 93967 93968 93969 93970 93971 93972 93973 93974 93975 93976 93977 93978 93979 93980 93981 93982 93983 93984 93985 93986 93987 93988 93989 93990 93991 93992 93993 93994 93995 93996 93997 93998 93999 94000 94001 94002 94003 94004 94005 94006 94007 94008 94009 94010 94011 94012 94013 94014 94015 94016 94017 94018 94019 94020 94021 94022 94023 94024 94025 94026 94027 94028 94029 94030 94031 94032 94033 94034 94035 94036 94037 94038 94039 94040 94041 94042 94043 94044 94045 94046 94047 94048 94049 94050 94051 94052 94053 94054 94055 94056 94057 94058 94059 94060 94061 94062 94063 94064 94065 94066 94067 94068 94069 94070 94071 94072 94073 94074 94075 94076 94077 94078 94079 94080 94081 94082 94083 94084 94085 94086 94087 94088 94089 94090 94091 94092 94093 94094 94095 94096 94097 94098 94099 94100 94101 94102 94103 94104 94105 94106 94107 94108 94109 94110 94111 94112 94113 94114 94115 94116 94117 94118 94119 94120 94121 94122 94123 94124 94125 94126 94127 94128 94129 94130 94131 94132 94133 94134 94135 94136 94137 94138 94139 94140 94141 94142 94143 94144 94145 94146 94147 94148 94149 94150 94151 94152 94153 94154 94155 94156 94157 94158 94159 94160 94161 94162 94163 94164 94165 94166 94167 94168 94169 94170 94171 94172 94173 94174 94175 94176 94177 94178 94179 94180 94181 94182 94183 94184 94185 94186 94187 94188 94189 94190 94191 94192 94193 94194 94195 94196 94197 94198 94199 94200 94201 94202 94203 94204 94205 94206 94207 94208 94209 94210 94211 94212 94213 94214 94215 94216 94217 94218 94219 94220 94221 94222 94223 94224 94225 94226 94227 94228 94229 94230 94231 94232 94233 94234 94235 94236 94237 94238 94239 94240 94241 94242 94243 94244 94245 94246 94247 94248 94249 94250 94251 94252 94253 94254 94255 94256 94257 94258 94259 94260 94261 94262 94263 94264 94265 94266 94267 94268 94269 94270 94271 94272 94273 94274 94275 94276 94277 94278 94279 94280 94281 94282 94283 94284 94285 94286 94287 94288 94289 94290 94291 94292 94293 94294 94295 94296 94297 94298 94299 94300 94301 94302 94303 94304 94305 94306 94307 94308 94309 94310 94311 94312 94313 94314 94315 94316 94317 94318 94319 94320 94321 94322 94323 94324 94325 94326 94327 94328 94329 94330 94331 94332 94333 94334 94335 94336 94337 94338 94339 94340 94341 94342 94343 94344 94345 94346 94347 94348 94349 94350 94351 94352 94353 94354 94355 94356 94357 94358 94359 94360 94361 94362 94363 94364 94365 94366 94367 94368 94369 94370 94371 94372 94373 94374 94375 94376 94377 94378 94379 94380 94381 94382 94383 94384 94385 94386 94387 94388 94389 94390 94391 94392 94393 94394 94395 94396 94397 94398 94399 94400 94401 94402 94403 94404 94405 94406 94407 94408 94409 94410 94411 94412 94413 94414 94415 94416 94417 94418 94419 94420 94421 94422 94423 94424 94425 94426 94427 94428 94429 94430 94431 94432 94433 94434 94435 94436 94437 94438 94439 94440 94441 94442 94443 94444 94445 94446 94447 94448 94449 94450 94451 94452 94453 94454 94455 94456 94457 94458 94459 94460 94461 94462 94463 94464 94465 94466 94467 94468 94469 94470 94471 94472 94473 94474 94475 94476 94477 94478 94479 94480 94481 94482 94483 94484 94485 94486 94487 94488 94489 94490 94491 94492 94493 94494 94495 94496 94497 94498 94499 94500 94501 94502 94503 94504 94505 94506 94507 94508 94509 94510 94511 94512 94513 94514 94515 94516 94517 94518 94519 94520 94521 94522 94523 94524 94525 94526 94527 94528 94529 94530 94531 94532 94533 94534 94535 94536 94537 94538 94539 94540 94541 94542 94543 94544 94545 94546 94547 94548 94549 94550 94551 94552 94553 94554 94555 94556 94557 94558 94559 94560 94561 94562 94563 94564 94565 94566 94567 94568 94569 94570 94571 94572 94573 94574 94575 94576 94577 94578 94579 94580 94581 94582 94583 94584 94585 94586 94587 94588 94589 94590 94591 94592 94593 94594 94595 94596 94597 94598 94599 94600 94601 94602 94603 94604 94605 94606 94607 94608 94609 94610 94611 94612 94613 94614 94615 94616 94617 94618 94619 94620 94621 94622 94623 94624 94625 94626 94627 94628 94629 94630 94631 94632 94633 94634 94635 94636 94637 94638 94639 94640 94641 94642 94643 94644 94645 94646 94647 94648 94649 94650 94651 94652 94653 94654 94655 94656 94657 94658 94659 94660 94661 94662 94663 94664 94665 94666 94667 94668 94669 94670 94671 94672 94673 94674 94675 94676 94677 94678 94679 94680 94681 94682 94683 94684 94685 94686 94687 94688 94689 94690 94691 94692 94693 94694 94695 94696 94697 94698 94699 94700 94701 94702 94703 94704 94705 94706 94707 94708 94709 94710 94711 94712 94713 94714 94715 94716 94717 94718 94719 94720 94721 94722 94723 94724 94725 94726 94727 94728 94729 94730 94731 94732 94733 94734 94735 94736 94737 94738 94739 94740 94741 94742 94743 94744 94745 94746 94747 94748 94749 94750 94751 94752 94753 94754 94755 94756 94757 94758 94759 94760 94761 94762 94763 94764 94765 94766 94767 94768 94769 94770 94771 94772 94773 94774 94775 94776 94777 94778 94779 94780 94781 94782 94783 94784 94785 94786 94787 94788 94789 94790 94791 94792 94793 94794 94795 94796 94797 94798 94799 94800 94801 94802 94803 94804 94805 94806 94807 94808 94809 94810 94811 94812 94813 94814 94815 94816 94817 94818 94819 94820 94821 94822 94823 94824 94825 94826 94827 94828 94829 94830 94831 94832 94833 94834 94835 94836 94837 94838 94839 94840 94841 94842 94843 94844 94845 94846 94847 94848 94849 94850 94851 94852 94853 94854 94855 94856 94857 94858 94859 94860 94861 94862 94863 94864 94865 94866 94867 94868 94869 94870 94871 94872 94873 94874 94875 94876 94877 94878 94879 94880 94881 94882 94883 94884 94885 94886 94887 94888 94889 94890 94891 94892 94893 94894 94895 94896 94897 94898 94899 94900 94901 94902 94903 94904 94905 94906 94907 94908 94909 94910 94911 94912 94913 94914 94915 94916 94917 94918 94919 94920 94921 94922 94923 94924 94925 94926 94927 94928 94929 94930 94931 94932 94933 94934 94935 94936 94937 94938 94939 94940 94941 94942 94943 94944 94945 94946 94947 94948 94949 94950 94951 94952 94953 94954 94955 94956 94957 94958 94959 94960 94961 94962 94963 94964 94965 94966 94967 94968 94969 94970 94971 94972 94973 94974 94975 94976 94977 94978 94979 94980 94981 94982 94983 94984 94985 94986 94987 94988 94989 94990 94991 94992 94993 94994 94995 94996 94997 94998 94999 95000 95001 95002 95003 95004 95005 95006 95007 95008 95009 95010 95011 95012 95013 95014 95015 95016 95017 95018 95019 95020 95021 95022 95023 95024 95025 95026 95027 95028 95029 95030 95031 95032 95033 95034 95035 95036 95037 95038 95039 95040 95041 95042 95043 95044 95045 95046 95047 95048 95049 95050 95051 95052 95053 95054 95055 95056 95057 95058 95059 95060 95061 95062 95063 95064 95065 95066 95067 95068 95069 95070 95071 95072 95073 95074 95075 95076 95077 95078 95079 95080 95081 95082 95083 95084 95085 95086 95087 95088 95089 95090 95091 95092 95093 95094 95095 95096 95097 95098 95099 95100 95101 95102 95103 95104 95105 95106 95107 95108 95109 95110 95111 95112 95113 95114 95115 95116 95117 95118 95119 95120 95121 95122 95123 95124 95125 95126 95127 95128 95129 95130 95131 95132 95133 95134 95135 95136 95137 95138 95139 95140 95141 95142 95143 95144 95145 95146 95147 95148 95149 95150 95151 95152 95153 95154 95155 95156 95157 95158 95159 95160 95161 95162 95163 95164 95165 95166 95167 95168 95169 95170 95171 95172 95173 95174 95175 95176 95177 95178 95179 95180 95181 95182 95183 95184 95185 95186 95187 95188 95189 95190 95191 95192 95193 95194 95195 95196 95197 95198 95199 95200 95201 95202 95203 95204 95205 95206 95207 95208 95209 95210 95211 95212 95213 95214 95215 95216 95217 95218 95219 95220 95221 95222 95223 95224 95225 95226 95227 95228 95229 95230 95231 95232 95233 95234 95235 95236 95237 95238 95239 95240 95241 95242 95243 95244 95245 95246 95247 95248 95249 95250 95251 95252 95253 95254 95255 95256 95257 95258 95259 95260 95261 95262 95263 95264 95265 95266 95267 95268 95269 95270 95271 95272 95273 95274 95275 95276 95277 95278 95279 95280 95281 95282 95283 95284 95285 95286 95287 95288 95289 95290 95291 95292 95293 95294 95295 95296 95297 95298 95299 95300 95301 95302 95303 95304 95305 95306 95307 95308 95309 95310 95311 95312 95313 95314 95315 95316 95317 95318 95319 95320 95321 95322 95323 95324 95325 95326 95327 95328 95329 95330 95331 95332 95333 95334 95335 95336 95337 95338 95339 95340 95341 95342 95343 95344 95345 95346 95347 95348 95349 95350 95351 95352 95353 95354 95355 95356 95357 95358 95359 95360 95361 95362 95363 95364 95365 95366 95367 95368 95369 95370 95371 95372 95373 95374 95375 95376 95377 95378 95379 95380 95381 95382 95383 95384 95385 95386 95387 95388 95389 95390 95391 95392 95393 95394 95395 95396 95397 95398 95399 95400 95401 95402 95403 95404 95405 95406 95407 95408 95409 95410 95411 95412 95413 95414 95415 95416 95417 95418 95419 95420 95421 95422 95423 95424 95425 95426 95427 95428 95429 95430 95431 95432 95433 95434 95435 95436 95437 95438 95439 95440 95441 95442 95443 95444 95445 95446 95447 95448 95449 95450 95451 95452 95453 95454 95455 95456 95457 95458 95459 95460 95461 95462 95463 95464 95465 95466 95467 95468 95469 95470 95471 95472 95473 95474 95475 95476 95477 95478 95479 95480 95481 95482 95483 95484 95485 95486 95487 95488 95489 95490 95491 95492 95493 95494 95495 95496 95497 95498 95499 95500 95501 95502 95503 95504 95505 95506 95507 95508 95509 95510 95511 95512 95513 95514 95515 95516 95517 95518 95519 95520 95521 95522 95523 95524 95525 95526 95527 95528 95529 95530 95531 95532 95533 95534 95535 95536 95537 95538 95539 95540 95541 95542 95543 95544 95545 95546 95547 95548 95549 95550 95551 95552 95553 95554 95555 95556 95557 95558 95559 95560 95561 95562 95563 95564 95565 95566 95567 95568 95569 95570 95571 95572 95573 95574 95575 95576 95577 95578 95579 95580 95581 95582 95583 95584 95585 95586 95587 95588 95589 95590 95591 95592 95593 95594 95595 95596 95597 95598 95599 95600 95601 95602 95603 95604 95605 95606 95607 95608 95609 95610 95611 95612 95613 95614 95615 95616 95617 95618 95619 95620 95621 95622 95623 95624 95625 95626 95627 95628 95629 95630 95631 95632 95633 95634 95635 95636 95637 95638 95639 95640 95641 95642 95643 95644 95645 95646 95647 95648 95649 95650 95651 95652 95653 95654 95655 95656 95657 95658 95659 95660 95661 95662 95663 95664 95665 95666 95667 95668 95669 95670 95671 95672 95673 95674 95675 95676 95677 95678 95679 95680 95681 95682 95683 95684 95685 95686 95687 95688 95689 95690 95691 95692 95693 95694 95695 95696 95697 95698 95699 95700 95701 95702 95703 95704 95705 95706 95707 95708 95709 95710 95711 95712 95713 95714 95715 95716 95717 95718 95719 95720 95721 95722 95723 95724 95725 95726 95727 95728 95729 95730 95731 95732 95733 95734 95735 95736 95737 95738 95739 95740 95741 95742 95743 95744 95745 95746 95747 95748 95749 95750 95751 95752 95753 95754 95755 95756 95757 95758 95759 95760 95761 95762 95763 95764 95765 95766 95767 95768 95769 95770 95771 95772 95773 95774 95775 95776 95777 95778 95779 95780 95781 95782 95783 95784 95785 95786 95787 95788 95789 95790 95791 95792 95793 95794 95795 95796 95797 95798 95799 95800 95801 95802 95803 95804 95805 95806 95807 95808 95809 95810 95811 95812 95813 95814 95815 95816 95817 95818 95819 95820 95821 95822 95823 95824 95825 95826 95827 95828 95829 95830 95831 95832 95833 95834 95835 95836 95837 95838 95839 95840 95841 95842 95843 95844 95845 95846 95847 95848 95849 95850 95851 95852 95853 95854 95855 95856 95857 95858 95859 95860 95861 95862 95863 95864 95865 95866 95867 95868 95869 95870 95871 95872 95873 95874 95875 95876 95877 95878 95879 95880 95881 95882 95883 95884 95885 95886 95887 95888 95889 95890 95891 95892 95893 95894 95895 95896 95897 95898 95899 95900 95901 95902 95903 95904 95905 95906 95907 95908 95909 95910 95911 95912 95913 95914 95915 95916 95917 95918 95919 95920 95921 95922 95923 95924 95925 95926 95927 95928 95929 95930 95931 95932 95933 95934 95935 95936 95937 95938 95939 95940 95941 95942 95943 95944 95945 95946 95947 95948 95949 95950 95951 95952 95953 95954 95955 95956 95957 95958 95959 95960 95961 95962 95963 95964 95965 95966 95967 95968 95969 95970 95971 95972 95973 95974 95975 95976 95977 95978 95979 95980 95981 95982 95983 95984 95985 95986 95987 95988 95989 95990 95991 95992 95993 95994 95995 95996 95997 95998 95999 96000 96001 96002 96003 96004 96005 96006 96007 96008 96009 96010 96011 96012 96013 96014 96015 96016 96017 96018 96019 96020 96021 96022 96023 96024 96025 96026 96027 96028 96029 96030 96031 96032 96033 96034 96035 96036 96037 96038 96039 96040 96041 96042 96043 96044 96045 96046 96047 96048 96049 96050 96051 96052 96053 96054 96055 96056 96057 96058 96059 96060 96061 96062 96063 96064 96065 96066 96067 96068 96069 96070 96071 96072 96073 96074 96075 96076 96077 96078 96079 96080 96081 96082 96083 96084 96085 96086 96087 96088 96089 96090 96091 96092 96093 96094 96095 96096 96097 96098 96099 96100 96101 96102 96103 96104 96105 96106 96107 96108 96109 96110 96111 96112 96113 96114 96115 96116 96117 96118 96119 96120 96121 96122 96123 96124 96125 96126 96127 96128 96129 96130 96131 96132 96133 96134 96135 96136 96137 96138 96139 96140 96141 96142 96143 96144 96145 96146 96147 96148 96149 96150 96151 96152 96153 96154 96155 96156 96157 96158 96159 96160 96161 96162 96163 96164 96165 96166 96167 96168 96169 96170 96171 96172 96173 96174 96175 96176 96177 96178 96179 96180 96181 96182 96183 96184 96185 96186 96187 96188 96189 96190 96191 96192 96193 96194 96195 96196 96197 96198 96199 96200 96201 96202 96203 96204 96205 96206 96207 96208 96209 96210 96211 96212 96213 96214 96215 96216 96217 96218 96219 96220 96221 96222 96223 96224 96225 96226 96227 96228 96229 96230 96231 96232 96233 96234 96235 96236 96237 96238 96239 96240 96241 96242 96243 96244 96245 96246 96247 96248 96249 96250 96251 96252 96253 96254 96255 96256 96257 96258 96259 96260 96261 96262 96263 96264 96265 96266 96267 96268 96269 96270 96271 96272 96273 96274 96275 96276 96277 96278 96279 96280 96281 96282 96283 96284 96285 96286 96287 96288 96289 96290 96291 96292 96293 96294 96295 96296 96297 96298 96299 96300 96301 96302 96303 96304 96305 96306 96307 96308 96309 96310 96311 96312 96313 96314 96315 96316 96317 96318 96319 96320 96321 96322 96323 96324 96325 96326 96327 96328 96329 96330 96331 96332 96333 96334 96335 96336 96337 96338 96339 96340 96341 96342 96343 96344 96345 96346 96347 96348 96349 96350 96351 96352 96353 96354 96355 96356 96357 96358 96359 96360 96361 96362 96363 96364 96365 96366 96367 96368 96369 96370 96371 96372 96373 96374 96375 96376 96377 96378 96379 96380 96381 96382 96383 96384 96385 96386 96387 96388 96389 96390 96391 96392 96393 96394 96395 96396 96397 96398 96399 96400 96401 96402 96403 96404 96405 96406 96407 96408 96409 96410 96411 96412 96413 96414 96415 96416 96417 96418 96419 96420 96421 96422 96423 96424 96425 96426 96427 96428 96429 96430 96431 96432 96433 96434 96435 96436 96437 96438 96439 96440 96441 96442 96443 96444 96445 96446 96447 96448 96449 96450 96451 96452 96453 96454 96455 96456 96457 96458 96459 96460 96461 96462 96463 96464 96465 96466 96467 96468 96469 96470 96471 96472 96473 96474 96475 96476 96477 96478 96479 96480 96481 96482 96483 96484 96485 96486 96487 96488 96489 96490 96491 96492 96493 96494 96495 96496 96497 96498 96499 96500 96501 96502 96503 96504 96505 96506 96507 96508 96509 96510 96511 96512 96513 96514 96515 96516 96517 96518 96519 96520 96521 96522 96523 96524 96525 96526 96527 96528 96529 96530 96531 96532 96533 96534 96535 96536 96537 96538 96539 96540 96541 96542 96543 96544 96545 96546 96547 96548 96549 96550 96551 96552 96553 96554 96555 96556 96557 96558 96559 96560 96561 96562 96563 96564 96565 96566 96567 96568 96569 96570 96571 96572 96573 96574 96575 96576 96577 96578 96579 96580 96581 96582 96583 96584 96585 96586 96587 96588 96589 96590 96591 96592 96593 96594 96595 96596 96597 96598 96599 96600 96601 96602 96603 96604 96605 96606 96607 96608 96609 96610 96611 96612 96613 96614 96615 96616 96617 96618 96619 96620 96621 96622 96623 96624 96625 96626 96627 96628 96629 96630 96631 96632 96633 96634 96635 96636 96637 96638 96639 96640 96641 96642 96643 96644 96645 96646 96647 96648 96649 96650 96651 96652 96653 96654 96655 96656 96657 96658 96659 96660 96661 96662 96663 96664 96665 96666 96667 96668 96669 96670 96671 96672 96673 96674 96675 96676 96677 96678 96679 96680 96681 96682 96683 96684 96685 96686 96687 96688 96689 96690 96691 96692 96693 96694 96695 96696 96697 96698 96699 96700 96701 96702 96703 96704 96705 96706 96707 96708 96709 96710 96711 96712 96713 96714 96715 96716 96717 96718 96719 96720 96721 96722 96723 96724 96725 96726 96727 96728 96729 96730 96731 96732 96733 96734 96735 96736 96737 96738 96739 96740 96741 96742 96743 96744 96745 96746 96747 96748 96749 96750 96751 96752 96753 96754 96755 96756 96757 96758 96759 96760 96761 96762 96763 96764 96765 96766 96767 96768 96769 96770 96771 96772 96773 96774 96775 96776 96777 96778 96779 96780 96781 96782 96783 96784 96785 96786 96787 96788 96789 96790 96791 96792 96793 96794 96795 96796 96797 96798 96799 96800 96801 96802 96803 96804 96805 96806 96807 96808 96809 96810 96811 96812 96813 96814 96815 96816 96817 96818 96819 96820 96821 96822 96823 96824 96825 96826 96827 96828 96829 96830 96831 96832 96833 96834 96835 96836 96837 96838 96839 96840 96841 96842 96843 96844 96845 96846 96847 96848 96849 96850 96851 96852 96853 96854 96855 96856 96857 96858 96859 96860 96861 96862 96863 96864 96865 96866 96867 96868 96869 96870 96871 96872 96873 96874 96875 96876 96877 96878 96879 96880 96881 96882 96883 96884 96885 96886 96887 96888 96889 96890 96891 96892 96893 96894 96895 96896 96897 96898 96899 96900 96901 96902 96903 96904 96905 96906 96907 96908 96909 96910 96911 96912 96913 96914 96915 96916 96917 96918 96919 96920 96921 96922 96923 96924 96925 96926 96927 96928 96929 96930 96931 96932 96933 96934 96935 96936 96937 96938 96939 96940 96941 96942 96943 96944 96945 96946 96947 96948 96949 96950 96951 96952 96953 96954 96955 96956 96957 96958 96959 96960 96961 96962 96963 96964 96965 96966 96967 96968 96969 96970 96971 96972 96973 96974 96975 96976 96977 96978 96979 96980 96981 96982 96983 96984 96985 96986 96987 96988 96989 96990 96991 96992 96993 96994 96995 96996 96997 96998 96999 97000 97001 97002 97003 97004 97005 97006 97007 97008 97009 97010 97011 97012 97013 97014 97015 97016 97017 97018 97019 97020 97021 97022 97023 97024 97025 97026 97027 97028 97029 97030 97031 97032 97033 97034 97035 97036 97037 97038 97039 97040 97041 97042 97043 97044 97045 97046 97047 97048 97049 97050 97051 97052 97053 97054 97055 97056 97057 97058 97059 97060 97061 97062 97063 97064 97065 97066 97067 97068 97069 97070 97071 97072 97073 97074 97075 97076 97077 97078 97079 97080 97081 97082 97083 97084 97085 97086 97087 97088 97089 97090 97091 97092 97093 97094 97095 97096 97097 97098 97099 97100 97101 97102 97103 97104 97105 97106 97107 97108 97109 97110 97111 97112 97113 97114 97115 97116 97117 97118 97119 97120 97121 97122 97123 97124 97125 97126 97127 97128 97129 97130 97131 97132 97133 97134 97135 97136 97137 97138 97139 97140 97141 97142 97143 97144 97145 97146 97147 97148 97149 97150 97151 97152 97153 97154 97155 97156 97157 97158 97159 97160 97161 97162 97163 97164 97165 97166 97167 97168 97169 97170 97171 97172 97173 97174 97175 97176 97177 97178 97179 97180 97181 97182 97183 97184 97185 97186 97187 97188 97189 97190 97191 97192 97193 97194 97195 97196 97197 97198 97199 97200 97201 97202 97203 97204 97205 97206 97207 97208 97209 97210 97211 97212 97213 97214 97215 97216 97217 97218 97219 97220 97221 97222 97223 97224 97225 97226 97227 97228 97229 97230 97231 97232 97233 97234 97235 97236 97237 97238 97239 97240 97241 97242 97243 97244 97245 97246 97247 97248 97249 97250 97251 97252 97253 97254 97255 97256 97257 97258 97259 97260 97261 97262 97263 97264 97265 97266 97267 97268 97269 97270 97271 97272 97273 97274 97275 97276 97277 97278 97279 97280 97281 97282 97283 97284 97285 97286 97287 97288 97289 97290 97291 97292 97293 97294 97295 97296 97297 97298 97299 97300 97301 97302 97303 97304 97305 97306 97307 97308 97309 97310 97311 97312 97313 97314 97315 97316 97317 97318 97319 97320 97321 97322 97323 97324 97325 97326 97327 97328 97329 97330 97331 97332 97333 97334 97335 97336 97337 97338 97339 97340 97341 97342 97343 97344 97345 97346 97347 97348 97349 97350 97351 97352 97353 97354 97355 97356 97357 97358 97359 97360 97361 97362 97363 97364 97365 97366 97367 97368 97369 97370 97371 97372 97373 97374 97375 97376 97377 97378 97379 97380 97381 97382 97383 97384 97385 97386 97387 97388 97389 97390 97391 97392 97393 97394 97395 97396 97397 97398 97399 97400 97401 97402 97403 97404 97405 97406 97407 97408 97409 97410 97411 97412 97413 97414 97415 97416 97417 97418 97419 97420 97421 97422 97423 97424 97425 97426 97427 97428 97429 97430 97431 97432 97433 97434 97435 97436 97437 97438 97439 97440 97441 97442 97443 97444 97445 97446 97447 97448 97449 97450 97451 97452 97453 97454 97455 97456 97457 97458 97459 97460 97461 97462 97463 97464 97465 97466 97467 97468 97469 97470 97471 97472 97473 97474 97475 97476 97477 97478 97479 97480 97481 97482 97483 97484 97485 97486 97487 97488 97489 97490 97491 97492 97493 97494 97495 97496 97497 97498 97499 97500 97501 97502 97503 97504 97505 97506 97507 97508 97509 97510 97511 97512 97513 97514 97515 97516 97517 97518 97519 97520 97521 97522 97523 97524 97525 97526 97527 97528 97529 97530 97531 97532 97533 97534 97535 97536 97537 97538 97539 97540 97541 97542 97543 97544 97545 97546 97547 97548 97549 97550 97551 97552 97553 97554 97555 97556 97557 97558 97559 97560 97561 97562 97563 97564 97565 97566 97567 97568 97569 97570 97571 97572 97573 97574 97575 97576 97577 97578 97579 97580 97581 97582 97583 97584 97585 97586 97587 97588 97589 97590 97591 97592 97593 97594 97595 97596 97597 97598 97599 97600 97601 97602 97603 97604 97605 97606 97607 97608 97609 97610 97611 97612 97613 97614 97615 97616 97617 97618 97619 97620 97621 97622 97623 97624 97625 97626 97627 97628 97629 97630 97631 97632 97633 97634 97635 97636 97637 97638 97639 97640 97641 97642 97643 97644 97645 97646 97647 97648 97649 97650 97651 97652 97653 97654 97655 97656 97657 97658 97659 97660 97661 97662 97663 97664 97665 97666 97667 97668 97669 97670 97671 97672 97673 97674 97675 97676 97677 97678 97679 97680 97681 97682 97683 97684 97685 97686 97687 97688 97689 97690 97691 97692 97693 97694 97695 97696 97697 97698 97699 97700 97701 97702 97703 97704 97705 97706 97707 97708 97709 97710 97711 97712 97713 97714 97715 97716 97717 97718 97719 97720 97721 97722 97723 97724 97725 97726 97727 97728 97729 97730 97731 97732 97733 97734 97735 97736 97737 97738 97739 97740 97741 97742 97743 97744 97745 97746 97747 97748 97749 97750 97751 97752 97753 97754 97755 97756 97757 97758 97759 97760 97761 97762 97763 97764 97765 97766 97767 97768 97769 97770 97771 97772 97773 97774 97775 97776 97777 97778 97779 97780 97781 97782 97783 97784 97785 97786 97787 97788 97789 97790 97791 97792 97793 97794 97795 97796 97797 97798 97799 97800 97801 97802 97803 97804 97805 97806 97807 97808 97809 97810 97811 97812 97813 97814 97815 97816 97817 97818 97819 97820 97821 97822 97823 97824 97825 97826 97827 97828 97829 97830 97831 97832 97833 97834 97835 97836 97837 97838 97839 97840 97841 97842 97843 97844 97845 97846 97847 97848 97849 97850 97851 97852 97853 97854 97855 97856 97857 97858 97859 97860 97861 97862 97863 97864 97865 97866 97867 97868 97869 97870 97871 97872 97873 97874 97875 97876 97877 97878 97879 97880 97881 97882 97883 97884 97885 97886 97887 97888 97889 97890 97891 97892 97893 97894 97895 97896 97897 97898 97899 97900 97901 97902 97903 97904 97905 97906 97907 97908 97909 97910 97911 97912 97913 97914 97915 97916 97917 97918 97919 97920 97921 97922 97923 97924 97925 97926 97927 97928 97929 97930 97931 97932 97933 97934 97935 97936 97937 97938 97939 97940 97941 97942 97943 97944 97945 97946 97947 97948 97949 97950 97951 97952 97953 97954 97955 97956 97957 97958 97959 97960 97961 97962 97963 97964 97965 97966 97967 97968 97969 97970 97971 97972 97973 97974 97975 97976 97977 97978 97979 97980 97981 97982 97983 97984 97985 97986 97987 97988 97989 97990 97991 97992 97993 97994 97995 97996 97997 97998 97999 98000 98001 98002 98003 98004 98005 98006 98007 98008 98009 98010 98011 98012 98013 98014 98015 98016 98017 98018 98019 98020 98021 98022 98023 98024 98025 98026 98027 98028 98029 98030 98031 98032 98033 98034 98035 98036 98037 98038 98039 98040 98041 98042 98043 98044 98045 98046 98047 98048 98049 98050 98051 98052 98053 98054 98055 98056 98057 98058 98059 98060 98061 98062 98063 98064 98065 98066 98067 98068 98069 98070 98071 98072 98073 98074 98075 98076 98077 98078 98079 98080 98081 98082 98083 98084 98085 98086 98087 98088 98089 98090 98091 98092 98093 98094 98095 98096 98097 98098 98099 98100 98101 98102 98103 98104 98105 98106 98107 98108 98109 98110 98111 98112 98113 98114 98115 98116 98117 98118 98119 98120 98121 98122 98123 98124 98125 98126 98127 98128 98129 98130 98131 98132 98133 98134 98135 98136 98137 98138 98139 98140 98141 98142 98143 98144 98145 98146 98147 98148 98149 98150 98151 98152 98153 98154 98155 98156 98157 98158 98159 98160 98161 98162 98163 98164 98165 98166 98167 98168 98169 98170 98171 98172 98173 98174 98175 98176 98177 98178 98179 98180 98181 98182 98183 98184 98185 98186 98187 98188 98189 98190 98191 98192 98193 98194 98195 98196 98197 98198 98199 98200 98201 98202 98203 98204 98205 98206 98207 98208 98209 98210 98211 98212 98213 98214 98215 98216 98217 98218 98219 98220 98221 98222 98223 98224 98225 98226 98227 98228 98229 98230 98231 98232 98233 98234 98235 98236 98237 98238 98239 98240 98241 98242 98243 98244 98245 98246 98247 98248 98249 98250 98251 98252 98253 98254 98255 98256 98257 98258 98259 98260 98261 98262 98263 98264 98265 98266 98267 98268 98269 98270 98271 98272 98273 98274 98275 98276 98277 98278 98279 98280 98281 98282 98283 98284 98285 98286 98287 98288 98289 98290 98291 98292 98293 98294 98295 98296 98297 98298 98299 98300 98301 98302 98303 98304 98305 98306 98307 98308 98309 98310 98311 98312 98313 98314 98315 98316 98317 98318 98319 98320 98321 98322 98323 98324 98325 98326 98327 98328 98329 98330 98331 98332 98333 98334 98335 98336 98337 98338 98339 98340 98341 98342 98343 98344 98345 98346 98347 98348 98349 98350 98351 98352 98353 98354 98355 98356 98357 98358 98359 98360 98361 98362 98363 98364 98365 98366 98367 98368 98369 98370 98371 98372 98373 98374 98375 98376 98377 98378 98379 98380 98381 98382 98383 98384 98385 98386 98387 98388 98389 98390 98391 98392 98393 98394 98395 98396 98397 98398 98399 98400 98401 98402 98403 98404 98405 98406 98407 98408 98409 98410 98411 98412 98413 98414 98415 98416 98417 98418 98419 98420 98421 98422 98423 98424 98425 98426 98427 98428 98429 98430 98431 98432 98433 98434 98435 98436 98437 98438 98439 98440 98441 98442 98443 98444 98445 98446 98447 98448 98449 98450 98451 98452 98453 98454 98455 98456 98457 98458 98459 98460 98461 98462 98463 98464 98465 98466 98467 98468 98469 98470 98471 98472 98473 98474 98475 98476 98477 98478 98479 98480 98481 98482 98483 98484 98485 98486 98487 98488 98489 98490 98491 98492 98493 98494 98495 98496 98497 98498 98499 98500 98501 98502 98503 98504 98505 98506 98507 98508 98509 98510 98511 98512 98513 98514 98515 98516 98517 98518 98519 98520 98521 98522 98523 98524 98525 98526 98527 98528 98529 98530 98531 98532 98533 98534 98535 98536 98537 98538 98539 98540 98541 98542 98543 98544 98545 98546 98547 98548 98549 98550 98551 98552 98553 98554 98555 98556 98557 98558 98559 98560 98561 98562 98563 98564 98565 98566 98567 98568 98569 98570 98571 98572 98573 98574 98575 98576 98577 98578 98579 98580 98581 98582 98583 98584 98585 98586 98587 98588 98589 98590 98591 98592 98593 98594 98595 98596 98597 98598 98599 98600 98601 98602 98603 98604 98605 98606 98607 98608 98609 98610 98611 98612 98613 98614 98615 98616 98617 98618 98619 98620 98621 98622 98623 98624 98625 98626 98627 98628 98629 98630 98631 98632 98633 98634 98635 98636 98637 98638 98639 98640 98641 98642 98643 98644 98645 98646 98647 98648 98649 98650 98651 98652 98653 98654 98655 98656 98657 98658 98659 98660 98661 98662 98663 98664 98665 98666 98667 98668 98669 98670 98671 98672 98673 98674 98675 98676 98677 98678 98679 98680 98681 98682 98683 98684 98685 98686 98687 98688 98689 98690 98691 98692 98693 98694 98695 98696 98697 98698 98699 98700 98701 98702 98703 98704 98705 98706 98707 98708 98709 98710 98711 98712 98713 98714 98715 98716 98717 98718 98719 98720 98721 98722 98723 98724 98725 98726 98727 98728 98729 98730 98731 98732 98733 98734 98735 98736 98737 98738 98739 98740 98741 98742 98743 98744 98745 98746 98747 98748 98749 98750 98751 98752 98753 98754 98755 98756 98757 98758 98759 98760 98761 98762 98763 98764 98765 98766 98767 98768 98769 98770 98771 98772 98773 98774 98775 98776 98777 98778 98779 98780 98781 98782 98783 98784 98785 98786 98787 98788 98789 98790 98791 98792 98793 98794 98795 98796 98797 98798 98799 98800 98801 98802 98803 98804 98805 98806 98807 98808 98809 98810 98811 98812 98813 98814 98815 98816 98817 98818 98819 98820 98821 98822 98823 98824 98825 98826 98827 98828 98829 98830 98831 98832 98833 98834 98835 98836 98837 98838 98839 98840 98841 98842 98843 98844 98845 98846 98847 98848 98849 98850 98851 98852 98853 98854 98855 98856 98857 98858 98859 98860 98861 98862 98863 98864 98865 98866 98867 98868 98869 98870 98871 98872 98873 98874 98875 98876 98877 98878 98879 98880 98881 98882 98883 98884 98885 98886 98887 98888 98889 98890 98891 98892 98893 98894 98895 98896 98897 98898 98899 98900 98901 98902 98903 98904 98905 98906 98907 98908 98909 98910 98911 98912 98913 98914 98915 98916 98917 98918 98919 98920 98921 98922 98923 98924 98925 98926 98927 98928 98929 98930 98931 98932 98933 98934 98935 98936 98937 98938 98939 98940 98941 98942 98943 98944 98945 98946 98947 98948 98949 98950 98951 98952 98953 98954 98955 98956 98957 98958 98959 98960 98961 98962 98963 98964 98965 98966 98967 98968 98969 98970 98971 98972 98973 98974 98975 98976 98977 98978 98979 98980 98981 98982 98983 98984 98985 98986 98987 98988 98989 98990 98991 98992 98993 98994 98995 98996 98997 98998 98999 99000 99001 99002 99003 99004 99005 99006 99007 99008 99009 99010 99011 99012 99013 99014 99015 99016 99017 99018 99019 99020 99021 99022 99023 99024 99025 99026 99027 99028 99029 99030 99031 99032 99033 99034 99035 99036 99037 99038 99039 99040 99041 99042 99043 99044 99045 99046 99047 99048 99049 99050 99051 99052 99053 99054 99055 99056 99057 99058 99059 99060 99061 99062 99063 99064 99065 99066 99067 99068 99069 99070 99071 99072 99073 99074 99075 99076 99077 99078 99079 99080 99081 99082 99083 99084 99085 99086 99087 99088 99089 99090 99091 99092 99093 99094 99095 99096 99097 99098 99099 99100 99101 99102 99103 99104 99105 99106 99107 99108 99109 99110 99111 99112 99113 99114 99115 99116 99117 99118 99119 99120 99121 99122 99123 99124 99125 99126 99127 99128 99129 99130 99131 99132 99133 99134 99135 99136 99137 99138 99139 99140 99141 99142 99143 99144 99145 99146 99147 99148 99149 99150 99151 99152 99153 99154 99155 99156 99157 99158 99159 99160 99161 99162 99163 99164 99165 99166 99167 99168 99169 99170 99171 99172 99173 99174 99175 99176 99177 99178 99179 99180 99181 99182 99183 99184 99185 99186 99187 99188 99189 99190 99191 99192 99193 99194 99195 99196 99197 99198 99199 99200 99201 99202 99203 99204 99205 99206 99207 99208 99209 99210 99211 99212 99213 99214 99215 99216 99217 99218 99219 99220 99221 99222 99223 99224 99225 99226 99227 99228 99229 99230 99231 99232 99233 99234 99235 99236 99237 99238 99239 99240 99241 99242 99243 99244 99245 99246 99247 99248 99249 99250 99251 99252 99253 99254 99255 99256 99257 99258 99259 99260 99261 99262 99263 99264 99265 99266 99267 99268 99269 99270 99271 99272 99273 99274 99275 99276 99277 99278 99279 99280 99281 99282 99283 99284 99285 99286 99287 99288 99289 99290 99291 99292 99293 99294 99295 99296 99297 99298 99299 99300 99301 99302 99303 99304 99305 99306 99307 99308 99309 99310 99311 99312 99313 99314 99315 99316 99317 99318 99319 99320 99321 99322 99323 99324 99325 99326 99327 99328 99329 99330 99331 99332 99333 99334 99335 99336 99337 99338 99339 99340 99341 99342 99343 99344 99345 99346 99347 99348 99349 99350 99351 99352 99353 99354 99355 99356 99357 99358 99359 99360 99361 99362 99363 99364 99365 99366 99367 99368 99369 99370 99371 99372 99373 99374 99375 99376 99377 99378 99379 99380 99381 99382 99383 99384 99385 99386 99387 99388 99389 99390 99391 99392 99393 99394 99395 99396 99397 99398 99399 99400 99401 99402 99403 99404 99405 99406 99407 99408 99409 99410 99411 99412 99413 99414 99415 99416 99417 99418 99419 99420 99421 99422 99423 99424 99425 99426 99427 99428 99429 99430 99431 99432 99433 99434 99435 99436 99437 99438 99439 99440 99441 99442 99443 99444 99445 99446 99447 99448 99449 99450 99451 99452 99453 99454 99455 99456 99457 99458 99459 99460 99461 99462 99463 99464 99465 99466 99467 99468 99469 99470 99471 99472 99473 99474 99475 99476 99477 99478 99479 99480 99481 99482 99483 99484 99485 99486 99487 99488 99489 99490 99491 99492 99493 99494 99495 99496 99497 99498 99499 99500 99501 99502 99503 99504 99505 99506 99507 99508 99509 99510 99511 99512 99513 99514 99515 99516 99517 99518 99519 99520 99521 99522 99523 99524 99525 99526 99527 99528 99529 99530 99531 99532 99533 99534 99535 99536 99537 99538 99539 99540 99541 99542 99543 99544 99545 99546 99547 99548 99549 99550 99551 99552 99553 99554 99555 99556 99557 99558 99559 99560 99561 99562 99563 99564 99565 99566 99567 99568 99569 99570 99571 99572 99573 99574 99575 99576 99577 99578 99579 99580 99581 99582 99583 99584 99585 99586 99587 99588 99589 99590 99591 99592 99593 99594 99595 99596 99597 99598 99599 99600 99601 99602 99603 99604 99605 99606 99607 99608 99609 99610 99611 99612 99613 99614 99615 99616 99617 99618 99619 99620 99621 99622 99623 99624 99625 99626 99627 99628 99629 99630 99631 99632 99633 99634 99635 99636 99637 99638 99639 99640 99641 99642 99643 99644 99645 99646 99647 99648 99649 99650 99651 99652 99653 99654 99655 99656 99657 99658 99659 99660 99661 99662 99663 99664 99665 99666 99667 99668 99669 99670 99671 99672 99673 99674 99675 99676 99677 99678 99679 99680 99681 99682 99683 99684 99685 99686 99687 99688 99689 99690 99691 99692 99693 99694 99695 99696 99697 99698 99699 99700 99701 99702 99703 99704 99705 99706 99707 99708 99709 99710 99711 99712 99713 99714 99715 99716 99717 99718 99719 99720 99721 99722 99723 99724 99725 99726 99727 99728 99729 99730 99731 99732 99733 99734 99735 99736 99737 99738 99739 99740 99741 99742 99743 99744 99745 99746 99747 99748 99749 99750 99751 99752 99753 99754 99755 99756 99757 99758 99759 99760 99761 99762 99763 99764 99765 99766 99767 99768 99769 99770 99771 99772 99773 99774 99775 99776 99777 99778 99779 99780 99781 99782 99783 99784 99785 99786 99787 99788 99789 99790 99791 99792 99793 99794 99795 99796 99797 99798 99799 99800 99801 99802 99803 99804 99805 99806 99807 99808 99809 99810 99811 99812 99813 99814 99815 99816 99817 99818 99819 99820 99821 99822 99823 99824 99825 99826 99827 99828 99829 99830 99831 99832 99833 99834 99835 99836 99837 99838 99839 99840 99841 99842 99843 99844 99845 99846 99847 99848 99849 99850 99851 99852 99853 99854 99855 99856 99857 99858 99859 99860 99861 99862 99863 99864 99865 99866 99867 99868 99869 99870 99871 99872 99873 99874 99875 99876 99877 99878 99879 99880 99881 99882 99883 99884 99885 99886 99887 99888 99889 99890 99891 99892 99893 99894 99895 99896 99897 99898 99899 99900 99901 99902 99903 99904 99905 99906 99907 99908 99909 99910 99911 99912 99913 99914 99915 99916 99917 99918 99919 99920 99921 99922 99923 99924 99925 99926 99927 99928 99929 99930 99931 99932 99933 99934 99935 99936 99937 99938 99939 99940 99941 99942 99943 99944 99945 99946 99947 99948 99949 99950 99951 99952 99953 99954 99955 99956 99957 99958 99959 99960 99961 99962 99963 99964 99965 99966 99967 99968 99969 99970 99971 99972 99973
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<meta name="nodejs.org:node-version" content="v20.19.2">
<title>Node.js v20.19.2 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/all.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:598px){.with-47-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:582px){.with-45-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:526px){.with-38-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:542px){.with-40-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:622px){.with-50-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1080px){.with-73-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:686px){.with-58-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1072px){.with-72-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:654px){.with-54-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:606px){.with-48-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1048px){.with-69-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1144px){.with-81-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:590px){.with-46-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:638px){.with-52-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1176px){.with-85-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;}}@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:750px){.with-66-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:734px){.with-64-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1088px){.with-74-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:630px){.with-51-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:662px){.with-55-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:702px){.with-60-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:478px){.with-32-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:574px){.with-44-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:294px){.with-9-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:374px){.with-19-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:518px){.with-37-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:742px){.with-65-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:326px){.with-13-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:446px){.with-28-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:566px){.with-43-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:398px){.with-22-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:670px){.with-56-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:334px){.with-14-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:366px){.with-18-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:318px){.with-12-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:342px){.with-15-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:550px){.with-41-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:486px){.with-33-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:758px){.with-67-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1152px){.with-82-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:726px){.with-63-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1096px){.with-75-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:534px){.with-39-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:462px){.with-30-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:286px){.with-8-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:614px){.with-49-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:694px){.with-59-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:510px){.with-36-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:502px){.with-35-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:494px){.with-34-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:678px){.with-57-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:766px){.with-68-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:430px){.with-26-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:454px){.with-29-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1064px){.with-71-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1120px){.with-78-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:710px){.with-61-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1112px){.with-77-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:358px){.with-17-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}</style>
</head>
<body class="alt apidoc" id="api-section-all">
<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="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="stream.html" class="nav-stream">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="all" class="interior">
<header class="header">
<div class="header-container">
<h1>Node.js v20.19.2 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 v20.19.2</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-v24.x/api/all.html">24.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v23.x/api/all.html">23.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v22.x/api/all.html">22.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v21.x/api/all.html">21.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v20.x/api/all.html">20.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v19.x/api/all.html">19.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v18.x/api/all.html">18.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v17.x/api/all.html">17.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v16.x/api/all.html">16.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v15.x/api/all.html">15.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v14.x/api/all.html">14.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v13.x/api/all.html">13.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v12.x/api/all.html">12.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v11.x/api/all.html">11.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v10.x/api/all.html">10.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v9.x/api/all.html">9.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v8.x/api/all.html">8.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v7.x/api/all.html">7.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v6.x/api/all.html">6.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v5.x/api/all.html">5.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v4.x/api/all.html">4.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/all.html">0.12.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/all.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="index.html">View on single page</a>
</li>
<li>
<a href="all.json">View as JSON</a>
</li>
</ul>
</div>
</li>
</ul>
</div>
<hr>
</header>
<!-- TOC --><details id="toc" open><summary>Table of contents</summary>
<ul>
<li><a href="#all_documentation_about-this-documentation">About this documentation</a>
<ul>
<li><a href="#all_documentation_contributing">Contributing</a></li>
<li><a href="#all_documentation_stability-index">Stability index</a></li>
<li><a href="#all_documentation_stability-overview">Stability overview</a></li>
<li><a href="#all_documentation_json-output">JSON output</a></li>
<li><a href="#all_documentation_system-calls-and-man-pages">System calls and man pages</a></li>
</ul>
</li>
<li><a href="#all_synopsis_usage-and-example">Usage and example</a>
<ul>
<li><a href="#all_synopsis_usage">Usage</a></li>
<li><a href="#all_synopsis_example">Example</a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_assert_assert">Assert</a></span>
<ul>
<li><a href="#all_assert_strict-assertion-mode">Strict assertion mode</a></li>
<li><a href="#all_assert_legacy-assertion-mode">Legacy assertion mode</a></li>
<li><a href="#all_assert_class-assertassertionerror">Class: assert.AssertionError</a>
<ul>
<li><a href="#all_assert_new-assertassertionerroroptions"><code>new assert.AssertionError(options)</code></a></li>
</ul>
</li>
<li><span class="stability_0"><a href="#all_assert_class-assertcalltracker">Class: <code>assert.CallTracker</code></a></span>
<ul>
<li><a href="#all_assert_new-assertcalltracker"><code>new assert.CallTracker()</code></a></li>
<li><a href="#all_assert_trackercallsfn-exact"><code>tracker.calls([fn][, exact])</code></a></li>
<li><a href="#all_assert_trackergetcallsfn"><code>tracker.getCalls(fn)</code></a></li>
<li><a href="#all_assert_trackerreport"><code>tracker.report()</code></a></li>
<li><a href="#all_assert_trackerresetfn"><code>tracker.reset([fn])</code></a></li>
<li><a href="#all_assert_trackerverify"><code>tracker.verify()</code></a></li>
</ul>
</li>
<li><a href="#all_assert_assertvalue-message"><code>assert(value[, message])</code></a></li>
<li><a href="#all_assert_assertdeepequalactual-expected-message"><code>assert.deepEqual(actual, expected[, message])</code></a>
<ul>
<li><a href="#all_assert_comparison-details">Comparison details</a></li>
</ul>
</li>
<li><a href="#all_assert_assertdeepstrictequalactual-expected-message"><code>assert.deepStrictEqual(actual, expected[, message])</code></a>
<ul>
<li><a href="#all_assert_comparison-details_1">Comparison details</a></li>
</ul>
</li>
<li><a href="#all_assert_assertdoesnotmatchstring-regexp-message"><code>assert.doesNotMatch(string, regexp[, message])</code></a></li>
<li><a href="#all_assert_assertdoesnotrejectasyncfn-error-message"><code>assert.doesNotReject(asyncFn[, error][, message])</code></a></li>
<li><a href="#all_assert_assertdoesnotthrowfn-error-message"><code>assert.doesNotThrow(fn[, error][, message])</code></a></li>
<li><a href="#all_assert_assertequalactual-expected-message"><code>assert.equal(actual, expected[, message])</code></a></li>
<li><a href="#all_assert_assertfailmessage"><code>assert.fail([message])</code></a></li>
<li><span class="stability_0"><a href="#all_assert_assertfailactual-expected-message-operator-stackstartfn"><code>assert.fail(actual, expected[, message[, operator[, stackStartFn]]])</code></a></span></li>
<li><a href="#all_assert_assertiferrorvalue"><code>assert.ifError(value)</code></a></li>
<li><a href="#all_assert_assertmatchstring-regexp-message"><code>assert.match(string, regexp[, message])</code></a></li>
<li><a href="#all_assert_assertnotdeepequalactual-expected-message"><code>assert.notDeepEqual(actual, expected[, message])</code></a></li>
<li><a href="#all_assert_assertnotdeepstrictequalactual-expected-message"><code>assert.notDeepStrictEqual(actual, expected[, message])</code></a></li>
<li><a href="#all_assert_assertnotequalactual-expected-message"><code>assert.notEqual(actual, expected[, message])</code></a></li>
<li><a href="#all_assert_assertnotstrictequalactual-expected-message"><code>assert.notStrictEqual(actual, expected[, message])</code></a></li>
<li><a href="#all_assert_assertokvalue-message"><code>assert.ok(value[, message])</code></a></li>
<li><a href="#all_assert_assertrejectsasyncfn-error-message"><code>assert.rejects(asyncFn[, error][, message])</code></a></li>
<li><a href="#all_assert_assertstrictequalactual-expected-message"><code>assert.strictEqual(actual, expected[, message])</code></a></li>
<li><a href="#all_assert_assertthrowsfn-error-message"><code>assert.throws(fn[, error][, message])</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_async_context_asynchronous-context-tracking">Asynchronous context tracking</a></span>
<ul>
<li><a href="#all_async_context_introduction">Introduction</a></li>
<li><a href="#all_async_context_class-asynclocalstorage">Class: <code>AsyncLocalStorage</code></a>
<ul>
<li><a href="#all_async_context_new-asynclocalstorage"><code>new AsyncLocalStorage()</code></a></li>
<li><span class="stability_1"><a href="#all_async_context_static-method-asynclocalstoragebindfn">Static method: <code>AsyncLocalStorage.bind(fn)</code></a></span></li>
<li><span class="stability_1"><a href="#all_async_context_static-method-asynclocalstoragesnapshot">Static method: <code>AsyncLocalStorage.snapshot()</code></a></span></li>
<li><span class="stability_1"><a href="#all_async_context_asynclocalstoragedisable"><code>asyncLocalStorage.disable()</code></a></span></li>
<li><a href="#all_async_context_asynclocalstoragegetstore"><code>asyncLocalStorage.getStore()</code></a></li>
<li><span class="stability_1"><a href="#all_async_context_asynclocalstorageenterwithstore"><code>asyncLocalStorage.enterWith(store)</code></a></span></li>
<li><a href="#all_async_context_asynclocalstoragerunstore-callback-args"><code>asyncLocalStorage.run(store, callback[, ...args])</code></a></li>
<li><span class="stability_1"><a href="#all_async_context_asynclocalstorageexitcallback-args"><code>asyncLocalStorage.exit(callback[, ...args])</code></a></span></li>
<li><a href="#all_async_context_usage-with-asyncawait">Usage with <code>async/await</code></a></li>
<li><a href="#all_async_context_troubleshooting-context-loss">Troubleshooting: Context loss</a></li>
</ul>
</li>
<li><a href="#all_async_context_class-asyncresource">Class: <code>AsyncResource</code></a>
<ul>
<li><a href="#all_async_context_new-asyncresourcetype-options"><code>new AsyncResource(type[, options])</code></a></li>
<li><a href="#all_async_context_static-method-asyncresourcebindfn-type-thisarg">Static method: <code>AsyncResource.bind(fn[, type[, thisArg]])</code></a></li>
<li><a href="#all_async_context_asyncresourcebindfn-thisarg"><code>asyncResource.bind(fn[, thisArg])</code></a></li>
<li><a href="#all_async_context_asyncresourceruninasyncscopefn-thisarg-args"><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code></a></li>
<li><a href="#all_async_context_asyncresourceemitdestroy"><code>asyncResource.emitDestroy()</code></a></li>
<li><a href="#all_async_context_asyncresourceasyncid"><code>asyncResource.asyncId()</code></a></li>
<li><a href="#all_async_context_asyncresourcetriggerasyncid"><code>asyncResource.triggerAsyncId()</code></a></li>
<li><a href="#all_async_context_using-asyncresource-for-a-worker-thread-pool">Using <code>AsyncResource</code> for a <code>Worker</code> thread pool</a></li>
<li><a href="#all_async_context_integrating-asyncresource-with-eventemitter">Integrating <code>AsyncResource</code> with <code>EventEmitter</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_async_hooks_async-hooks">Async hooks</a></span>
<ul>
<li><a href="#all_async_hooks_terminology">Terminology</a></li>
<li><a href="#all_async_hooks_overview">Overview</a></li>
<li><a href="#all_async_hooks_async_hookscreatehookcallbacks"><code>async_hooks.createHook(callbacks)</code></a>
<ul>
<li><a href="#all_async_hooks_error-handling">Error handling</a></li>
<li><a href="#all_async_hooks_printing-in-asynchook-callbacks">Printing in <code>AsyncHook</code> callbacks</a></li>
</ul>
</li>
<li><a href="#all_async_hooks_class-asynchook">Class: <code>AsyncHook</code></a>
<ul>
<li><a href="#all_async_hooks_asynchookenable"><code>asyncHook.enable()</code></a></li>
<li><a href="#all_async_hooks_asynchookdisable"><code>asyncHook.disable()</code></a></li>
<li><a href="#all_async_hooks_hook-callbacks">Hook callbacks</a>
<ul>
<li><a href="#all_async_hooks_initasyncid-type-triggerasyncid-resource"><code>init(asyncId, type, triggerAsyncId, resource)</code></a>
<ul>
<li><a href="#all_async_hooks_type"><code>type</code></a></li>
<li><a href="#all_async_hooks_triggerasyncid"><code>triggerAsyncId</code></a></li>
<li><a href="#all_async_hooks_resource"><code>resource</code></a></li>
<li><a href="#all_async_hooks_asynchronous-context-example">Asynchronous context example</a></li>
</ul>
</li>
<li><a href="#all_async_hooks_beforeasyncid"><code>before(asyncId)</code></a></li>
<li><a href="#all_async_hooks_afterasyncid"><code>after(asyncId)</code></a></li>
<li><a href="#all_async_hooks_destroyasyncid"><code>destroy(asyncId)</code></a></li>
<li><a href="#all_async_hooks_promiseresolveasyncid"><code>promiseResolve(asyncId)</code></a></li>
</ul>
</li>
<li><a href="#all_async_hooks_async_hooksexecutionasyncresource"><code>async_hooks.executionAsyncResource()</code></a></li>
<li><a href="#all_async_hooks_async_hooksexecutionasyncid"><code>async_hooks.executionAsyncId()</code></a></li>
<li><a href="#all_async_hooks_async_hookstriggerasyncid"><code>async_hooks.triggerAsyncId()</code></a></li>
<li><a href="#all_async_hooks_async_hooksasyncwrapproviders"><code>async_hooks.asyncWrapProviders</code></a></li>
</ul>
</li>
<li><a href="#all_async_hooks_promise-execution-tracking">Promise execution tracking</a></li>
<li><a href="#all_async_hooks_javascript-embedder-api">JavaScript embedder API</a>
<ul>
<li><a href="#all_async_hooks_class-asyncresource">Class: <code>AsyncResource</code></a></li>
</ul>
</li>
<li><a href="#all_async_hooks_class-asynclocalstorage">Class: <code>AsyncLocalStorage</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_buffer_buffer">Buffer</a></span>
<ul>
<li><a href="#all_buffer_buffers-and-character-encodings">Buffers and character encodings</a></li>
<li><a href="#all_buffer_buffers-and-typedarrays">Buffers and TypedArrays</a></li>
<li><a href="#all_buffer_buffers-and-iteration">Buffers and iteration</a></li>
<li><a href="#all_buffer_class-blob">Class: <code>Blob</code></a>
<ul>
<li><a href="#all_buffer_new-bufferblobsources-options"><code>new buffer.Blob([sources[, options]])</code></a></li>
<li><a href="#all_buffer_blobarraybuffer"><code>blob.arrayBuffer()</code></a>
<ul>
<li><a href="#all_buffer_blobbytes"><code>blob.bytes()</code></a></li>
</ul>
</li>
<li><a href="#all_buffer_blobsize"><code>blob.size</code></a></li>
<li><a href="#all_buffer_blobslicestart-end-type"><code>blob.slice([start[, end[, type]]])</code></a></li>
<li><a href="#all_buffer_blobstream"><code>blob.stream()</code></a></li>
<li><a href="#all_buffer_blobtext"><code>blob.text()</code></a></li>
<li><a href="#all_buffer_blobtype"><code>blob.type</code></a></li>
<li><a href="#all_buffer_blob-objects-and-messagechannel"><code>Blob</code> objects and <code>MessageChannel</code></a></li>
</ul>
</li>
<li><a href="#all_buffer_class-buffer">Class: <code>Buffer</code></a>
<ul>
<li><a href="#all_buffer_static-method-bufferallocsize-fill-encoding">Static method: <code>Buffer.alloc(size[, fill[, encoding]])</code></a></li>
<li><a href="#all_buffer_static-method-bufferallocunsafesize">Static method: <code>Buffer.allocUnsafe(size)</code></a></li>
<li><a href="#all_buffer_static-method-bufferallocunsafeslowsize">Static method: <code>Buffer.allocUnsafeSlow(size)</code></a></li>
<li><a href="#all_buffer_static-method-bufferbytelengthstring-encoding">Static method: <code>Buffer.byteLength(string[, encoding])</code></a></li>
<li><a href="#all_buffer_static-method-buffercomparebuf1-buf2">Static method: <code>Buffer.compare(buf1, buf2)</code></a></li>
<li><a href="#all_buffer_static-method-bufferconcatlist-totallength">Static method: <code>Buffer.concat(list[, totalLength])</code></a></li>
<li><a href="#all_buffer_static-method-buffercopybytesfromview-offset-length">Static method: <code>Buffer.copyBytesFrom(view[, offset[, length]])</code></a></li>
<li><a href="#all_buffer_static-method-bufferfromarray">Static method: <code>Buffer.from(array)</code></a></li>
<li><a href="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length">Static method: <code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a></li>
<li><a href="#all_buffer_static-method-bufferfrombuffer">Static method: <code>Buffer.from(buffer)</code></a></li>
<li><a href="#all_buffer_static-method-bufferfromobject-offsetorencoding-length">Static method: <code>Buffer.from(object[, offsetOrEncoding[, length]])</code></a></li>
<li><a href="#all_buffer_static-method-bufferfromstring-encoding">Static method: <code>Buffer.from(string[, encoding])</code></a></li>
<li><a href="#all_buffer_static-method-bufferisbufferobj">Static method: <code>Buffer.isBuffer(obj)</code></a></li>
<li><a href="#all_buffer_static-method-bufferisencodingencoding">Static method: <code>Buffer.isEncoding(encoding)</code></a></li>
<li><a href="#all_buffer_class-property-bufferpoolsize">Class property: <code>Buffer.poolSize</code></a></li>
<li><a href="#all_buffer_bufindex"><code>buf[index]</code></a></li>
<li><a href="#all_buffer_bufbuffer"><code>buf.buffer</code></a></li>
<li><a href="#all_buffer_bufbyteoffset"><code>buf.byteOffset</code></a></li>
<li><a href="#all_buffer_bufcomparetarget-targetstart-targetend-sourcestart-sourceend"><code>buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])</code></a></li>
<li><a href="#all_buffer_bufcopytarget-targetstart-sourcestart-sourceend"><code>buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])</code></a></li>
<li><a href="#all_buffer_bufentries"><code>buf.entries()</code></a></li>
<li><a href="#all_buffer_bufequalsotherbuffer"><code>buf.equals(otherBuffer)</code></a></li>
<li><a href="#all_buffer_buffillvalue-offset-end-encoding"><code>buf.fill(value[, offset[, end]][, encoding])</code></a></li>
<li><a href="#all_buffer_bufincludesvalue-byteoffset-encoding"><code>buf.includes(value[, byteOffset][, encoding])</code></a></li>
<li><a href="#all_buffer_bufindexofvalue-byteoffset-encoding"><code>buf.indexOf(value[, byteOffset][, encoding])</code></a></li>
<li><a href="#all_buffer_bufkeys"><code>buf.keys()</code></a></li>
<li><a href="#all_buffer_buflastindexofvalue-byteoffset-encoding"><code>buf.lastIndexOf(value[, byteOffset][, encoding])</code></a></li>
<li><a href="#all_buffer_buflength"><code>buf.length</code></a></li>
<li><span class="stability_0"><a href="#all_buffer_bufparent"><code>buf.parent</code></a></span></li>
<li><a href="#all_buffer_bufreadbigint64beoffset"><code>buf.readBigInt64BE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadbigint64leoffset"><code>buf.readBigInt64LE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadbiguint64beoffset"><code>buf.readBigUInt64BE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadbiguint64leoffset"><code>buf.readBigUInt64LE([offset])</code></a></li>
<li><a href="#all_buffer_bufreaddoublebeoffset"><code>buf.readDoubleBE([offset])</code></a></li>
<li><a href="#all_buffer_bufreaddoubleleoffset"><code>buf.readDoubleLE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadfloatbeoffset"><code>buf.readFloatBE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadfloatleoffset"><code>buf.readFloatLE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadint8offset"><code>buf.readInt8([offset])</code></a></li>
<li><a href="#all_buffer_bufreadint16beoffset"><code>buf.readInt16BE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadint16leoffset"><code>buf.readInt16LE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadint32beoffset"><code>buf.readInt32BE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadint32leoffset"><code>buf.readInt32LE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadintbeoffset-bytelength"><code>buf.readIntBE(offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufreadintleoffset-bytelength"><code>buf.readIntLE(offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufreaduint8offset"><code>buf.readUInt8([offset])</code></a></li>
<li><a href="#all_buffer_bufreaduint16beoffset"><code>buf.readUInt16BE([offset])</code></a></li>
<li><a href="#all_buffer_bufreaduint16leoffset"><code>buf.readUInt16LE([offset])</code></a></li>
<li><a href="#all_buffer_bufreaduint32beoffset"><code>buf.readUInt32BE([offset])</code></a></li>
<li><a href="#all_buffer_bufreaduint32leoffset"><code>buf.readUInt32LE([offset])</code></a></li>
<li><a href="#all_buffer_bufreaduintbeoffset-bytelength"><code>buf.readUIntBE(offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufreaduintleoffset-bytelength"><code>buf.readUIntLE(offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufsubarraystart-end"><code>buf.subarray([start[, end]])</code></a></li>
<li><span class="stability_0"><a href="#all_buffer_bufslicestart-end"><code>buf.slice([start[, end]])</code></a></span></li>
<li><a href="#all_buffer_bufswap16"><code>buf.swap16()</code></a></li>
<li><a href="#all_buffer_bufswap32"><code>buf.swap32()</code></a></li>
<li><a href="#all_buffer_bufswap64"><code>buf.swap64()</code></a></li>
<li><a href="#all_buffer_buftojson"><code>buf.toJSON()</code></a></li>
<li><a href="#all_buffer_buftostringencoding-start-end"><code>buf.toString([encoding[, start[, end]]])</code></a></li>
<li><a href="#all_buffer_bufvalues"><code>buf.values()</code></a></li>
<li><a href="#all_buffer_bufwritestring-offset-length-encoding"><code>buf.write(string[, offset[, length]][, encoding])</code></a></li>
<li><a href="#all_buffer_bufwritebigint64bevalue-offset"><code>buf.writeBigInt64BE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritebigint64levalue-offset"><code>buf.writeBigInt64LE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritebiguint64bevalue-offset"><code>buf.writeBigUInt64BE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritebiguint64levalue-offset"><code>buf.writeBigUInt64LE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritedoublebevalue-offset"><code>buf.writeDoubleBE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritedoublelevalue-offset"><code>buf.writeDoubleLE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritefloatbevalue-offset"><code>buf.writeFloatBE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritefloatlevalue-offset"><code>buf.writeFloatLE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteint8value-offset"><code>buf.writeInt8(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteint16bevalue-offset"><code>buf.writeInt16BE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteint16levalue-offset"><code>buf.writeInt16LE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteint32bevalue-offset"><code>buf.writeInt32BE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteint32levalue-offset"><code>buf.writeInt32LE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteintbevalue-offset-bytelength"><code>buf.writeIntBE(value, offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufwriteintlevalue-offset-bytelength"><code>buf.writeIntLE(value, offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufwriteuint8value-offset"><code>buf.writeUInt8(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteuint16bevalue-offset"><code>buf.writeUInt16BE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteuint16levalue-offset"><code>buf.writeUInt16LE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteuint32bevalue-offset"><code>buf.writeUInt32BE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteuint32levalue-offset"><code>buf.writeUInt32LE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteuintbevalue-offset-bytelength"><code>buf.writeUIntBE(value, offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufwriteuintlevalue-offset-bytelength"><code>buf.writeUIntLE(value, offset, byteLength)</code></a></li>
<li><span class="stability_0"><a href="#all_buffer_new-bufferarray"><code>new Buffer(array)</code></a></span></li>
<li><span class="stability_0"><a href="#all_buffer_new-bufferarraybuffer-byteoffset-length"><code>new Buffer(arrayBuffer[, byteOffset[, length]])</code></a></span></li>
<li><span class="stability_0"><a href="#all_buffer_new-bufferbuffer"><code>new Buffer(buffer)</code></a></span></li>
<li><span class="stability_0"><a href="#all_buffer_new-buffersize"><code>new Buffer(size)</code></a></span></li>
<li><span class="stability_0"><a href="#all_buffer_new-bufferstring-encoding"><code>new Buffer(string[, encoding])</code></a></span></li>
</ul>
</li>
<li><a href="#all_buffer_class-file">Class: <code>File</code></a>
<ul>
<li><a href="#all_buffer_new-bufferfilesources-filename-options"><code>new buffer.File(sources, fileName[, options])</code></a></li>
<li><a href="#all_buffer_filename"><code>file.name</code></a></li>
<li><a href="#all_buffer_filelastmodified"><code>file.lastModified</code></a></li>
</ul>
</li>
<li><a href="#all_buffer_nodebuffer-module-apis"><code>node:buffer</code> module APIs</a>
<ul>
<li><span class="stability_3"><a href="#all_buffer_bufferatobdata"><code>buffer.atob(data)</code></a></span></li>
<li><span class="stability_3"><a href="#all_buffer_bufferbtoadata"><code>buffer.btoa(data)</code></a></span></li>
<li><a href="#all_buffer_bufferisasciiinput"><code>buffer.isAscii(input)</code></a></li>
<li><a href="#all_buffer_bufferisutf8input"><code>buffer.isUtf8(input)</code></a></li>
<li><a href="#all_buffer_bufferinspect_max_bytes"><code>buffer.INSPECT_MAX_BYTES</code></a></li>
<li><a href="#all_buffer_bufferkmaxlength"><code>buffer.kMaxLength</code></a></li>
<li><a href="#all_buffer_bufferkstringmaxlength"><code>buffer.kStringMaxLength</code></a></li>
<li><span class="stability_1"><a href="#all_buffer_bufferresolveobjecturlid"><code>buffer.resolveObjectURL(id)</code></a></span></li>
<li><a href="#all_buffer_buffertranscodesource-fromenc-toenc"><code>buffer.transcode(source, fromEnc, toEnc)</code></a></li>
<li><span class="stability_0"><a href="#all_buffer_class-slowbuffer">Class: <code>SlowBuffer</code></a></span>
<ul>
<li><span class="stability_0"><a href="#all_buffer_new-slowbuffersize"><code>new SlowBuffer(size)</code></a></span></li>
</ul>
</li>
<li><a href="#all_buffer_buffer-constants">Buffer constants</a>
<ul>
<li><a href="#all_buffer_bufferconstantsmax_length"><code>buffer.constants.MAX_LENGTH</code></a></li>
<li><a href="#all_buffer_bufferconstantsmax_string_length"><code>buffer.constants.MAX_STRING_LENGTH</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_buffer_bufferfrom-bufferalloc-and-bufferallocunsafe"><code>Buffer.from()</code>, <code>Buffer.alloc()</code>, and <code>Buffer.allocUnsafe()</code></a>
<ul>
<li><a href="#all_buffer_the---zero-fill-buffers-command-line-option">The <code>--zero-fill-buffers</code> command-line option</a></li>
<li><a href="#all_buffer_what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe">What makes <code>Buffer.allocUnsafe()</code> and <code>Buffer.allocUnsafeSlow()</code> "unsafe"?</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_addons_c-addons">C++ addons</a>
<ul>
<li><a href="#all_addons_hello-world">Hello world</a>
<ul>
<li><a href="#all_addons_context-aware-addons">Context-aware addons</a>
<ul>
<li><a href="#all_addons_worker-support">Worker support</a></li>
</ul>
</li>
<li><a href="#all_addons_building">Building</a></li>
<li><a href="#all_addons_linking-to-libraries-included-with-nodejs">Linking to libraries included with Node.js</a></li>
<li><a href="#all_addons_loading-addons-using-require">Loading addons using <code>require()</code></a></li>
</ul>
</li>
<li><a href="#all_addons_native-abstractions-for-nodejs">Native abstractions for Node.js</a></li>
<li><span class="stability_2"><a href="#all_addons_node-api">Node-API</a></span></li>
<li><a href="#all_addons_addon-examples">Addon examples</a>
<ul>
<li><a href="#all_addons_function-arguments">Function arguments</a></li>
<li><a href="#all_addons_callbacks">Callbacks</a></li>
<li><a href="#all_addons_object-factory">Object factory</a></li>
<li><a href="#all_addons_function-factory">Function factory</a></li>
<li><a href="#all_addons_wrapping-c-objects">Wrapping C++ objects</a></li>
<li><a href="#all_addons_factory-of-wrapped-objects">Factory of wrapped objects</a></li>
<li><a href="#all_addons_passing-wrapped-objects-around">Passing wrapped objects around</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_n-api_node-api">Node-API</a></span>
<ul>
<li><a href="#all_n-api_implications-of-abi-stability">Implications of ABI stability</a></li>
<li><a href="#all_n-api_building">Building</a>
<ul>
<li><a href="#all_n-api_build-tools">Build tools</a>
<ul>
<li><a href="#all_n-api_node-gyp">node-gyp</a></li>
<li><a href="#all_n-api_cmakejs">CMake.js</a></li>
</ul>
</li>
<li><a href="#all_n-api_uploading-precompiled-binaries">Uploading precompiled binaries</a>
<ul>
<li><a href="#all_n-api_node-pre-gyp">node-pre-gyp</a></li>
<li><a href="#all_n-api_prebuild">prebuild</a></li>
<li><a href="#all_n-api_prebuildify">prebuildify</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_n-api_usage">Usage</a></li>
<li><a href="#all_n-api_node-api-version-matrix">Node-API version matrix</a></li>
<li><a href="#all_n-api_environment-life-cycle-apis">Environment life cycle APIs</a>
<ul>
<li><a href="#all_n-api_napi_set_instance_data"><code>napi_set_instance_data</code></a></li>
<li><a href="#all_n-api_napi_get_instance_data"><code>napi_get_instance_data</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_basic-node-api-data-types">Basic Node-API data types</a>
<ul>
<li><a href="#all_n-api_napi_status"><code>napi_status</code></a></li>
<li><a href="#all_n-api_napi_extended_error_info"><code>napi_extended_error_info</code></a></li>
<li><a href="#all_n-api_napi_env"><code>napi_env</code></a></li>
<li><span class="stability_1"><a href="#all_n-api_node_api_basic_env"><code>node_api_basic_env</code></a></span></li>
<li><a href="#all_n-api_napi_value"><code>napi_value</code></a></li>
<li><a href="#all_n-api_napi_threadsafe_function"><code>napi_threadsafe_function</code></a></li>
<li><a href="#all_n-api_napi_threadsafe_function_release_mode"><code>napi_threadsafe_function_release_mode</code></a></li>
<li><a href="#all_n-api_napi_threadsafe_function_call_mode"><code>napi_threadsafe_function_call_mode</code></a></li>
<li><a href="#all_n-api_node-api-memory-management-types">Node-API memory management types</a>
<ul>
<li><a href="#all_n-api_napi_handle_scope"><code>napi_handle_scope</code></a></li>
<li><a href="#all_n-api_napi_escapable_handle_scope"><code>napi_escapable_handle_scope</code></a></li>
<li><a href="#all_n-api_napi_ref"><code>napi_ref</code></a></li>
<li><a href="#all_n-api_napi_type_tag"><code>napi_type_tag</code></a></li>
<li><a href="#all_n-api_napi_async_cleanup_hook_handle"><code>napi_async_cleanup_hook_handle</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_node-api-callback-types">Node-API callback types</a>
<ul>
<li><a href="#all_n-api_napi_callback_info"><code>napi_callback_info</code></a></li>
<li><a href="#all_n-api_napi_callback"><code>napi_callback</code></a></li>
<li><span class="stability_1"><a href="#all_n-api_node_api_basic_finalize"><code>node_api_basic_finalize</code></a></span></li>
<li><a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a></li>
<li><a href="#all_n-api_napi_async_execute_callback"><code>napi_async_execute_callback</code></a></li>
<li><a href="#all_n-api_napi_async_complete_callback"><code>napi_async_complete_callback</code></a></li>
<li><a href="#all_n-api_napi_threadsafe_function_call_js"><code>napi_threadsafe_function_call_js</code></a></li>
<li><a href="#all_n-api_napi_cleanup_hook"><code>napi_cleanup_hook</code></a></li>
<li><a href="#all_n-api_napi_async_cleanup_hook"><code>napi_async_cleanup_hook</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_n-api_error-handling">Error handling</a>
<ul>
<li><a href="#all_n-api_return-values">Return values</a>
<ul>
<li><a href="#all_n-api_napi_get_last_error_info"><code>napi_get_last_error_info</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_exceptions">Exceptions</a>
<ul>
<li><a href="#all_n-api_napi_throw"><code>napi_throw</code></a></li>
<li><a href="#all_n-api_napi_throw_error"><code>napi_throw_error</code></a></li>
<li><a href="#all_n-api_napi_throw_type_error"><code>napi_throw_type_error</code></a></li>
<li><a href="#all_n-api_napi_throw_range_error"><code>napi_throw_range_error</code></a></li>
<li><a href="#all_n-api_node_api_throw_syntax_error"><code>node_api_throw_syntax_error</code></a></li>
<li><a href="#all_n-api_napi_is_error"><code>napi_is_error</code></a></li>
<li><a href="#all_n-api_napi_create_error"><code>napi_create_error</code></a></li>
<li><a href="#all_n-api_napi_create_type_error"><code>napi_create_type_error</code></a></li>
<li><a href="#all_n-api_napi_create_range_error"><code>napi_create_range_error</code></a></li>
<li><a href="#all_n-api_node_api_create_syntax_error"><code>node_api_create_syntax_error</code></a></li>
<li><a href="#all_n-api_napi_get_and_clear_last_exception"><code>napi_get_and_clear_last_exception</code></a></li>
<li><a href="#all_n-api_napi_is_exception_pending"><code>napi_is_exception_pending</code></a></li>
<li><a href="#all_n-api_napi_fatal_exception"><code>napi_fatal_exception</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_fatal-errors">Fatal errors</a>
<ul>
<li><a href="#all_n-api_napi_fatal_error"><code>napi_fatal_error</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_n-api_object-lifetime-management">Object lifetime management</a>
<ul>
<li><a href="#all_n-api_making-handle-lifespan-shorter-than-that-of-the-native-method">Making handle lifespan shorter than that of the native method</a>
<ul>
<li><a href="#all_n-api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a></li>
<li><a href="#all_n-api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a></li>
<li><a href="#all_n-api_napi_open_escapable_handle_scope"><code>napi_open_escapable_handle_scope</code></a></li>
<li><a href="#all_n-api_napi_close_escapable_handle_scope"><code>napi_close_escapable_handle_scope</code></a></li>
<li><a href="#all_n-api_napi_escape_handle"><code>napi_escape_handle</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_references-to-values-with-a-lifespan-longer-than-that-of-the-native-method">References to values with a lifespan longer than that of the native method</a>
<ul>
<li><a href="#all_n-api_napi_create_reference"><code>napi_create_reference</code></a></li>
<li><a href="#all_n-api_napi_delete_reference"><code>napi_delete_reference</code></a></li>
<li><a href="#all_n-api_napi_reference_ref"><code>napi_reference_ref</code></a></li>
<li><a href="#all_n-api_napi_reference_unref"><code>napi_reference_unref</code></a></li>
<li><a href="#all_n-api_napi_get_reference_value"><code>napi_get_reference_value</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_cleanup-on-exit-of-the-current-nodejs-environment">Cleanup on exit of the current Node.js environment</a>
<ul>
<li><a href="#all_n-api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a></li>
<li><a href="#all_n-api_napi_remove_env_cleanup_hook"><code>napi_remove_env_cleanup_hook</code></a></li>
<li><a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a></li>
<li><a href="#all_n-api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_finalization-on-the-exit-of-the-nodejs-environment">Finalization on the exit of the Node.js environment</a></li>
</ul>
</li>
<li><a href="#all_n-api_module-registration">Module registration</a></li>
<li><a href="#all_n-api_working-with-javascript-values">Working with JavaScript values</a>
<ul>
<li><a href="#all_n-api_enum-types">Enum types</a>
<ul>
<li><a href="#all_n-api_napi_key_collection_mode"><code>napi_key_collection_mode</code></a></li>
<li><a href="#all_n-api_napi_key_filter"><code>napi_key_filter</code></a></li>
<li><a href="#all_n-api_napi_key_conversion"><code>napi_key_conversion</code></a></li>
<li><a href="#all_n-api_napi_valuetype"><code>napi_valuetype</code></a></li>
<li><a href="#all_n-api_napi_typedarray_type"><code>napi_typedarray_type</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_object-creation-functions">Object creation functions</a>
<ul>
<li><a href="#all_n-api_napi_create_array"><code>napi_create_array</code></a></li>
<li><a href="#all_n-api_napi_create_array_with_length"><code>napi_create_array_with_length</code></a></li>
<li><a href="#all_n-api_napi_create_arraybuffer"><code>napi_create_arraybuffer</code></a></li>
<li><a href="#all_n-api_napi_create_buffer"><code>napi_create_buffer</code></a></li>
<li><a href="#all_n-api_napi_create_buffer_copy"><code>napi_create_buffer_copy</code></a></li>
<li><a href="#all_n-api_napi_create_date"><code>napi_create_date</code></a></li>
<li><a href="#all_n-api_napi_create_external"><code>napi_create_external</code></a></li>
<li><a href="#all_n-api_napi_create_external_arraybuffer"><code>napi_create_external_arraybuffer</code></a></li>
<li><a href="#all_n-api_napi_create_external_buffer"><code>napi_create_external_buffer</code></a></li>
<li><a href="#all_n-api_napi_create_object"><code>napi_create_object</code></a></li>
<li><a href="#all_n-api_napi_create_symbol"><code>napi_create_symbol</code></a></li>
<li><a href="#all_n-api_node_api_symbol_for"><code>node_api_symbol_for</code></a></li>
<li><a href="#all_n-api_napi_create_typedarray"><code>napi_create_typedarray</code></a></li>
<li><a href="#all_n-api_napi_create_dataview"><code>napi_create_dataview</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_functions-to-convert-from-c-types-to-node-api">Functions to convert from C types to Node-API</a>
<ul>
<li><a href="#all_n-api_napi_create_int32"><code>napi_create_int32</code></a></li>
<li><a href="#all_n-api_napi_create_uint32"><code>napi_create_uint32</code></a></li>
<li><a href="#all_n-api_napi_create_int64"><code>napi_create_int64</code></a></li>
<li><a href="#all_n-api_napi_create_double"><code>napi_create_double</code></a></li>
<li><a href="#all_n-api_napi_create_bigint_int64"><code>napi_create_bigint_int64</code></a></li>
<li><a href="#all_n-api_napi_create_bigint_uint64"><code>napi_create_bigint_uint64</code></a></li>
<li><a href="#all_n-api_napi_create_bigint_words"><code>napi_create_bigint_words</code></a></li>
<li><a href="#all_n-api_napi_create_string_latin1"><code>napi_create_string_latin1</code></a></li>
<li><span class="stability_1"><a href="#all_n-api_node_api_create_external_string_latin1"><code>node_api_create_external_string_latin1</code></a></span></li>
<li><a href="#all_n-api_napi_create_string_utf16"><code>napi_create_string_utf16</code></a></li>
<li><span class="stability_1"><a href="#all_n-api_node_api_create_external_string_utf16"><code>node_api_create_external_string_utf16</code></a></span></li>
<li><a href="#all_n-api_napi_create_string_utf8"><code>napi_create_string_utf8</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_functions-to-create-optimized-property-keys">Functions to create optimized property keys</a>
<ul>
<li><span class="stability_1"><a href="#all_n-api_node_api_create_property_key_latin1"><code>node_api_create_property_key_latin1</code></a></span></li>
<li><span class="stability_1"><a href="#all_n-api_node_api_create_property_key_utf16"><code>node_api_create_property_key_utf16</code></a></span></li>
<li><span class="stability_1"><a href="#all_n-api_node_api_create_property_key_utf8"><code>node_api_create_property_key_utf8</code></a></span></li>
</ul>
</li>
<li><a href="#all_n-api_functions-to-convert-from-node-api-to-c-types">Functions to convert from Node-API to C types</a>
<ul>
<li><a href="#all_n-api_napi_get_array_length"><code>napi_get_array_length</code></a></li>
<li><a href="#all_n-api_napi_get_arraybuffer_info"><code>napi_get_arraybuffer_info</code></a></li>
<li><a href="#all_n-api_napi_get_buffer_info"><code>napi_get_buffer_info</code></a></li>
<li><a href="#all_n-api_napi_get_prototype"><code>napi_get_prototype</code></a></li>
<li><a href="#all_n-api_napi_get_typedarray_info"><code>napi_get_typedarray_info</code></a></li>
<li><a href="#all_n-api_napi_get_dataview_info"><code>napi_get_dataview_info</code></a></li>
<li><a href="#all_n-api_napi_get_date_value"><code>napi_get_date_value</code></a></li>
<li><a href="#all_n-api_napi_get_value_bool"><code>napi_get_value_bool</code></a></li>
<li><a href="#all_n-api_napi_get_value_double"><code>napi_get_value_double</code></a></li>
<li><a href="#all_n-api_napi_get_value_bigint_int64"><code>napi_get_value_bigint_int64</code></a></li>
<li><a href="#all_n-api_napi_get_value_bigint_uint64"><code>napi_get_value_bigint_uint64</code></a></li>
<li><a href="#all_n-api_napi_get_value_bigint_words"><code>napi_get_value_bigint_words</code></a></li>
<li><a href="#all_n-api_napi_get_value_external"><code>napi_get_value_external</code></a></li>
<li><a href="#all_n-api_napi_get_value_int32"><code>napi_get_value_int32</code></a></li>
<li><a href="#all_n-api_napi_get_value_int64"><code>napi_get_value_int64</code></a></li>
<li><a href="#all_n-api_napi_get_value_string_latin1"><code>napi_get_value_string_latin1</code></a></li>
<li><a href="#all_n-api_napi_get_value_string_utf8"><code>napi_get_value_string_utf8</code></a></li>
<li><a href="#all_n-api_napi_get_value_string_utf16"><code>napi_get_value_string_utf16</code></a></li>
<li><a href="#all_n-api_napi_get_value_uint32"><code>napi_get_value_uint32</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_functions-to-get-global-instances">Functions to get global instances</a>
<ul>
<li><a href="#all_n-api_napi_get_boolean"><code>napi_get_boolean</code></a></li>
<li><a href="#all_n-api_napi_get_global"><code>napi_get_global</code></a></li>
<li><a href="#all_n-api_napi_get_null"><code>napi_get_null</code></a></li>
<li><a href="#all_n-api_napi_get_undefined"><code>napi_get_undefined</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_n-api_working-with-javascript-values-and-abstract-operations">Working with JavaScript values and abstract operations</a>
<ul>
<li><a href="#all_n-api_napi_coerce_to_bool"><code>napi_coerce_to_bool</code></a></li>
<li><a href="#all_n-api_napi_coerce_to_number"><code>napi_coerce_to_number</code></a></li>
<li><a href="#all_n-api_napi_coerce_to_object"><code>napi_coerce_to_object</code></a></li>
<li><a href="#all_n-api_napi_coerce_to_string"><code>napi_coerce_to_string</code></a></li>
<li><a href="#all_n-api_napi_typeof"><code>napi_typeof</code></a></li>
<li><a href="#all_n-api_napi_instanceof"><code>napi_instanceof</code></a></li>
<li><a href="#all_n-api_napi_is_array"><code>napi_is_array</code></a></li>
<li><a href="#all_n-api_napi_is_arraybuffer"><code>napi_is_arraybuffer</code></a></li>
<li><a href="#all_n-api_napi_is_buffer"><code>napi_is_buffer</code></a></li>
<li><a href="#all_n-api_napi_is_date"><code>napi_is_date</code></a></li>
<li><a href="#all_n-api_napi_is_error_1"><code>napi_is_error</code></a></li>
<li><a href="#all_n-api_napi_is_typedarray"><code>napi_is_typedarray</code></a></li>
<li><a href="#all_n-api_napi_is_dataview"><code>napi_is_dataview</code></a></li>
<li><a href="#all_n-api_napi_strict_equals"><code>napi_strict_equals</code></a></li>
<li><a href="#all_n-api_napi_detach_arraybuffer"><code>napi_detach_arraybuffer</code></a></li>
<li><a href="#all_n-api_napi_is_detached_arraybuffer"><code>napi_is_detached_arraybuffer</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_working-with-javascript-properties">Working with JavaScript properties</a>
<ul>
<li><a href="#all_n-api_structures">Structures</a>
<ul>
<li><a href="#all_n-api_napi_property_attributes"><code>napi_property_attributes</code></a></li>
<li><a href="#all_n-api_napi_property_descriptor"><code>napi_property_descriptor</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_functions">Functions</a>
<ul>
<li><a href="#all_n-api_napi_get_property_names"><code>napi_get_property_names</code></a></li>
<li><a href="#all_n-api_napi_get_all_property_names"><code>napi_get_all_property_names</code></a></li>
<li><a href="#all_n-api_napi_set_property"><code>napi_set_property</code></a></li>
<li><a href="#all_n-api_napi_get_property"><code>napi_get_property</code></a></li>
<li><a href="#all_n-api_napi_has_property"><code>napi_has_property</code></a></li>
<li><a href="#all_n-api_napi_delete_property"><code>napi_delete_property</code></a></li>
<li><a href="#all_n-api_napi_has_own_property"><code>napi_has_own_property</code></a></li>
<li><a href="#all_n-api_napi_set_named_property"><code>napi_set_named_property</code></a></li>
<li><a href="#all_n-api_napi_get_named_property"><code>napi_get_named_property</code></a></li>
<li><a href="#all_n-api_napi_has_named_property"><code>napi_has_named_property</code></a></li>
<li><a href="#all_n-api_napi_set_element"><code>napi_set_element</code></a></li>
<li><a href="#all_n-api_napi_get_element"><code>napi_get_element</code></a></li>
<li><a href="#all_n-api_napi_has_element"><code>napi_has_element</code></a></li>
<li><a href="#all_n-api_napi_delete_element"><code>napi_delete_element</code></a></li>
<li><a href="#all_n-api_napi_define_properties"><code>napi_define_properties</code></a></li>
<li><a href="#all_n-api_napi_object_freeze"><code>napi_object_freeze</code></a></li>
<li><a href="#all_n-api_napi_object_seal"><code>napi_object_seal</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_n-api_working-with-javascript-functions">Working with JavaScript functions</a>
<ul>
<li><a href="#all_n-api_napi_call_function"><code>napi_call_function</code></a></li>
<li><a href="#all_n-api_napi_create_function"><code>napi_create_function</code></a></li>
<li><a href="#all_n-api_napi_get_cb_info"><code>napi_get_cb_info</code></a></li>
<li><a href="#all_n-api_napi_get_new_target"><code>napi_get_new_target</code></a></li>
<li><a href="#all_n-api_napi_new_instance"><code>napi_new_instance</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_object-wrap">Object wrap</a>
<ul>
<li><a href="#all_n-api_napi_define_class"><code>napi_define_class</code></a></li>
<li><a href="#all_n-api_napi_wrap"><code>napi_wrap</code></a></li>
<li><a href="#all_n-api_napi_unwrap"><code>napi_unwrap</code></a></li>
<li><a href="#all_n-api_napi_remove_wrap"><code>napi_remove_wrap</code></a></li>
<li><a href="#all_n-api_napi_type_tag_object"><code>napi_type_tag_object</code></a></li>
<li><a href="#all_n-api_napi_check_object_type_tag"><code>napi_check_object_type_tag</code></a></li>
<li><a href="#all_n-api_napi_add_finalizer"><code>napi_add_finalizer</code></a>
<ul>
<li><span class="stability_1"><a href="#all_n-api_node_api_post_finalizer"><code>node_api_post_finalizer</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_n-api_simple-asynchronous-operations">Simple asynchronous operations</a>
<ul>
<li><a href="#all_n-api_napi_create_async_work"><code>napi_create_async_work</code></a></li>
<li><a href="#all_n-api_napi_delete_async_work"><code>napi_delete_async_work</code></a></li>
<li><a href="#all_n-api_napi_queue_async_work"><code>napi_queue_async_work</code></a></li>
<li><a href="#all_n-api_napi_cancel_async_work"><code>napi_cancel_async_work</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_custom-asynchronous-operations">Custom asynchronous operations</a>
<ul>
<li><a href="#all_n-api_napi_async_init"><code>napi_async_init</code></a></li>
<li><a href="#all_n-api_napi_async_destroy"><code>napi_async_destroy</code></a></li>
<li><a href="#all_n-api_napi_make_callback"><code>napi_make_callback</code></a></li>
<li><a href="#all_n-api_napi_open_callback_scope"><code>napi_open_callback_scope</code></a></li>
<li><a href="#all_n-api_napi_close_callback_scope"><code>napi_close_callback_scope</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_version-management">Version management</a>
<ul>
<li><a href="#all_n-api_napi_get_node_version"><code>napi_get_node_version</code></a></li>
<li><a href="#all_n-api_napi_get_version"><code>napi_get_version</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_memory-management">Memory management</a>
<ul>
<li><a href="#all_n-api_napi_adjust_external_memory"><code>napi_adjust_external_memory</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_promises">Promises</a>
<ul>
<li><a href="#all_n-api_napi_create_promise"><code>napi_create_promise</code></a></li>
<li><a href="#all_n-api_napi_resolve_deferred"><code>napi_resolve_deferred</code></a></li>
<li><a href="#all_n-api_napi_reject_deferred"><code>napi_reject_deferred</code></a></li>
<li><a href="#all_n-api_napi_is_promise"><code>napi_is_promise</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_script-execution">Script execution</a>
<ul>
<li><a href="#all_n-api_napi_run_script"><code>napi_run_script</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_libuv-event-loop">libuv event loop</a>
<ul>
<li><a href="#all_n-api_napi_get_uv_event_loop"><code>napi_get_uv_event_loop</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_asynchronous-thread-safe-function-calls">Asynchronous thread-safe function calls</a>
<ul>
<li><a href="#all_n-api_calling-a-thread-safe-function">Calling a thread-safe function</a></li>
<li><a href="#all_n-api_reference-counting-of-thread-safe-functions">Reference counting of thread-safe functions</a></li>
<li><a href="#all_n-api_deciding-whether-to-keep-the-process-running">Deciding whether to keep the process running</a></li>
<li><a href="#all_n-api_napi_create_threadsafe_function"><code>napi_create_threadsafe_function</code></a></li>
<li><a href="#all_n-api_napi_get_threadsafe_function_context"><code>napi_get_threadsafe_function_context</code></a></li>
<li><a href="#all_n-api_napi_call_threadsafe_function"><code>napi_call_threadsafe_function</code></a></li>
<li><a href="#all_n-api_napi_acquire_threadsafe_function"><code>napi_acquire_threadsafe_function</code></a></li>
<li><a href="#all_n-api_napi_release_threadsafe_function"><code>napi_release_threadsafe_function</code></a></li>
<li><a href="#all_n-api_napi_ref_threadsafe_function"><code>napi_ref_threadsafe_function</code></a></li>
<li><a href="#all_n-api_napi_unref_threadsafe_function"><code>napi_unref_threadsafe_function</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_miscellaneous-utilities">Miscellaneous utilities</a>
<ul>
<li><a href="#all_n-api_node_api_get_module_file_name"><code>node_api_get_module_file_name</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_embedding_c-embedder-api">C++ embedder API</a>
<ul>
<li><a href="#all_embedding_example-embedding-application">Example embedding application</a>
<ul>
<li><a href="#all_embedding_setting-up-a-per-process-state">Setting up a per-process state</a></li>
<li><a href="#all_embedding_setting-up-a-per-instance-state">Setting up a per-instance state</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_child_process_child-process">Child process</a></span>
<ul>
<li><a href="#all_child_process_asynchronous-process-creation">Asynchronous process creation</a>
<ul>
<li><a href="#all_child_process_spawning-bat-and-cmd-files-on-windows">Spawning <code>.bat</code> and <code>.cmd</code> files on Windows</a></li>
<li><a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec(command[, options][, callback])</code></a></li>
<li><a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile(file[, args][, options][, callback])</code></a></li>
<li><a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork(modulePath[, args][, options])</code></a></li>
<li><a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn(command[, args][, options])</code></a>
<ul>
<li><a href="#all_child_process_optionsdetached"><code>options.detached</code></a></li>
<li><a href="#all_child_process_optionsstdio"><code>options.stdio</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_child_process_synchronous-process-creation">Synchronous process creation</a>
<ul>
<li><a href="#all_child_process_child_processexecfilesyncfile-args-options"><code>child_process.execFileSync(file[, args][, options])</code></a></li>
<li><a href="#all_child_process_child_processexecsynccommand-options"><code>child_process.execSync(command[, options])</code></a></li>
<li><a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync(command[, args][, options])</code></a></li>
</ul>
</li>
<li><a href="#all_child_process_class-childprocess">Class: <code>ChildProcess</code></a>
<ul>
<li><a href="#all_child_process_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_child_process_event-disconnect">Event: <code>'disconnect'</code></a></li>
<li><a href="#all_child_process_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_child_process_event-exit">Event: <code>'exit'</code></a></li>
<li><a href="#all_child_process_event-message">Event: <code>'message'</code></a></li>
<li><a href="#all_child_process_event-spawn">Event: <code>'spawn'</code></a></li>
<li><a href="#all_child_process_subprocesschannel"><code>subprocess.channel</code></a>
<ul>
<li><a href="#all_child_process_subprocesschannelref"><code>subprocess.channel.ref()</code></a></li>
<li><a href="#all_child_process_subprocesschannelunref"><code>subprocess.channel.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_child_process_subprocessconnected"><code>subprocess.connected</code></a></li>
<li><a href="#all_child_process_subprocessdisconnect"><code>subprocess.disconnect()</code></a></li>
<li><a href="#all_child_process_subprocessexitcode"><code>subprocess.exitCode</code></a></li>
<li><a href="#all_child_process_subprocesskillsignal"><code>subprocess.kill([signal])</code></a></li>
<li><span class="stability_1"><a href="#all_child_process_subprocesssymboldispose"><code>subprocess[Symbol.dispose]()</code></a></span></li>
<li><a href="#all_child_process_subprocesskilled"><code>subprocess.killed</code></a></li>
<li><a href="#all_child_process_subprocesspid"><code>subprocess.pid</code></a></li>
<li><a href="#all_child_process_subprocessref"><code>subprocess.ref()</code></a></li>
<li><a href="#all_child_process_subprocesssendmessage-sendhandle-options-callback"><code>subprocess.send(message[, sendHandle[, options]][, callback])</code></a>
<ul>
<li><a href="#all_child_process_example-sending-a-server-object">Example: sending a server object</a></li>
<li><a href="#all_child_process_example-sending-a-socket-object">Example: sending a socket object</a></li>
</ul>
</li>
<li><a href="#all_child_process_subprocesssignalcode"><code>subprocess.signalCode</code></a></li>
<li><a href="#all_child_process_subprocessspawnargs"><code>subprocess.spawnargs</code></a></li>
<li><a href="#all_child_process_subprocessspawnfile"><code>subprocess.spawnfile</code></a></li>
<li><a href="#all_child_process_subprocessstderr"><code>subprocess.stderr</code></a></li>
<li><a href="#all_child_process_subprocessstdin"><code>subprocess.stdin</code></a></li>
<li><a href="#all_child_process_subprocessstdio"><code>subprocess.stdio</code></a></li>
<li><a href="#all_child_process_subprocessstdout"><code>subprocess.stdout</code></a></li>
<li><a href="#all_child_process_subprocessunref"><code>subprocess.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_child_process_maxbuffer-and-unicode"><code>maxBuffer</code> and Unicode</a></li>
<li><a href="#all_child_process_shell-requirements">Shell requirements</a></li>
<li><a href="#all_child_process_default-windows-shell">Default Windows shell</a></li>
<li><a href="#all_child_process_advanced-serialization">Advanced serialization</a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_cluster_cluster">Cluster</a></span>
<ul>
<li><a href="#all_cluster_how-it-works">How it works</a></li>
<li><a href="#all_cluster_class-worker">Class: <code>Worker</code></a>
<ul>
<li><a href="#all_cluster_event-disconnect">Event: <code>'disconnect'</code></a></li>
<li><a href="#all_cluster_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_cluster_event-exit">Event: <code>'exit'</code></a></li>
<li><a href="#all_cluster_event-listening">Event: <code>'listening'</code></a></li>
<li><a href="#all_cluster_event-message">Event: <code>'message'</code></a></li>
<li><a href="#all_cluster_event-online">Event: <code>'online'</code></a></li>
<li><a href="#all_cluster_workerdisconnect"><code>worker.disconnect()</code></a></li>
<li><a href="#all_cluster_workerexitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a></li>
<li><a href="#all_cluster_workerid"><code>worker.id</code></a></li>
<li><a href="#all_cluster_workerisconnected"><code>worker.isConnected()</code></a></li>
<li><a href="#all_cluster_workerisdead"><code>worker.isDead()</code></a></li>
<li><a href="#all_cluster_workerkillsignal"><code>worker.kill([signal])</code></a></li>
<li><a href="#all_cluster_workerprocess"><code>worker.process</code></a></li>
<li><a href="#all_cluster_workersendmessage-sendhandle-options-callback"><code>worker.send(message[, sendHandle[, options]][, callback])</code></a></li>
</ul>
</li>
<li><a href="#all_cluster_event-disconnect_1">Event: <code>'disconnect'</code></a></li>
<li><a href="#all_cluster_event-exit_1">Event: <code>'exit'</code></a></li>
<li><a href="#all_cluster_event-fork">Event: <code>'fork'</code></a></li>
<li><a href="#all_cluster_event-listening_1">Event: <code>'listening'</code></a></li>
<li><a href="#all_cluster_event-message_1">Event: <code>'message'</code></a></li>
<li><a href="#all_cluster_event-online_1">Event: <code>'online'</code></a></li>
<li><a href="#all_cluster_event-setup">Event: <code>'setup'</code></a></li>
<li><a href="#all_cluster_clusterdisconnectcallback"><code>cluster.disconnect([callback])</code></a></li>
<li><a href="#all_cluster_clusterforkenv"><code>cluster.fork([env])</code></a></li>
<li><span class="stability_0"><a href="#all_cluster_clusterismaster"><code>cluster.isMaster</code></a></span></li>
<li><a href="#all_cluster_clusterisprimary"><code>cluster.isPrimary</code></a></li>
<li><a href="#all_cluster_clusterisworker"><code>cluster.isWorker</code></a></li>
<li><a href="#all_cluster_clusterschedulingpolicy"><code>cluster.schedulingPolicy</code></a></li>
<li><a href="#all_cluster_clustersettings"><code>cluster.settings</code></a></li>
<li><span class="stability_0"><a href="#all_cluster_clustersetupmastersettings"><code>cluster.setupMaster([settings])</code></a></span></li>
<li><a href="#all_cluster_clustersetupprimarysettings"><code>cluster.setupPrimary([settings])</code></a></li>
<li><a href="#all_cluster_clusterworker"><code>cluster.worker</code></a></li>
<li><a href="#all_cluster_clusterworkers"><code>cluster.workers</code></a></li>
</ul>
</li>
<li><a href="#all_cli_command-line-api">Command-line API</a>
<ul>
<li><a href="#all_cli_synopsis">Synopsis</a></li>
<li><a href="#all_cli_program-entry-point">Program entry point</a>
<ul>
<li><a href="#all_cli_ecmascript-modules-loader-entry-point-caveat">ECMAScript modules loader entry point caveat</a></li>
</ul>
</li>
<li><a href="#all_cli_options">Options</a>
<ul>
<li><a href="#all_cli_-"><code>-</code></a></li>
<li><a href="#all_cli_--"><code>--</code></a></li>
<li><a href="#all_cli_--abort-on-uncaught-exception"><code>--abort-on-uncaught-exception</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--allow-addons"><code>--allow-addons</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--allow-child-process"><code>--allow-child-process</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--allow-fs-read"><code>--allow-fs-read</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--allow-fs-write"><code>--allow-fs-write</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--allow-wasi"><code>--allow-wasi</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--allow-worker"><code>--allow-worker</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--build-snapshot"><code>--build-snapshot</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--build-snapshot-config"><code>--build-snapshot-config</code></a></span></li>
<li><a href="#all_cli_-c---check"><code>-c</code>, <code>--check</code></a></li>
<li><a href="#all_cli_--completion-bash"><code>--completion-bash</code></a></li>
<li><span class="stability_2"><a href="#all_cli_-c-condition---conditionscondition"><code>-C condition</code>, <code>--conditions=condition</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--cpu-prof"><code>--cpu-prof</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--cpu-prof-dir"><code>--cpu-prof-dir</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--cpu-prof-interval"><code>--cpu-prof-interval</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--cpu-prof-name"><code>--cpu-prof-name</code></a></span></li>
<li><a href="#all_cli_--diagnostic-dirdirectory"><code>--diagnostic-dir=directory</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--disable-warningcode-or-type"><code>--disable-warning=code-or-type</code></a></span></li>
<li><a href="#all_cli_--disable-wasm-trap-handler"><code>--disable-wasm-trap-handler</code></a></li>
<li><a href="#all_cli_--disable-protomode"><code>--disable-proto=mode</code></a></li>
<li><a href="#all_cli_--disallow-code-generation-from-strings"><code>--disallow-code-generation-from-strings</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--expose-gc"><code>--expose-gc</code></a></span></li>
<li><a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order=order</code></a></li>
<li><a href="#all_cli_--enable-fips"><code>--enable-fips</code></a></li>
<li><a href="#all_cli_--enable-source-maps"><code>--enable-source-maps</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--env-fileconfig"><code>--env-file=config</code></a></span></li>
<li><a href="#all_cli_-e---eval-script"><code>-e</code>, <code>--eval "script"</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type=type</code></a></span></li>
<li><a href="#all_cli_--experimental-eventsource"><code>--experimental-eventsource</code></a></li>
<li><a href="#all_cli_--experimental-import-meta-resolve"><code>--experimental-import-meta-resolve</code></a></li>
<li><a href="#all_cli_--experimental-loadermodule"><code>--experimental-loader=module</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-network-imports"><code>--experimental-network-imports</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-network-inspection"><code>--experimental-network-inspection</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-permission"><code>--experimental-permission</code></a></span></li>
<li><span class="stability_0"><a href="#all_cli_--experimental-policy"><code>--experimental-policy</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-require-module"><code>--experimental-require-module</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-sea-config"><code>--experimental-sea-config</code></a></span></li>
<li><a href="#all_cli_--experimental-shadow-realm"><code>--experimental-shadow-realm</code></a></li>
<li><a href="#all_cli_--experimental-test-coverage"><code>--experimental-test-coverage</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-test-module-mocks"><code>--experimental-test-module-mocks</code></a></span></li>
<li><a href="#all_cli_--experimental-vm-modules"><code>--experimental-vm-modules</code></a></li>
<li><a href="#all_cli_--experimental-wasi-unstable-preview1"><code>--experimental-wasi-unstable-preview1</code></a></li>
<li><a href="#all_cli_--experimental-wasm-modules"><code>--experimental-wasm-modules</code></a></li>
<li><a href="#all_cli_--experimental-websocket"><code>--experimental-websocket</code></a></li>
<li><a href="#all_cli_--force-context-aware"><code>--force-context-aware</code></a></li>
<li><a href="#all_cli_--force-fips"><code>--force-fips</code></a></li>
<li><a href="#all_cli_--force-node-api-uncaught-exceptions-policy"><code>--force-node-api-uncaught-exceptions-policy</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--frozen-intrinsics"><code>--frozen-intrinsics</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--heap-prof"><code>--heap-prof</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--heap-prof-dir"><code>--heap-prof-dir</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--heap-prof-interval"><code>--heap-prof-interval</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--heap-prof-name"><code>--heap-prof-name</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--heapsnapshot-near-heap-limitmax_count"><code>--heapsnapshot-near-heap-limit=max_count</code></a></span></li>
<li><a href="#all_cli_--heapsnapshot-signalsignal"><code>--heapsnapshot-signal=signal</code></a></li>
<li><a href="#all_cli_-h---help"><code>-h</code>, <code>--help</code></a></li>
<li><a href="#all_cli_--icu-data-dirfile"><code>--icu-data-dir=file</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--importmodule"><code>--import=module</code></a></span></li>
<li><a href="#all_cli_--input-typetype"><code>--input-type=type</code></a></li>
<li><a href="#all_cli_--insecure-http-parser"><code>--insecure-http-parser</code></a></li>
<li><a href="#all_cli_--inspecthostport"><code>--inspect[=[host:]port]</code></a>
<ul>
<li><a href="#all_cli_warning-binding-inspector-to-a-public-ipport-combination-is-insecure">Warning: binding inspector to a public IP:port combination is insecure</a></li>
</ul>
</li>
<li><a href="#all_cli_--inspect-brkhostport"><code>--inspect-brk[=[host:]port]</code></a></li>
<li><a href="#all_cli_--inspect-porthostport"><code>--inspect-port=[host:]port</code></a></li>
<li><a href="#all_cli_--inspect-publish-uidstderrhttp"><code>--inspect-publish-uid=stderr,http</code></a></li>
<li><a href="#all_cli_--inspect-waithostport"><code>--inspect-wait[=[host:]port]</code></a></li>
<li><a href="#all_cli_-i---interactive"><code>-i</code>, <code>--interactive</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--jitless"><code>--jitless</code></a></span></li>
<li><a href="#all_cli_--max-http-header-sizesize"><code>--max-http-header-size=size</code></a></li>
<li><a href="#all_cli_--napi-modules"><code>--napi-modules</code></a></li>
<li><a href="#all_cli_--network-family-autoselection-attempt-timeout"><code>--network-family-autoselection-attempt-timeout</code></a></li>
<li><a href="#all_cli_--no-addons"><code>--no-addons</code></a></li>
<li><a href="#all_cli_--no-deprecation"><code>--no-deprecation</code></a></li>
<li><a href="#all_cli_--no-experimental-detect-module"><code>--no-experimental-detect-module</code></a></li>
<li><a href="#all_cli_--no-experimental-fetch"><code>--no-experimental-fetch</code></a></li>
<li><a href="#all_cli_--no-experimental-global-customevent"><code>--no-experimental-global-customevent</code></a></li>
<li><a href="#all_cli_--no-experimental-global-webcrypto"><code>--no-experimental-global-webcrypto</code></a></li>
<li><a href="#all_cli_--no-experimental-repl-await"><code>--no-experimental-repl-await</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--no-experimental-require-module"><code>--no-experimental-require-module</code></a></span></li>
<li><a href="#all_cli_--no-extra-info-on-fatal-exception"><code>--no-extra-info-on-fatal-exception</code></a></li>
<li><a href="#all_cli_--no-force-async-hooks-checks"><code>--no-force-async-hooks-checks</code></a></li>
<li><a href="#all_cli_--no-global-search-paths"><code>--no-global-search-paths</code></a></li>
<li><a href="#all_cli_--no-network-family-autoselection"><code>--no-network-family-autoselection</code></a></li>
<li><a href="#all_cli_--no-warnings"><code>--no-warnings</code></a></li>
<li><a href="#all_cli_--node-memory-debug"><code>--node-memory-debug</code></a></li>
<li><a href="#all_cli_--openssl-configfile"><code>--openssl-config=file</code></a></li>
<li><a href="#all_cli_--openssl-legacy-provider"><code>--openssl-legacy-provider</code></a></li>
<li><a href="#all_cli_--openssl-shared-config"><code>--openssl-shared-config</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--env-file-if-existsconfig"><code>--env-file-if-exists=config</code></a></span></li>
<li><a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a></li>
<li><span class="stability_0"><a href="#all_cli_--policy-integritysri"><code>--policy-integrity=sri</code></a></span></li>
<li><a href="#all_cli_--preserve-symlinks"><code>--preserve-symlinks</code></a></li>
<li><a href="#all_cli_--preserve-symlinks-main"><code>--preserve-symlinks-main</code></a></li>
<li><a href="#all_cli_-p---print-script"><code>-p</code>, <code>--print "script"</code></a></li>
<li><a href="#all_cli_--experimental-print-required-tla"><code>--experimental-print-required-tla</code></a></li>
<li><a href="#all_cli_--prof"><code>--prof</code></a></li>
<li><a href="#all_cli_--prof-process"><code>--prof-process</code></a></li>
<li><a href="#all_cli_--redirect-warningsfile"><code>--redirect-warnings=file</code></a></li>
<li><a href="#all_cli_--report-compact"><code>--report-compact</code></a></li>
<li><a href="#all_cli_--report-dirdirectory-report-directorydirectory"><code>--report-dir=directory</code>, <code>report-directory=directory</code></a></li>
<li><a href="#all_cli_--report-filenamefilename"><code>--report-filename=filename</code></a></li>
<li><a href="#all_cli_--report-on-fatalerror"><code>--report-on-fatalerror</code></a></li>
<li><a href="#all_cli_--report-on-signal"><code>--report-on-signal</code></a></li>
<li><a href="#all_cli_--report-signalsignal"><code>--report-signal=signal</code></a></li>
<li><a href="#all_cli_--report-uncaught-exception"><code>--report-uncaught-exception</code></a></li>
<li><a href="#all_cli_--report-exclude-network"><code>--report-exclude-network</code></a></li>
<li><a href="#all_cli_-r---require-module"><code>-r</code>, <code>--require module</code></a></li>
<li><a href="#all_cli_--secure-heapn"><code>--secure-heap=n</code></a></li>
<li><a href="#all_cli_--secure-heap-minn"><code>--secure-heap-min=n</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--snapshot-blobpath"><code>--snapshot-blob=path</code></a></span></li>
<li><a href="#all_cli_--test"><code>--test</code></a></li>
<li><a href="#all_cli_--test-concurrency"><code>--test-concurrency</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--test-coverage-exclude"><code>--test-coverage-exclude</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--test-coverage-include"><code>--test-coverage-include</code></a></span></li>
<li><a href="#all_cli_--test-force-exit"><code>--test-force-exit</code></a></li>
<li><a href="#all_cli_--test-name-pattern"><code>--test-name-pattern</code></a></li>
<li><a href="#all_cli_--test-only"><code>--test-only</code></a></li>
<li><a href="#all_cli_--test-reporter"><code>--test-reporter</code></a></li>
<li><a href="#all_cli_--test-reporter-destination"><code>--test-reporter-destination</code></a></li>
<li><a href="#all_cli_--test-shard"><code>--test-shard</code></a></li>
<li><a href="#all_cli_--test-timeout"><code>--test-timeout</code></a></li>
<li><a href="#all_cli_--throw-deprecation"><code>--throw-deprecation</code></a></li>
<li><a href="#all_cli_--titletitle"><code>--title=title</code></a></li>
<li><a href="#all_cli_--tls-cipher-listlist"><code>--tls-cipher-list=list</code></a></li>
<li><a href="#all_cli_--tls-keylogfile"><code>--tls-keylog=file</code></a></li>
<li><a href="#all_cli_--tls-max-v12"><code>--tls-max-v1.2</code></a></li>
<li><a href="#all_cli_--tls-max-v13"><code>--tls-max-v1.3</code></a></li>
<li><a href="#all_cli_--tls-min-v10"><code>--tls-min-v1.0</code></a></li>
<li><a href="#all_cli_--tls-min-v11"><code>--tls-min-v1.1</code></a></li>
<li><a href="#all_cli_--tls-min-v12"><code>--tls-min-v1.2</code></a></li>
<li><a href="#all_cli_--tls-min-v13"><code>--tls-min-v1.3</code></a></li>
<li><span class="stability_0"><a href="#all_cli_--trace-atomics-wait"><code>--trace-atomics-wait</code></a></span></li>
<li><a href="#all_cli_--trace-deprecation"><code>--trace-deprecation</code></a></li>
<li><a href="#all_cli_--trace-event-categories"><code>--trace-event-categories</code></a></li>
<li><a href="#all_cli_--trace-event-file-pattern"><code>--trace-event-file-pattern</code></a></li>
<li><a href="#all_cli_--trace-events-enabled"><code>--trace-events-enabled</code></a></li>
<li><a href="#all_cli_--trace-exit"><code>--trace-exit</code></a></li>
<li><a href="#all_cli_--trace-require-modulemode"><code>--trace-require-module=mode</code></a></li>
<li><a href="#all_cli_--trace-sigint"><code>--trace-sigint</code></a></li>
<li><a href="#all_cli_--trace-sync-io"><code>--trace-sync-io</code></a></li>
<li><a href="#all_cli_--trace-tls"><code>--trace-tls</code></a></li>
<li><a href="#all_cli_--trace-uncaught"><code>--trace-uncaught</code></a></li>
<li><a href="#all_cli_--trace-warnings"><code>--trace-warnings</code></a></li>
<li><a href="#all_cli_--track-heap-objects"><code>--track-heap-objects</code></a></li>
<li><a href="#all_cli_--unhandled-rejectionsmode"><code>--unhandled-rejections=mode</code></a></li>
<li><a href="#all_cli_--use-bundled-ca---use-openssl-ca"><code>--use-bundled-ca</code>, <code>--use-openssl-ca</code></a></li>
<li><a href="#all_cli_--use-largepagesmode"><code>--use-largepages=mode</code></a></li>
<li><a href="#all_cli_--v8-options"><code>--v8-options</code></a></li>
<li><a href="#all_cli_--v8-pool-sizenum"><code>--v8-pool-size=num</code></a></li>
<li><a href="#all_cli_-v---version"><code>-v</code>, <code>--version</code></a></li>
<li><span class="stability_2"><a href="#all_cli_--watch"><code>--watch</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--watch-path"><code>--watch-path</code></a></span></li>
<li><a href="#all_cli_--watch-preserve-output"><code>--watch-preserve-output</code></a></li>
<li><a href="#all_cli_--zero-fill-buffers"><code>--zero-fill-buffers</code></a></li>
</ul>
</li>
<li><a href="#all_cli_environment-variables">Environment variables</a>
<ul>
<li><a href="#all_cli_force_color1-2-3"><code>FORCE_COLOR=[1, 2, 3]</code></a></li>
<li><a href="#all_cli_no_colorany"><code>NO_COLOR=<any></code></a></li>
<li><a href="#all_cli_node_debugmodule"><code>NODE_DEBUG=module[,…]</code></a></li>
<li><a href="#all_cli_node_debug_nativemodule"><code>NODE_DEBUG_NATIVE=module[,…]</code></a></li>
<li><a href="#all_cli_node_disable_colors1"><code>NODE_DISABLE_COLORS=1</code></a></li>
<li><a href="#all_cli_node_extra_ca_certsfile"><code>NODE_EXTRA_CA_CERTS=file</code></a></li>
<li><a href="#all_cli_node_icu_datafile"><code>NODE_ICU_DATA=file</code></a></li>
<li><a href="#all_cli_node_no_warnings1"><code>NODE_NO_WARNINGS=1</code></a></li>
<li><a href="#all_cli_node_optionsoptions"><code>NODE_OPTIONS=options...</code></a></li>
<li><a href="#all_cli_node_pathpath"><code>NODE_PATH=path[:…]</code></a></li>
<li><a href="#all_cli_node_pending_deprecation1"><code>NODE_PENDING_DEPRECATION=1</code></a></li>
<li><a href="#all_cli_node_pending_pipe_instancesinstances"><code>NODE_PENDING_PIPE_INSTANCES=instances</code></a></li>
<li><a href="#all_cli_node_preserve_symlinks1"><code>NODE_PRESERVE_SYMLINKS=1</code></a></li>
<li><a href="#all_cli_node_redirect_warningsfile"><code>NODE_REDIRECT_WARNINGS=file</code></a></li>
<li><a href="#all_cli_node_repl_external_modulefile"><code>NODE_REPL_EXTERNAL_MODULE=file</code></a></li>
<li><a href="#all_cli_node_repl_historyfile"><code>NODE_REPL_HISTORY=file</code></a></li>
<li><a href="#all_cli_node_skip_platform_checkvalue"><code>NODE_SKIP_PLATFORM_CHECK=value</code></a></li>
<li><a href="#all_cli_node_test_contextvalue"><code>NODE_TEST_CONTEXT=value</code></a></li>
<li><a href="#all_cli_node_tls_reject_unauthorizedvalue"><code>NODE_TLS_REJECT_UNAUTHORIZED=value</code></a></li>
<li><a href="#all_cli_node_v8_coveragedir"><code>NODE_V8_COVERAGE=dir</code></a>
<ul>
<li><a href="#all_cli_coverage-output">Coverage output</a></li>
<li><span class="stability_1"><a href="#all_cli_source-map-cache">Source map cache</a></span></li>
</ul>
</li>
<li><a href="#all_cli_openssl_conffile"><code>OPENSSL_CONF=file</code></a></li>
<li><a href="#all_cli_ssl_cert_dirdir"><code>SSL_CERT_DIR=dir</code></a></li>
<li><a href="#all_cli_ssl_cert_filefile"><code>SSL_CERT_FILE=file</code></a></li>
<li><a href="#all_cli_tz"><code>TZ</code></a></li>
<li><a href="#all_cli_uv_threadpool_sizesize"><code>UV_THREADPOOL_SIZE=size</code></a></li>
<li><a href="#all_cli_uv_use_io_uringvalue"><code>UV_USE_IO_URING=value</code></a></li>
</ul>
</li>
<li><a href="#all_cli_useful-v8-options">Useful V8 options</a>
<ul>
<li><a href="#all_cli_--abort-on-uncaught-exception_1"><code>--abort-on-uncaught-exception</code></a></li>
<li><a href="#all_cli_--disallow-code-generation-from-strings_1"><code>--disallow-code-generation-from-strings</code></a></li>
<li><a href="#all_cli_--enable-etw-stack-walking"><code>--enable-etw-stack-walking</code></a></li>
<li><a href="#all_cli_--expose-gc_1"><code>--expose-gc</code></a></li>
<li><a href="#all_cli_--harmony-shadow-realm"><code>--harmony-shadow-realm</code></a></li>
<li><a href="#all_cli_--huge-max-old-generation-size"><code>--huge-max-old-generation-size</code></a></li>
<li><a href="#all_cli_--jitless_1"><code>--jitless</code></a></li>
<li><a href="#all_cli_--interpreted-frames-native-stack"><code>--interpreted-frames-native-stack</code></a></li>
<li><a href="#all_cli_--prof_1"><code>--prof</code></a></li>
<li><a href="#all_cli_--perf-basic-prof"><code>--perf-basic-prof</code></a></li>
<li><a href="#all_cli_--perf-basic-prof-only-functions"><code>--perf-basic-prof-only-functions</code></a></li>
<li><a href="#all_cli_--perf-prof"><code>--perf-prof</code></a></li>
<li><a href="#all_cli_--perf-prof-unwinding-info"><code>--perf-prof-unwinding-info</code></a></li>
<li><a href="#all_cli_--max-old-space-sizesize-in-mib"><code>--max-old-space-size=SIZE</code> (in MiB)</a></li>
<li><a href="#all_cli_--max-semi-space-sizesize-in-mib"><code>--max-semi-space-size=SIZE</code> (in MiB)</a></li>
<li><a href="#all_cli_--security-revert"><code>--security-revert</code></a></li>
<li><a href="#all_cli_--stack-trace-limitlimit"><code>--stack-trace-limit=limit</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_console_console">Console</a></span>
<ul>
<li><a href="#all_console_class-console">Class: <code>Console</code></a>
<ul>
<li><a href="#all_console_new-consolestdout-stderr-ignoreerrors"><code>new Console(stdout[, stderr][, ignoreErrors])</code></a></li>
<li><a href="#all_console_new-consoleoptions"><code>new Console(options)</code></a></li>
<li><a href="#all_console_consoleassertvalue-message"><code>console.assert(value[, ...message])</code></a></li>
<li><a href="#all_console_consoleclear"><code>console.clear()</code></a></li>
<li><a href="#all_console_consolecountlabel"><code>console.count([label])</code></a></li>
<li><a href="#all_console_consolecountresetlabel"><code>console.countReset([label])</code></a></li>
<li><a href="#all_console_consoledebugdata-args"><code>console.debug(data[, ...args])</code></a></li>
<li><a href="#all_console_consoledirobj-options"><code>console.dir(obj[, options])</code></a></li>
<li><a href="#all_console_consoledirxmldata"><code>console.dirxml(...data)</code></a></li>
<li><a href="#all_console_consoleerrordata-args"><code>console.error([data][, ...args])</code></a></li>
<li><a href="#all_console_consolegrouplabel"><code>console.group([...label])</code></a></li>
<li><a href="#all_console_consolegroupcollapsed"><code>console.groupCollapsed()</code></a></li>
<li><a href="#all_console_consolegroupend"><code>console.groupEnd()</code></a></li>
<li><a href="#all_console_consoleinfodata-args"><code>console.info([data][, ...args])</code></a></li>
<li><a href="#all_console_consolelogdata-args"><code>console.log([data][, ...args])</code></a></li>
<li><a href="#all_console_consoletabletabulardata-properties"><code>console.table(tabularData[, properties])</code></a></li>
<li><a href="#all_console_consoletimelabel"><code>console.time([label])</code></a></li>
<li><a href="#all_console_consoletimeendlabel"><code>console.timeEnd([label])</code></a></li>
<li><a href="#all_console_consoletimeloglabel-data"><code>console.timeLog([label][, ...data])</code></a></li>
<li><a href="#all_console_consoletracemessage-args"><code>console.trace([message][, ...args])</code></a></li>
<li><a href="#all_console_consolewarndata-args"><code>console.warn([data][, ...args])</code></a></li>
</ul>
</li>
<li><a href="#all_console_inspector-only-methods">Inspector only methods</a>
<ul>
<li><a href="#all_console_consoleprofilelabel"><code>console.profile([label])</code></a></li>
<li><a href="#all_console_consoleprofileendlabel"><code>console.profileEnd([label])</code></a></li>
<li><a href="#all_console_consoletimestamplabel"><code>console.timeStamp([label])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_corepack_corepack">Corepack</a>
<ul>
<li><a href="#all_corepack_workflows">Workflows</a>
<ul>
<li><a href="#all_corepack_enabling-the-feature">Enabling the feature</a></li>
<li><a href="#all_corepack_configuring-a-package">Configuring a package</a></li>
<li><a href="#all_corepack_upgrading-the-global-versions">Upgrading the global versions</a></li>
<li><a href="#all_corepack_offline-workflow">Offline workflow</a></li>
</ul>
</li>
<li><a href="#all_corepack_supported-package-managers">Supported package managers</a></li>
<li><a href="#all_corepack_common-questions">Common questions</a>
<ul>
<li><a href="#all_corepack_how-does-corepack-interact-with-npm">How does Corepack interact with npm?</a></li>
<li><a href="#all_corepack_running-npm-install--g-yarn-doesnt-work">Running <code>npm install -g yarn</code> doesn't work</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_crypto_crypto">Crypto</a></span>
<ul>
<li><a href="#all_crypto_determining-if-crypto-support-is-unavailable">Determining if crypto support is unavailable</a></li>
<li><a href="#all_crypto_class-certificate">Class: <code>Certificate</code></a>
<ul>
<li><a href="#all_crypto_static-method-certificateexportchallengespkac-encoding">Static method: <code>Certificate.exportChallenge(spkac[, encoding])</code></a></li>
<li><a href="#all_crypto_static-method-certificateexportpublickeyspkac-encoding">Static method: <code>Certificate.exportPublicKey(spkac[, encoding])</code></a></li>
<li><a href="#all_crypto_static-method-certificateverifyspkacspkac-encoding">Static method: <code>Certificate.verifySpkac(spkac[, encoding])</code></a></li>
<li><span class="stability_0"><a href="#all_crypto_legacy-api">Legacy API</a></span>
<ul>
<li><a href="#all_crypto_new-cryptocertificate"><code>new crypto.Certificate()</code></a></li>
<li><a href="#all_crypto_certificateexportchallengespkac-encoding"><code>certificate.exportChallenge(spkac[, encoding])</code></a></li>
<li><a href="#all_crypto_certificateexportpublickeyspkac-encoding"><code>certificate.exportPublicKey(spkac[, encoding])</code></a></li>
<li><a href="#all_crypto_certificateverifyspkacspkac-encoding"><code>certificate.verifySpkac(spkac[, encoding])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_crypto_class-cipher">Class: <code>Cipher</code></a>
<ul>
<li><a href="#all_crypto_cipherfinaloutputencoding"><code>cipher.final([outputEncoding])</code></a></li>
<li><a href="#all_crypto_ciphergetauthtag"><code>cipher.getAuthTag()</code></a></li>
<li><a href="#all_crypto_ciphersetaadbuffer-options"><code>cipher.setAAD(buffer[, options])</code></a></li>
<li><a href="#all_crypto_ciphersetautopaddingautopadding"><code>cipher.setAutoPadding([autoPadding])</code></a></li>
<li><a href="#all_crypto_cipherupdatedata-inputencoding-outputencoding"><code>cipher.update(data[, inputEncoding][, outputEncoding])</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-decipher">Class: <code>Decipher</code></a>
<ul>
<li><a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final([outputEncoding])</code></a></li>
<li><a href="#all_crypto_deciphersetaadbuffer-options"><code>decipher.setAAD(buffer[, options])</code></a></li>
<li><a href="#all_crypto_deciphersetauthtagbuffer-encoding"><code>decipher.setAuthTag(buffer[, encoding])</code></a></li>
<li><a href="#all_crypto_deciphersetautopaddingautopadding"><code>decipher.setAutoPadding([autoPadding])</code></a></li>
<li><a href="#all_crypto_decipherupdatedata-inputencoding-outputencoding"><code>decipher.update(data[, inputEncoding][, outputEncoding])</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-diffiehellman">Class: <code>DiffieHellman</code></a>
<ul>
<li><a href="#all_crypto_diffiehellmancomputesecretotherpublickey-inputencoding-outputencoding"><code>diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmangeneratekeysencoding"><code>diffieHellman.generateKeys([encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmangetgeneratorencoding"><code>diffieHellman.getGenerator([encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmangetprimeencoding"><code>diffieHellman.getPrime([encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmangetprivatekeyencoding"><code>diffieHellman.getPrivateKey([encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmangetpublickeyencoding"><code>diffieHellman.getPublicKey([encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmansetprivatekeyprivatekey-encoding"><code>diffieHellman.setPrivateKey(privateKey[, encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmansetpublickeypublickey-encoding"><code>diffieHellman.setPublicKey(publicKey[, encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmanverifyerror"><code>diffieHellman.verifyError</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-diffiehellmangroup">Class: <code>DiffieHellmanGroup</code></a></li>
<li><a href="#all_crypto_class-ecdh">Class: <code>ECDH</code></a>
<ul>
<li><a href="#all_crypto_static-method-ecdhconvertkeykey-curve-inputencoding-outputencoding-format">Static method: <code>ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])</code></a></li>
<li><a href="#all_crypto_ecdhcomputesecretotherpublickey-inputencoding-outputencoding"><code>ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</code></a></li>
<li><a href="#all_crypto_ecdhgeneratekeysencoding-format"><code>ecdh.generateKeys([encoding[, format]])</code></a></li>
<li><a href="#all_crypto_ecdhgetprivatekeyencoding"><code>ecdh.getPrivateKey([encoding])</code></a></li>
<li><a href="#all_crypto_ecdhgetpublickeyencoding-format"><code>ecdh.getPublicKey([encoding][, format])</code></a></li>
<li><a href="#all_crypto_ecdhsetprivatekeyprivatekey-encoding"><code>ecdh.setPrivateKey(privateKey[, encoding])</code></a></li>
<li><span class="stability_0"><a href="#all_crypto_ecdhsetpublickeypublickey-encoding"><code>ecdh.setPublicKey(publicKey[, encoding])</code></a></span></li>
</ul>
</li>
<li><a href="#all_crypto_class-hash">Class: <code>Hash</code></a>
<ul>
<li><a href="#all_crypto_hashcopyoptions"><code>hash.copy([options])</code></a></li>
<li><a href="#all_crypto_hashdigestencoding"><code>hash.digest([encoding])</code></a></li>
<li><a href="#all_crypto_hashupdatedata-inputencoding"><code>hash.update(data[, inputEncoding])</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-hmac">Class: <code>Hmac</code></a>
<ul>
<li><a href="#all_crypto_hmacdigestencoding"><code>hmac.digest([encoding])</code></a></li>
<li><a href="#all_crypto_hmacupdatedata-inputencoding"><code>hmac.update(data[, inputEncoding])</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-keyobject">Class: <code>KeyObject</code></a>
<ul>
<li><a href="#all_crypto_static-method-keyobjectfromkey">Static method: <code>KeyObject.from(key)</code></a></li>
<li><a href="#all_crypto_keyobjectasymmetrickeydetails"><code>keyObject.asymmetricKeyDetails</code></a></li>
<li><a href="#all_crypto_keyobjectasymmetrickeytype"><code>keyObject.asymmetricKeyType</code></a></li>
<li><a href="#all_crypto_keyobjectexportoptions"><code>keyObject.export([options])</code></a></li>
<li><a href="#all_crypto_keyobjectequalsotherkeyobject"><code>keyObject.equals(otherKeyObject)</code></a></li>
<li><a href="#all_crypto_keyobjectsymmetrickeysize"><code>keyObject.symmetricKeySize</code></a></li>
<li><a href="#all_crypto_keyobjecttype"><code>keyObject.type</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-sign">Class: <code>Sign</code></a>
<ul>
<li><a href="#all_crypto_signsignprivatekey-outputencoding"><code>sign.sign(privateKey[, outputEncoding])</code></a></li>
<li><a href="#all_crypto_signupdatedata-inputencoding"><code>sign.update(data[, inputEncoding])</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-verify">Class: <code>Verify</code></a>
<ul>
<li><a href="#all_crypto_verifyupdatedata-inputencoding"><code>verify.update(data[, inputEncoding])</code></a></li>
<li><a href="#all_crypto_verifyverifyobject-signature-signatureencoding"><code>verify.verify(object, signature[, signatureEncoding])</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-x509certificate">Class: <code>X509Certificate</code></a>
<ul>
<li><a href="#all_crypto_new-x509certificatebuffer"><code>new X509Certificate(buffer)</code></a></li>
<li><a href="#all_crypto_x509ca"><code>x509.ca</code></a></li>
<li><a href="#all_crypto_x509checkemailemail-options"><code>x509.checkEmail(email[, options])</code></a></li>
<li><a href="#all_crypto_x509checkhostname-options"><code>x509.checkHost(name[, options])</code></a></li>
<li><a href="#all_crypto_x509checkipip"><code>x509.checkIP(ip)</code></a></li>
<li><a href="#all_crypto_x509checkissuedothercert"><code>x509.checkIssued(otherCert)</code></a></li>
<li><a href="#all_crypto_x509checkprivatekeyprivatekey"><code>x509.checkPrivateKey(privateKey)</code></a></li>
<li><a href="#all_crypto_x509fingerprint"><code>x509.fingerprint</code></a></li>
<li><a href="#all_crypto_x509fingerprint256"><code>x509.fingerprint256</code></a></li>
<li><a href="#all_crypto_x509fingerprint512"><code>x509.fingerprint512</code></a></li>
<li><a href="#all_crypto_x509infoaccess"><code>x509.infoAccess</code></a></li>
<li><a href="#all_crypto_x509issuer"><code>x509.issuer</code></a></li>
<li><a href="#all_crypto_x509issuercertificate"><code>x509.issuerCertificate</code></a></li>
<li><a href="#all_crypto_x509extkeyusage"><code>x509.extKeyUsage</code></a></li>
<li><a href="#all_crypto_x509publickey"><code>x509.publicKey</code></a></li>
<li><a href="#all_crypto_x509raw"><code>x509.raw</code></a></li>
<li><a href="#all_crypto_x509serialnumber"><code>x509.serialNumber</code></a></li>
<li><a href="#all_crypto_x509subject"><code>x509.subject</code></a></li>
<li><a href="#all_crypto_x509subjectaltname"><code>x509.subjectAltName</code></a></li>
<li><a href="#all_crypto_x509tojson"><code>x509.toJSON()</code></a></li>
<li><a href="#all_crypto_x509tolegacyobject"><code>x509.toLegacyObject()</code></a></li>
<li><a href="#all_crypto_x509tostring"><code>x509.toString()</code></a></li>
<li><a href="#all_crypto_x509validfrom"><code>x509.validFrom</code></a></li>
<li><a href="#all_crypto_x509validto"><code>x509.validTo</code></a></li>
<li><a href="#all_crypto_x509verifypublickey"><code>x509.verify(publicKey)</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_nodecrypto-module-methods-and-properties"><code>node:crypto</code> module methods and properties</a>
<ul>
<li><a href="#all_crypto_cryptoconstants"><code>crypto.constants</code></a></li>
<li><span class="stability_0"><a href="#all_crypto_cryptofips"><code>crypto.fips</code></a></span></li>
<li><a href="#all_crypto_cryptocheckprimecandidate-options-callback"><code>crypto.checkPrime(candidate[, options], callback)</code></a></li>
<li><a href="#all_crypto_cryptocheckprimesynccandidate-options"><code>crypto.checkPrimeSync(candidate[, options])</code></a></li>
<li><span class="stability_0"><a href="#all_crypto_cryptocreatecipheralgorithm-password-options"><code>crypto.createCipher(algorithm, password[, options])</code></a></span></li>
<li><a href="#all_crypto_cryptocreatecipherivalgorithm-key-iv-options"><code>crypto.createCipheriv(algorithm, key, iv[, options])</code></a></li>
<li><span class="stability_0"><a href="#all_crypto_cryptocreatedecipheralgorithm-password-options"><code>crypto.createDecipher(algorithm, password[, options])</code></a></span></li>
<li><a href="#all_crypto_cryptocreatedecipherivalgorithm-key-iv-options"><code>crypto.createDecipheriv(algorithm, key, iv[, options])</code></a></li>
<li><a href="#all_crypto_cryptocreatediffiehellmanprime-primeencoding-generator-generatorencoding"><code>crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])</code></a></li>
<li><a href="#all_crypto_cryptocreatediffiehellmanprimelength-generator"><code>crypto.createDiffieHellman(primeLength[, generator])</code></a></li>
<li><a href="#all_crypto_cryptocreatediffiehellmangroupname"><code>crypto.createDiffieHellmanGroup(name)</code></a></li>
<li><a href="#all_crypto_cryptocreateecdhcurvename"><code>crypto.createECDH(curveName)</code></a></li>
<li><a href="#all_crypto_cryptocreatehashalgorithm-options"><code>crypto.createHash(algorithm[, options])</code></a></li>
<li><a href="#all_crypto_cryptocreatehmacalgorithm-key-options"><code>crypto.createHmac(algorithm, key[, options])</code></a></li>
<li><a href="#all_crypto_cryptocreateprivatekeykey"><code>crypto.createPrivateKey(key)</code></a></li>
<li><a href="#all_crypto_cryptocreatepublickeykey"><code>crypto.createPublicKey(key)</code></a></li>
<li><a href="#all_crypto_cryptocreatesecretkeykey-encoding"><code>crypto.createSecretKey(key[, encoding])</code></a></li>
<li><a href="#all_crypto_cryptocreatesignalgorithm-options"><code>crypto.createSign(algorithm[, options])</code></a></li>
<li><a href="#all_crypto_cryptocreateverifyalgorithm-options"><code>crypto.createVerify(algorithm[, options])</code></a></li>
<li><a href="#all_crypto_cryptodiffiehellmanoptions"><code>crypto.diffieHellman(options)</code></a></li>
<li><span class="stability_1"><a href="#all_crypto_cryptohashalgorithm-data-outputencoding"><code>crypto.hash(algorithm, data[, outputEncoding])</code></a></span></li>
<li><a href="#all_crypto_cryptogeneratekeytype-options-callback"><code>crypto.generateKey(type, options, callback)</code></a></li>
<li><a href="#all_crypto_cryptogeneratekeypairtype-options-callback"><code>crypto.generateKeyPair(type, options, callback)</code></a></li>
<li><a href="#all_crypto_cryptogeneratekeypairsynctype-options"><code>crypto.generateKeyPairSync(type, options)</code></a></li>
<li><a href="#all_crypto_cryptogeneratekeysynctype-options"><code>crypto.generateKeySync(type, options)</code></a></li>
<li><a href="#all_crypto_cryptogenerateprimesize-options-callback"><code>crypto.generatePrime(size[, options[, callback]])</code></a></li>
<li><a href="#all_crypto_cryptogenerateprimesyncsize-options"><code>crypto.generatePrimeSync(size[, options])</code></a></li>
<li><a href="#all_crypto_cryptogetcipherinfonameornid-options"><code>crypto.getCipherInfo(nameOrNid[, options])</code></a></li>
<li><a href="#all_crypto_cryptogetciphers"><code>crypto.getCiphers()</code></a></li>
<li><a href="#all_crypto_cryptogetcurves"><code>crypto.getCurves()</code></a></li>
<li><a href="#all_crypto_cryptogetdiffiehellmangroupname"><code>crypto.getDiffieHellman(groupName)</code></a></li>
<li><a href="#all_crypto_cryptogetfips"><code>crypto.getFips()</code></a></li>
<li><a href="#all_crypto_cryptogethashes"><code>crypto.getHashes()</code></a></li>
<li><a href="#all_crypto_cryptogetrandomvaluestypedarray"><code>crypto.getRandomValues(typedArray)</code></a></li>
<li><a href="#all_crypto_cryptohkdfdigest-ikm-salt-info-keylen-callback"><code>crypto.hkdf(digest, ikm, salt, info, keylen, callback)</code></a></li>
<li><a href="#all_crypto_cryptohkdfsyncdigest-ikm-salt-info-keylen"><code>crypto.hkdfSync(digest, ikm, salt, info, keylen)</code></a></li>
<li><a href="#all_crypto_cryptopbkdf2password-salt-iterations-keylen-digest-callback"><code>crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)</code></a></li>
<li><a href="#all_crypto_cryptopbkdf2syncpassword-salt-iterations-keylen-digest"><code>crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)</code></a></li>
<li><a href="#all_crypto_cryptoprivatedecryptprivatekey-buffer"><code>crypto.privateDecrypt(privateKey, buffer)</code></a></li>
<li><a href="#all_crypto_cryptoprivateencryptprivatekey-buffer"><code>crypto.privateEncrypt(privateKey, buffer)</code></a></li>
<li><a href="#all_crypto_cryptopublicdecryptkey-buffer"><code>crypto.publicDecrypt(key, buffer)</code></a></li>
<li><a href="#all_crypto_cryptopublicencryptkey-buffer"><code>crypto.publicEncrypt(key, buffer)</code></a></li>
<li><a href="#all_crypto_cryptorandombytessize-callback"><code>crypto.randomBytes(size[, callback])</code></a></li>
<li><a href="#all_crypto_cryptorandomfillsyncbuffer-offset-size"><code>crypto.randomFillSync(buffer[, offset][, size])</code></a></li>
<li><a href="#all_crypto_cryptorandomfillbuffer-offset-size-callback"><code>crypto.randomFill(buffer[, offset][, size], callback)</code></a></li>
<li><a href="#all_crypto_cryptorandomintmin-max-callback"><code>crypto.randomInt([min, ]max[, callback])</code></a></li>
<li><a href="#all_crypto_cryptorandomuuidoptions"><code>crypto.randomUUID([options])</code></a></li>
<li><a href="#all_crypto_cryptoscryptpassword-salt-keylen-options-callback"><code>crypto.scrypt(password, salt, keylen[, options], callback)</code></a></li>
<li><a href="#all_crypto_cryptoscryptsyncpassword-salt-keylen-options"><code>crypto.scryptSync(password, salt, keylen[, options])</code></a></li>
<li><a href="#all_crypto_cryptosecureheapused"><code>crypto.secureHeapUsed()</code></a></li>
<li><a href="#all_crypto_cryptosetengineengine-flags"><code>crypto.setEngine(engine[, flags])</code></a></li>
<li><a href="#all_crypto_cryptosetfipsbool"><code>crypto.setFips(bool)</code></a></li>
<li><a href="#all_crypto_cryptosignalgorithm-data-key-callback"><code>crypto.sign(algorithm, data, key[, callback])</code></a></li>
<li><a href="#all_crypto_cryptosubtle"><code>crypto.subtle</code></a></li>
<li><a href="#all_crypto_cryptotimingsafeequala-b"><code>crypto.timingSafeEqual(a, b)</code></a></li>
<li><a href="#all_crypto_cryptoverifyalgorithm-data-key-signature-callback"><code>crypto.verify(algorithm, data, key, signature[, callback])</code></a></li>
<li><a href="#all_crypto_cryptowebcrypto"><code>crypto.webcrypto</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_notes">Notes</a>
<ul>
<li><a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">Using strings as inputs to cryptographic APIs</a></li>
<li><a href="#all_crypto_legacy-streams-api-prior-to-nodejs-010">Legacy streams API (prior to Node.js 0.10)</a></li>
<li><a href="#all_crypto_support-for-weak-or-compromised-algorithms">Support for weak or compromised algorithms</a></li>
<li><a href="#all_crypto_ccm-mode">CCM mode</a></li>
<li><a href="#all_crypto_fips-mode">FIPS mode</a></li>
</ul>
</li>
<li><a href="#all_crypto_crypto-constants">Crypto constants</a>
<ul>
<li><a href="#all_crypto_openssl-options">OpenSSL options</a></li>
<li><a href="#all_crypto_openssl-engine-constants">OpenSSL engine constants</a></li>
<li><a href="#all_crypto_other-openssl-constants">Other OpenSSL constants</a></li>
<li><a href="#all_crypto_nodejs-crypto-constants">Node.js crypto constants</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_debugger_debugger">Debugger</a></span>
<ul>
<li><a href="#all_debugger_watchers">Watchers</a></li>
<li><a href="#all_debugger_command-reference">Command reference</a>
<ul>
<li><a href="#all_debugger_stepping">Stepping</a></li>
<li><a href="#all_debugger_breakpoints">Breakpoints</a></li>
<li><a href="#all_debugger_information">Information</a></li>
<li><a href="#all_debugger_execution-control">Execution control</a></li>
<li><a href="#all_debugger_various">Various</a></li>
</ul>
</li>
<li><a href="#all_debugger_advanced-usage">Advanced usage</a>
<ul>
<li><a href="#all_debugger_v8-inspector-integration-for-nodejs">V8 inspector integration for Node.js</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_deprecations_deprecated-apis">Deprecated APIs</a>
<ul>
<li><a href="#all_deprecations_revoking-deprecations">Revoking deprecations</a></li>
<li><a href="#all_deprecations_list-of-deprecated-apis">List of deprecated APIs</a>
<ul>
<li><a href="#DEP0001">DEP0001: <code>http.OutgoingMessage.prototype.flush</code></a></li>
<li><a href="#DEP0002">DEP0002: <code>require('_linklist')</code></a></li>
<li><a href="#DEP0003">DEP0003: <code>_writableState.buffer</code></a></li>
<li><a href="#DEP0004">DEP0004: <code>CryptoStream.prototype.readyState</code></a></li>
<li><a href="#DEP0005">DEP0005: <code>Buffer()</code> constructor</a></li>
<li><a href="#DEP0006">DEP0006: <code>child_process</code> <code>options.customFds</code></a></li>
<li><a href="#DEP0007">DEP0007: Replace <code>cluster</code> <code>worker.suicide</code> with <code>worker.exitedAfterDisconnect</code></a></li>
<li><a href="#DEP0008">DEP0008: <code>require('node:constants')</code></a></li>
<li><a href="#DEP0009">DEP0009: <code>crypto.pbkdf2</code> without digest</a></li>
<li><a href="#DEP0010">DEP0010: <code>crypto.createCredentials</code></a></li>
<li><a href="#DEP0011">DEP0011: <code>crypto.Credentials</code></a></li>
<li><a href="#DEP0012">DEP0012: <code>Domain.dispose</code></a></li>
<li><a href="#DEP0013">DEP0013: <code>fs</code> asynchronous function without callback</a></li>
<li><a href="#DEP0014">DEP0014: <code>fs.read</code> legacy String interface</a></li>
<li><a href="#DEP0015">DEP0015: <code>fs.readSync</code> legacy String interface</a></li>
<li><a href="#DEP0016">DEP0016: <code>GLOBAL</code>/<code>root</code></a></li>
<li><a href="#DEP0017">DEP0017: <code>Intl.v8BreakIterator</code></a></li>
<li><a href="#DEP0018">DEP0018: Unhandled promise rejections</a></li>
<li><a href="#DEP0019">DEP0019: <code>require('.')</code> resolved outside directory</a></li>
<li><a href="#DEP0020">DEP0020: <code>Server.connections</code></a></li>
<li><a href="#DEP0021">DEP0021: <code>Server.listenFD</code></a></li>
<li><a href="#DEP0022">DEP0022: <code>os.tmpDir()</code></a></li>
<li><a href="#DEP0023">DEP0023: <code>os.getNetworkInterfaces()</code></a></li>
<li><a href="#DEP0024">DEP0024: <code>REPLServer.prototype.convertToContext()</code></a></li>
<li><a href="#DEP0025">DEP0025: <code>require('node:sys')</code></a></li>
<li><a href="#DEP0026">DEP0026: <code>util.print()</code></a></li>
<li><a href="#DEP0027">DEP0027: <code>util.puts()</code></a></li>
<li><a href="#DEP0028">DEP0028: <code>util.debug()</code></a></li>
<li><a href="#DEP0029">DEP0029: <code>util.error()</code></a></li>
<li><a href="#DEP0030">DEP0030: <code>SlowBuffer</code></a></li>
<li><a href="#DEP0031">DEP0031: <code>ecdh.setPublicKey()</code></a></li>
<li><a href="#DEP0032">DEP0032: <code>node:domain</code> module</a></li>
<li><a href="#DEP0033">DEP0033: <code>EventEmitter.listenerCount()</code></a></li>
<li><a href="#DEP0034">DEP0034: <code>fs.exists(path, callback)</code></a></li>
<li><a href="#DEP0035">DEP0035: <code>fs.lchmod(path, mode, callback)</code></a></li>
<li><a href="#DEP0036">DEP0036: <code>fs.lchmodSync(path, mode)</code></a></li>
<li><a href="#DEP0037">DEP0037: <code>fs.lchown(path, uid, gid, callback)</code></a></li>
<li><a href="#DEP0038">DEP0038: <code>fs.lchownSync(path, uid, gid)</code></a></li>
<li><a href="#DEP0039">DEP0039: <code>require.extensions</code></a></li>
<li><a href="#DEP0040">DEP0040: <code>node:punycode</code> module</a></li>
<li><a href="#DEP0041">DEP0041: <code>NODE_REPL_HISTORY_FILE</code> environment variable</a></li>
<li><a href="#DEP0042">DEP0042: <code>tls.CryptoStream</code></a></li>
<li><a href="#DEP0043">DEP0043: <code>tls.SecurePair</code></a></li>
<li><a href="#DEP0044">DEP0044: <code>util.isArray()</code></a></li>
<li><a href="#DEP0045">DEP0045: <code>util.isBoolean()</code></a></li>
<li><a href="#DEP0046">DEP0046: <code>util.isBuffer()</code></a></li>
<li><a href="#DEP0047">DEP0047: <code>util.isDate()</code></a></li>
<li><a href="#DEP0048">DEP0048: <code>util.isError()</code></a></li>
<li><a href="#DEP0049">DEP0049: <code>util.isFunction()</code></a></li>
<li><a href="#DEP0050">DEP0050: <code>util.isNull()</code></a></li>
<li><a href="#DEP0051">DEP0051: <code>util.isNullOrUndefined()</code></a></li>
<li><a href="#DEP0052">DEP0052: <code>util.isNumber()</code></a></li>
<li><a href="#DEP0053">DEP0053: <code>util.isObject()</code></a></li>
<li><a href="#DEP0054">DEP0054: <code>util.isPrimitive()</code></a></li>
<li><a href="#DEP0055">DEP0055: <code>util.isRegExp()</code></a></li>
<li><a href="#DEP0056">DEP0056: <code>util.isString()</code></a></li>
<li><a href="#DEP0057">DEP0057: <code>util.isSymbol()</code></a></li>
<li><a href="#DEP0058">DEP0058: <code>util.isUndefined()</code></a></li>
<li><a href="#DEP0059">DEP0059: <code>util.log()</code></a></li>
<li><a href="#DEP0060">DEP0060: <code>util._extend()</code></a></li>
<li><a href="#DEP0061">DEP0061: <code>fs.SyncWriteStream</code></a></li>
<li><a href="#DEP0062">DEP0062: <code>node --debug</code></a></li>
<li><a href="#DEP0063">DEP0063: <code>ServerResponse.prototype.writeHeader()</code></a></li>
<li><a href="#DEP0064">DEP0064: <code>tls.createSecurePair()</code></a></li>
<li><a href="#DEP0065">DEP0065: <code>repl.REPL_MODE_MAGIC</code> and <code>NODE_REPL_MODE=magic</code></a></li>
<li><a href="#DEP0066">DEP0066: <code>OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames</code></a></li>
<li><a href="#DEP0067">DEP0067: <code>OutgoingMessage.prototype._renderHeaders</code></a></li>
<li><a href="#DEP0068">DEP0068: <code>node debug</code></a></li>
<li><a href="#DEP0069">DEP0069: <code>vm.runInDebugContext(string)</code></a></li>
<li><a href="#DEP0070">DEP0070: <code>async_hooks.currentId()</code></a></li>
<li><a href="#DEP0071">DEP0071: <code>async_hooks.triggerId()</code></a></li>
<li><a href="#DEP0072">DEP0072: <code>async_hooks.AsyncResource.triggerId()</code></a></li>
<li><a href="#DEP0073">DEP0073: Several internal properties of <code>net.Server</code></a></li>
<li><a href="#DEP0074">DEP0074: <code>REPLServer.bufferedCommand</code></a></li>
<li><a href="#DEP0075">DEP0075: <code>REPLServer.parseREPLKeyword()</code></a></li>
<li><a href="#DEP0076">DEP0076: <code>tls.parseCertString()</code></a></li>
<li><a href="#DEP0077">DEP0077: <code>Module._debug()</code></a></li>
<li><a href="#DEP0078">DEP0078: <code>REPLServer.turnOffEditorMode()</code></a></li>
<li><a href="#DEP0079">DEP0079: Custom inspection function on objects via <code>.inspect()</code></a></li>
<li><a href="#DEP0080">DEP0080: <code>path._makeLong()</code></a></li>
<li><a href="#DEP0081">DEP0081: <code>fs.truncate()</code> using a file descriptor</a></li>
<li><a href="#DEP0082">DEP0082: <code>REPLServer.prototype.memory()</code></a></li>
<li><a href="#DEP0083">DEP0083: Disabling ECDH by setting <code>ecdhCurve</code> to <code>false</code></a></li>
<li><a href="#DEP0084">DEP0084: requiring bundled internal dependencies</a></li>
<li><a href="#DEP0085">DEP0085: AsyncHooks sensitive API</a></li>
<li><a href="#DEP0086">DEP0086: Remove <code>runInAsyncIdScope</code></a></li>
<li><a href="#DEP0089">DEP0089: <code>require('node:assert')</code></a></li>
<li><a href="#DEP0090">DEP0090: Invalid GCM authentication tag lengths</a></li>
<li><a href="#DEP0091">DEP0091: <code>crypto.DEFAULT_ENCODING</code></a></li>
<li><a href="#DEP0092">DEP0092: Top-level <code>this</code> bound to <code>module.exports</code></a></li>
<li><a href="#DEP0093">DEP0093: <code>crypto.fips</code> is deprecated and replaced</a></li>
<li><a href="#DEP0094">DEP0094: Using <code>assert.fail()</code> with more than one argument</a></li>
<li><a href="#DEP0095">DEP0095: <code>timers.enroll()</code></a></li>
<li><a href="#DEP0096">DEP0096: <code>timers.unenroll()</code></a></li>
<li><a href="#DEP0097">DEP0097: <code>MakeCallback</code> with <code>domain</code> property</a></li>
<li><a href="#DEP0098">DEP0098: AsyncHooks embedder <code>AsyncResource.emitBefore</code> and <code>AsyncResource.emitAfter</code> APIs</a></li>
<li><a href="#DEP0099">DEP0099: Async context-unaware <code>node::MakeCallback</code> C++ APIs</a></li>
<li><a href="#DEP0100">DEP0100: <code>process.assert()</code></a></li>
<li><a href="#DEP0101">DEP0101: <code>--with-lttng</code></a></li>
<li><a href="#DEP0102">DEP0102: Using <code>noAssert</code> in <code>Buffer#(read|write)</code> operations</a></li>
<li><a href="#DEP0103">DEP0103: <code>process.binding('util').is[...]</code> typechecks</a></li>
<li><a href="#DEP0104">DEP0104: <code>process.env</code> string coercion</a></li>
<li><a href="#DEP0105">DEP0105: <code>decipher.finaltol</code></a></li>
<li><a href="#DEP0106">DEP0106: <code>crypto.createCipher</code> and <code>crypto.createDecipher</code></a></li>
<li><a href="#DEP0107">DEP0107: <code>tls.convertNPNProtocols()</code></a></li>
<li><a href="#DEP0108">DEP0108: <code>zlib.bytesRead</code></a></li>
<li><a href="#DEP0109">DEP0109: <code>http</code>, <code>https</code>, and <code>tls</code> support for invalid URLs</a></li>
<li><a href="#DEP0110">DEP0110: <code>vm.Script</code> cached data</a></li>
<li><a href="#DEP0111">DEP0111: <code>process.binding()</code></a></li>
<li><a href="#DEP0112">DEP0112: <code>dgram</code> private APIs</a></li>
<li><a href="#DEP0113">DEP0113: <code>Cipher.setAuthTag()</code>, <code>Decipher.getAuthTag()</code></a></li>
<li><a href="#DEP0114">DEP0114: <code>crypto._toBuf()</code></a></li>
<li><a href="#DEP0115">DEP0115: <code>crypto.prng()</code>, <code>crypto.pseudoRandomBytes()</code>, <code>crypto.rng()</code></a></li>
<li><a href="#DEP0116">DEP0116: Legacy URL API</a></li>
<li><a href="#DEP0117">DEP0117: Native crypto handles</a></li>
<li><a href="#DEP0118">DEP0118: <code>dns.lookup()</code> support for a falsy host name</a></li>
<li><a href="#DEP0119">DEP0119: <code>process.binding('uv').errname()</code> private API</a></li>
<li><a href="#DEP0120">DEP0120: Windows Performance Counter support</a></li>
<li><a href="#DEP0121">DEP0121: <code>net._setSimultaneousAccepts()</code></a></li>
<li><a href="#DEP0122">DEP0122: <code>tls</code> <code>Server.prototype.setOptions()</code></a></li>
<li><a href="#DEP0123">DEP0123: setting the TLS ServerName to an IP address</a></li>
<li><a href="#DEP0124">DEP0124: using <code>REPLServer.rli</code></a></li>
<li><a href="#DEP0125">DEP0125: <code>require('node:_stream_wrap')</code></a></li>
<li><a href="#DEP0126">DEP0126: <code>timers.active()</code></a></li>
<li><a href="#DEP0127">DEP0127: <code>timers._unrefActive()</code></a></li>
<li><a href="#DEP0128">DEP0128: modules with an invalid <code>main</code> entry and an <code>index.js</code> file</a></li>
<li><a href="#DEP0129">DEP0129: <code>ChildProcess._channel</code></a></li>
<li><a href="#DEP0130">DEP0130: <code>Module.createRequireFromPath()</code></a></li>
<li><a href="#DEP0131">DEP0131: Legacy HTTP parser</a></li>
<li><a href="#DEP0132">DEP0132: <code>worker.terminate()</code> with callback</a></li>
<li><a href="#DEP0133">DEP0133: <code>http</code> <code>connection</code></a></li>
<li><a href="#DEP0134">DEP0134: <code>process._tickCallback</code></a></li>
<li><a href="#DEP0135">DEP0135: <code>WriteStream.open()</code> and <code>ReadStream.open()</code> are internal</a></li>
<li><a href="#DEP0136">DEP0136: <code>http</code> <code>finished</code></a></li>
<li><a href="#DEP0137">DEP0137: Closing fs.FileHandle on garbage collection</a></li>
<li><a href="#DEP0138">DEP0138: <code>process.mainModule</code></a></li>
<li><a href="#DEP0139">DEP0139: <code>process.umask()</code> with no arguments</a></li>
<li><a href="#DEP0140">DEP0140: Use <code>request.destroy()</code> instead of <code>request.abort()</code></a></li>
<li><a href="#DEP0141">DEP0141: <code>repl.inputStream</code> and <code>repl.outputStream</code></a></li>
<li><a href="#DEP0142">DEP0142: <code>repl._builtinLibs</code></a></li>
<li><a href="#DEP0143">DEP0143: <code>Transform._transformState</code></a></li>
<li><a href="#DEP0144">DEP0144: <code>module.parent</code></a></li>
<li><a href="#DEP0145">DEP0145: <code>socket.bufferSize</code></a></li>
<li><a href="#DEP0146">DEP0146: <code>new crypto.Certificate()</code></a></li>
<li><a href="#DEP0147">DEP0147: <code>fs.rmdir(path, { recursive: true })</code></a></li>
<li><a href="#DEP0148">DEP0148: Folder mappings in <code>"exports"</code> (trailing <code>"/"</code>)</a></li>
<li><a href="#DEP0149">DEP0149: <code>http.IncomingMessage#connection</code></a></li>
<li><a href="#DEP0150">DEP0150: Changing the value of <code>process.config</code></a></li>
<li><a href="#DEP0151">DEP0151: Main index lookup and extension searching</a></li>
<li><a href="#DEP0152">DEP0152: Extension PerformanceEntry properties</a></li>
<li><a href="#DEP0153">DEP0153: <code>dns.lookup</code> and <code>dnsPromises.lookup</code> options type coercion</a></li>
<li><a href="#DEP0154">DEP0154: RSA-PSS generate key pair options</a></li>
<li><a href="#DEP0155">DEP0155: Trailing slashes in pattern specifier resolutions</a></li>
<li><a href="#DEP0156">DEP0156: <code>.aborted</code> property and <code>'abort'</code>, <code>'aborted'</code> event in <code>http</code></a></li>
<li><a href="#DEP0157">DEP0157: Thenable support in streams</a></li>
<li><a href="#DEP0158">DEP0158: <code>buffer.slice(start, end)</code></a></li>
<li><a href="#DEP0159">DEP0159: <code>ERR_INVALID_CALLBACK</code></a></li>
<li><a href="#DEP0160">DEP0160: <code>process.on('multipleResolves', handler)</code></a></li>
<li><a href="#DEP0161">DEP0161: <code>process._getActiveRequests()</code> and <code>process._getActiveHandles()</code></a></li>
<li><a href="#DEP0162">DEP0162: <code>fs.write()</code>, <code>fs.writeFileSync()</code> coercion to string</a></li>
<li><a href="#DEP0163">DEP0163: <code>channel.subscribe(onMessage)</code>, <code>channel.unsubscribe(onMessage)</code></a></li>
<li><a href="#DEP0164">DEP0164: <code>process.exit(code)</code>, <code>process.exitCode</code> coercion to integer</a></li>
<li><a href="#DEP0165">DEP0165: <code>--trace-atomics-wait</code></a></li>
<li><a href="#DEP0166">DEP0166: Double slashes in imports and exports targets</a></li>
<li><a href="#DEP0167">DEP0167: Weak <code>DiffieHellmanGroup</code> instances (<code>modp1</code>, <code>modp2</code>, <code>modp5</code>)</a></li>
<li><a href="#DEP0168">DEP0168: Unhandled exception in Node-API callbacks</a></li>
<li><a href="#DEP0169">DEP0169: Insecure url.parse()</a></li>
<li><a href="#DEP0170">DEP0170: Invalid port when using <code>url.parse()</code></a></li>
<li><a href="#DEP0171">DEP0171: Setters for <code>http.IncomingMessage</code> headers and trailers</a></li>
<li><a href="#DEP0172">DEP0172: The <code>asyncResource</code> property of <code>AsyncResource</code> bound functions</a></li>
<li><a href="#DEP0173">DEP0173: the <code>assert.CallTracker</code> class</a></li>
<li><a href="#DEP0174">DEP0174: calling <code>promisify</code> on a function that returns a <code>Promise</code></a></li>
<li><a href="#DEP0175">DEP0175: <code>util.toUSVString</code></a></li>
<li><a href="#DEP0176">DEP0176: <code>fs.F_OK</code>, <code>fs.R_OK</code>, <code>fs.W_OK</code>, <code>fs.X_OK</code></a></li>
<li><a href="#DEP0177">DEP0177: <code>util.types.isWebAssemblyCompiledModule</code></a></li>
<li><a href="#DEP0178">DEP0178: <code>dirent.path</code></a></li>
<li><a href="#DEP0179">DEP0179: <code>Hash</code> constructor</a></li>
<li><a href="#DEP0180">DEP0180: <code>fs.Stats</code> constructor</a></li>
<li><a href="#DEP0181">DEP0181: <code>Hmac</code> constructor</a></li>
<li><a href="#DEP0182">DEP0182: Short GCM authentication tags without explicit <code>authTagLength</code></a></li>
<li><a href="#DEP0183">DEP0183: OpenSSL engine-based APIs</a></li>
<li><a href="#DEP0184">DEP0184: Instantiating <code>node:zlib</code> classes without <code>new</code></a></li>
<li><a href="#DEP0185">DEP0185: Instantiating <code>node:repl</code> classes without <code>new</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_diagnostics_channel_diagnostics-channel">Diagnostics Channel</a></span>
<ul>
<li><a href="#all_diagnostics_channel_public-api">Public API</a>
<ul>
<li><a href="#all_diagnostics_channel_overview">Overview</a>
<ul>
<li><a href="#all_diagnostics_channel_diagnostics_channelhassubscribersname"><code>diagnostics_channel.hasSubscribers(name)</code></a></li>
<li><a href="#all_diagnostics_channel_diagnostics_channelchannelname"><code>diagnostics_channel.channel(name)</code></a></li>
<li><a href="#all_diagnostics_channel_diagnostics_channelsubscribename-onmessage"><code>diagnostics_channel.subscribe(name, onMessage)</code></a></li>
<li><a href="#all_diagnostics_channel_diagnostics_channelunsubscribename-onmessage"><code>diagnostics_channel.unsubscribe(name, onMessage)</code></a></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_diagnostics_channeltracingchannelnameorchannels"><code>diagnostics_channel.tracingChannel(nameOrChannels)</code></a></span></li>
</ul>
</li>
<li><a href="#all_diagnostics_channel_class-channel">Class: <code>Channel</code></a>
<ul>
<li><a href="#all_diagnostics_channel_channelhassubscribers"><code>channel.hasSubscribers</code></a></li>
<li><a href="#all_diagnostics_channel_channelpublishmessage"><code>channel.publish(message)</code></a></li>
<li><span class="stability_0"><a href="#all_diagnostics_channel_channelsubscribeonmessage"><code>channel.subscribe(onMessage)</code></a></span></li>
<li><span class="stability_0"><a href="#all_diagnostics_channel_channelunsubscribeonmessage"><code>channel.unsubscribe(onMessage)</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_channelbindstorestore-transform"><code>channel.bindStore(store[, transform])</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_channelunbindstorestore"><code>channel.unbindStore(store)</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args"><code>channel.runStores(context, fn[, thisArg[, ...args]])</code></a></span></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_class-tracingchannel">Class: <code>TracingChannel</code></a></span>
<ul>
<li><span class="stability_1"><a href="#all_diagnostics_channel_tracingchannelsubscribesubscribers"><code>tracingChannel.subscribe(subscribers)</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_tracingchannelunsubscribesubscribers"><code>tracingChannel.unsubscribe(subscribers)</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_tracingchanneltracesyncfn-context-thisarg-args"><code>tracingChannel.traceSync(fn[, context[, thisArg[, ...args]]])</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_tracingchanneltracepromisefn-context-thisarg-args"><code>tracingChannel.tracePromise(fn[, context[, thisArg[, ...args]]])</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_tracingchanneltracecallbackfn-position-context-thisarg-args"><code>tracingChannel.traceCallback(fn[, position[, context[, thisArg[, ...args]]]])</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_tracingchannelhassubscribers"><code>tracingChannel.hasSubscribers</code></a></span></li>
</ul>
</li>
<li><a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a>
<ul>
<li><a href="#all_diagnostics_channel_startevent"><code>start(event)</code></a></li>
<li><a href="#all_diagnostics_channel_endevent"><code>end(event)</code></a></li>
<li><a href="#all_diagnostics_channel_asyncstartevent"><code>asyncStart(event)</code></a></li>
<li><a href="#all_diagnostics_channel_asyncendevent"><code>asyncEnd(event)</code></a></li>
<li><a href="#all_diagnostics_channel_errorevent"><code>error(event)</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_built-in-channels">Built-in Channels</a></span>
<ul>
<li><a href="#all_diagnostics_channel_http">HTTP</a></li>
<li><a href="#all_diagnostics_channel_net">NET</a></li>
<li><a href="#all_diagnostics_channel_udp">UDP</a></li>
<li><a href="#all_diagnostics_channel_process">Process</a></li>
<li><a href="#all_diagnostics_channel_worker-thread">Worker Thread</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_dns_dns">DNS</a></span>
<ul>
<li><a href="#all_dns_class-dnsresolver">Class: <code>dns.Resolver</code></a>
<ul>
<li><a href="#all_dns_resolveroptions"><code>Resolver([options])</code></a></li>
<li><a href="#all_dns_resolvercancel"><code>resolver.cancel()</code></a></li>
<li><a href="#all_dns_resolversetlocaladdressipv4-ipv6"><code>resolver.setLocalAddress([ipv4][, ipv6])</code></a></li>
</ul>
</li>
<li><a href="#all_dns_dnsgetservers"><code>dns.getServers()</code></a></li>
<li><a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup(hostname[, options], callback)</code></a>
<ul>
<li><a href="#all_dns_supported-getaddrinfo-flags">Supported getaddrinfo flags</a></li>
</ul>
</li>
<li><a href="#all_dns_dnslookupserviceaddress-port-callback"><code>dns.lookupService(address, port, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvehostname-rrtype-callback"><code>dns.resolve(hostname[, rrtype], callback)</code></a></li>
<li><a href="#all_dns_dnsresolve4hostname-options-callback"><code>dns.resolve4(hostname[, options], callback)</code></a></li>
<li><a href="#all_dns_dnsresolve6hostname-options-callback"><code>dns.resolve6(hostname[, options], callback)</code></a></li>
<li><a href="#all_dns_dnsresolveanyhostname-callback"><code>dns.resolveAny(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvecnamehostname-callback"><code>dns.resolveCname(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvecaahostname-callback"><code>dns.resolveCaa(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvemxhostname-callback"><code>dns.resolveMx(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvenaptrhostname-callback"><code>dns.resolveNaptr(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvenshostname-callback"><code>dns.resolveNs(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolveptrhostname-callback"><code>dns.resolvePtr(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvesoahostname-callback"><code>dns.resolveSoa(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvesrvhostname-callback"><code>dns.resolveSrv(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvetxthostname-callback"><code>dns.resolveTxt(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsreverseip-callback"><code>dns.reverse(ip, callback)</code></a></li>
<li><a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder(order)</code></a></li>
<li><a href="#all_dns_dnsgetdefaultresultorder"><code>dns.getDefaultResultOrder()</code></a></li>
<li><a href="#all_dns_dnssetserversservers"><code>dns.setServers(servers)</code></a></li>
<li><a href="#all_dns_dns-promises-api">DNS promises API</a>
<ul>
<li><a href="#all_dns_class-dnspromisesresolver">Class: <code>dnsPromises.Resolver</code></a></li>
<li><a href="#all_dns_resolvercancel_1"><code>resolver.cancel()</code></a></li>
<li><a href="#all_dns_dnspromisesgetservers"><code>dnsPromises.getServers()</code></a></li>
<li><a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup(hostname[, options])</code></a></li>
<li><a href="#all_dns_dnspromiseslookupserviceaddress-port"><code>dnsPromises.lookupService(address, port)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvehostname-rrtype"><code>dnsPromises.resolve(hostname[, rrtype])</code></a></li>
<li><a href="#all_dns_dnspromisesresolve4hostname-options"><code>dnsPromises.resolve4(hostname[, options])</code></a></li>
<li><a href="#all_dns_dnspromisesresolve6hostname-options"><code>dnsPromises.resolve6(hostname[, options])</code></a></li>
<li><a href="#all_dns_dnspromisesresolveanyhostname"><code>dnsPromises.resolveAny(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvecaahostname"><code>dnsPromises.resolveCaa(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvecnamehostname"><code>dnsPromises.resolveCname(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvemxhostname"><code>dnsPromises.resolveMx(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvenaptrhostname"><code>dnsPromises.resolveNaptr(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvenshostname"><code>dnsPromises.resolveNs(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolveptrhostname"><code>dnsPromises.resolvePtr(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvesoahostname"><code>dnsPromises.resolveSoa(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvesrvhostname"><code>dnsPromises.resolveSrv(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvetxthostname"><code>dnsPromises.resolveTxt(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesreverseip"><code>dnsPromises.reverse(ip)</code></a></li>
<li><a href="#all_dns_dnspromisessetdefaultresultorderorder"><code>dnsPromises.setDefaultResultOrder(order)</code></a></li>
<li><a href="#all_dns_dnspromisesgetdefaultresultorder"><code>dnsPromises.getDefaultResultOrder()</code></a></li>
<li><a href="#all_dns_dnspromisessetserversservers"><code>dnsPromises.setServers(servers)</code></a></li>
</ul>
</li>
<li><a href="#all_dns_error-codes">Error codes</a></li>
<li><a href="#all_dns_implementation-considerations">Implementation considerations</a>
<ul>
<li><a href="#all_dns_dnslookup"><code>dns.lookup()</code></a></li>
<li><a href="#all_dns_dnsresolve-dnsresolve-and-dnsreverse"><code>dns.resolve()</code>, <code>dns.resolve*()</code>, and <code>dns.reverse()</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_0"><a href="#all_domain_domain">Domain</a></span>
<ul>
<li><a href="#all_domain_warning-dont-ignore-errors">Warning: Don't ignore errors!</a></li>
<li><a href="#all_domain_additions-to-error-objects">Additions to <code>Error</code> objects</a></li>
<li><a href="#all_domain_implicit-binding">Implicit binding</a></li>
<li><a href="#all_domain_explicit-binding">Explicit binding</a></li>
<li><a href="#all_domain_domaincreate"><code>domain.create()</code></a></li>
<li><a href="#all_domain_class-domain">Class: <code>Domain</code></a>
<ul>
<li><a href="#all_domain_domainmembers"><code>domain.members</code></a></li>
<li><a href="#all_domain_domainaddemitter"><code>domain.add(emitter)</code></a></li>
<li><a href="#all_domain_domainbindcallback"><code>domain.bind(callback)</code></a></li>
<li><a href="#all_domain_domainenter"><code>domain.enter()</code></a></li>
<li><a href="#all_domain_domainexit"><code>domain.exit()</code></a></li>
<li><a href="#all_domain_domaininterceptcallback"><code>domain.intercept(callback)</code></a></li>
<li><a href="#all_domain_domainremoveemitter"><code>domain.remove(emitter)</code></a></li>
<li><a href="#all_domain_domainrunfn-args"><code>domain.run(fn[, ...args])</code></a></li>
</ul>
</li>
<li><a href="#all_domain_domains-and-promises">Domains and promises</a></li>
</ul>
</li>
<li><a href="#all_errors_errors">Errors</a>
<ul>
<li><a href="#all_errors_error-propagation-and-interception">Error propagation and interception</a></li>
<li><a href="#all_errors_class-error">Class: <code>Error</code></a>
<ul>
<li><a href="#all_errors_new-errormessage-options"><code>new Error(message[, options])</code></a></li>
<li><a href="#all_errors_errorcapturestacktracetargetobject-constructoropt"><code>Error.captureStackTrace(targetObject[, constructorOpt])</code></a></li>
<li><a href="#all_errors_errorstacktracelimit"><code>Error.stackTraceLimit</code></a></li>
<li><a href="#all_errors_errorcause"><code>error.cause</code></a></li>
<li><a href="#all_errors_errorcode"><code>error.code</code></a></li>
<li><a href="#all_errors_errormessage"><code>error.message</code></a></li>
<li><a href="#all_errors_errorstack"><code>error.stack</code></a></li>
</ul>
</li>
<li><a href="#all_errors_class-assertionerror">Class: <code>AssertionError</code></a></li>
<li><a href="#all_errors_class-rangeerror">Class: <code>RangeError</code></a></li>
<li><a href="#all_errors_class-referenceerror">Class: <code>ReferenceError</code></a></li>
<li><a href="#all_errors_class-syntaxerror">Class: <code>SyntaxError</code></a></li>
<li><a href="#all_errors_class-systemerror">Class: <code>SystemError</code></a>
<ul>
<li><a href="#all_errors_erroraddress"><code>error.address</code></a></li>
<li><a href="#all_errors_errorcode_1"><code>error.code</code></a></li>
<li><a href="#all_errors_errordest"><code>error.dest</code></a></li>
<li><a href="#all_errors_errorerrno"><code>error.errno</code></a></li>
<li><a href="#all_errors_errorinfo"><code>error.info</code></a></li>
<li><a href="#all_errors_errormessage_1"><code>error.message</code></a></li>
<li><a href="#all_errors_errorpath"><code>error.path</code></a></li>
<li><a href="#all_errors_errorport"><code>error.port</code></a></li>
<li><a href="#all_errors_errorsyscall"><code>error.syscall</code></a></li>
<li><a href="#all_errors_common-system-errors">Common system errors</a></li>
</ul>
</li>
<li><a href="#all_errors_class-typeerror">Class: <code>TypeError</code></a></li>
<li><a href="#all_errors_exceptions-vs-errors">Exceptions vs. errors</a></li>
<li><a href="#all_errors_openssl-errors">OpenSSL errors</a>
<ul>
<li><a href="#all_errors_erroropensslerrorstack"><code>error.opensslErrorStack</code></a></li>
<li><a href="#all_errors_errorfunction"><code>error.function</code></a></li>
<li><a href="#all_errors_errorlibrary"><code>error.library</code></a></li>
<li><a href="#all_errors_errorreason"><code>error.reason</code></a></li>
</ul>
</li>
<li><a href="#all_errors_nodejs-error-codes">Node.js error codes</a>
<ul>
<li><a href="#all_errors_abort_err"><code>ABORT_ERR</code></a></li>
<li><a href="#all_errors_err_access_denied"><code>ERR_ACCESS_DENIED</code></a></li>
<li><a href="#all_errors_err_ambiguous_argument"><code>ERR_AMBIGUOUS_ARGUMENT</code></a></li>
<li><a href="#all_errors_err_arg_not_iterable"><code>ERR_ARG_NOT_ITERABLE</code></a></li>
<li><a href="#all_errors_err_assertion"><code>ERR_ASSERTION</code></a></li>
<li><a href="#all_errors_err_async_callback"><code>ERR_ASYNC_CALLBACK</code></a></li>
<li><a href="#all_errors_err_async_type"><code>ERR_ASYNC_TYPE</code></a></li>
<li><a href="#all_errors_err_brotli_compression_failed"><code>ERR_BROTLI_COMPRESSION_FAILED</code></a></li>
<li><a href="#all_errors_err_brotli_invalid_param"><code>ERR_BROTLI_INVALID_PARAM</code></a></li>
<li><a href="#all_errors_err_buffer_context_not_available"><code>ERR_BUFFER_CONTEXT_NOT_AVAILABLE</code></a></li>
<li><a href="#all_errors_err_buffer_out_of_bounds"><code>ERR_BUFFER_OUT_OF_BOUNDS</code></a></li>
<li><a href="#all_errors_err_buffer_too_large"><code>ERR_BUFFER_TOO_LARGE</code></a></li>
<li><a href="#all_errors_err_cannot_watch_sigint"><code>ERR_CANNOT_WATCH_SIGINT</code></a></li>
<li><a href="#all_errors_err_child_closed_before_reply"><code>ERR_CHILD_CLOSED_BEFORE_REPLY</code></a></li>
<li><a href="#all_errors_err_child_process_ipc_required"><code>ERR_CHILD_PROCESS_IPC_REQUIRED</code></a></li>
<li><a href="#all_errors_err_child_process_stdio_maxbuffer"><code>ERR_CHILD_PROCESS_STDIO_MAXBUFFER</code></a></li>
<li><a href="#all_errors_err_closed_message_port"><code>ERR_CLOSED_MESSAGE_PORT</code></a></li>
<li><a href="#all_errors_err_console_writable_stream"><code>ERR_CONSOLE_WRITABLE_STREAM</code></a></li>
<li><a href="#all_errors_err_construct_call_invalid"><code>ERR_CONSTRUCT_CALL_INVALID</code></a></li>
<li><a href="#all_errors_err_construct_call_required"><code>ERR_CONSTRUCT_CALL_REQUIRED</code></a></li>
<li><a href="#all_errors_err_context_not_initialized"><code>ERR_CONTEXT_NOT_INITIALIZED</code></a></li>
<li><a href="#all_errors_err_crypto_custom_engine_not_supported"><code>ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED</code></a></li>
<li><a href="#all_errors_err_crypto_ecdh_invalid_format"><code>ERR_CRYPTO_ECDH_INVALID_FORMAT</code></a></li>
<li><a href="#all_errors_err_crypto_ecdh_invalid_public_key"><code>ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY</code></a></li>
<li><a href="#all_errors_err_crypto_engine_unknown"><code>ERR_CRYPTO_ENGINE_UNKNOWN</code></a></li>
<li><a href="#all_errors_err_crypto_fips_forced"><code>ERR_CRYPTO_FIPS_FORCED</code></a></li>
<li><a href="#all_errors_err_crypto_fips_unavailable"><code>ERR_CRYPTO_FIPS_UNAVAILABLE</code></a></li>
<li><a href="#all_errors_err_crypto_hash_finalized"><code>ERR_CRYPTO_HASH_FINALIZED</code></a></li>
<li><a href="#all_errors_err_crypto_hash_update_failed"><code>ERR_CRYPTO_HASH_UPDATE_FAILED</code></a></li>
<li><a href="#all_errors_err_crypto_incompatible_key"><code>ERR_CRYPTO_INCOMPATIBLE_KEY</code></a></li>
<li><a href="#all_errors_err_crypto_incompatible_key_options"><code>ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS</code></a></li>
<li><a href="#all_errors_err_crypto_initialization_failed"><code>ERR_CRYPTO_INITIALIZATION_FAILED</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_auth_tag"><code>ERR_CRYPTO_INVALID_AUTH_TAG</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_counter"><code>ERR_CRYPTO_INVALID_COUNTER</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_curve"><code>ERR_CRYPTO_INVALID_CURVE</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_digest"><code>ERR_CRYPTO_INVALID_DIGEST</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_iv"><code>ERR_CRYPTO_INVALID_IV</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_jwk"><code>ERR_CRYPTO_INVALID_JWK</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_key_object_type"><code>ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_keylen"><code>ERR_CRYPTO_INVALID_KEYLEN</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_keypair"><code>ERR_CRYPTO_INVALID_KEYPAIR</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_keytype"><code>ERR_CRYPTO_INVALID_KEYTYPE</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_messagelen"><code>ERR_CRYPTO_INVALID_MESSAGELEN</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_scrypt_params"><code>ERR_CRYPTO_INVALID_SCRYPT_PARAMS</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_state"><code>ERR_CRYPTO_INVALID_STATE</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_tag_length"><code>ERR_CRYPTO_INVALID_TAG_LENGTH</code></a></li>
<li><a href="#all_errors_err_crypto_job_init_failed"><code>ERR_CRYPTO_JOB_INIT_FAILED</code></a></li>
<li><a href="#all_errors_err_crypto_jwk_unsupported_curve"><code>ERR_CRYPTO_JWK_UNSUPPORTED_CURVE</code></a></li>
<li><a href="#all_errors_err_crypto_jwk_unsupported_key_type"><code>ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE</code></a></li>
<li><a href="#all_errors_err_crypto_operation_failed"><code>ERR_CRYPTO_OPERATION_FAILED</code></a></li>
<li><a href="#all_errors_err_crypto_pbkdf2_error"><code>ERR_CRYPTO_PBKDF2_ERROR</code></a></li>
<li><a href="#all_errors_err_crypto_scrypt_invalid_parameter"><code>ERR_CRYPTO_SCRYPT_INVALID_PARAMETER</code></a></li>
<li><a href="#all_errors_err_crypto_scrypt_not_supported"><code>ERR_CRYPTO_SCRYPT_NOT_SUPPORTED</code></a></li>
<li><a href="#all_errors_err_crypto_sign_key_required"><code>ERR_CRYPTO_SIGN_KEY_REQUIRED</code></a></li>
<li><a href="#all_errors_err_crypto_timing_safe_equal_length"><code>ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH</code></a></li>
<li><a href="#all_errors_err_crypto_unknown_cipher"><code>ERR_CRYPTO_UNKNOWN_CIPHER</code></a></li>
<li><a href="#all_errors_err_crypto_unknown_dh_group"><code>ERR_CRYPTO_UNKNOWN_DH_GROUP</code></a></li>
<li><a href="#all_errors_err_crypto_unsupported_operation"><code>ERR_CRYPTO_UNSUPPORTED_OPERATION</code></a></li>
<li><a href="#all_errors_err_debugger_error"><code>ERR_DEBUGGER_ERROR</code></a></li>
<li><a href="#all_errors_err_debugger_startup_error"><code>ERR_DEBUGGER_STARTUP_ERROR</code></a></li>
<li><a href="#all_errors_err_dlopen_disabled"><code>ERR_DLOPEN_DISABLED</code></a></li>
<li><a href="#all_errors_err_dlopen_failed"><code>ERR_DLOPEN_FAILED</code></a></li>
<li><a href="#all_errors_err_dir_closed"><code>ERR_DIR_CLOSED</code></a></li>
<li><a href="#all_errors_err_dir_concurrent_operation"><code>ERR_DIR_CONCURRENT_OPERATION</code></a></li>
<li><a href="#all_errors_err_dns_set_servers_failed"><code>ERR_DNS_SET_SERVERS_FAILED</code></a></li>
<li><a href="#all_errors_err_domain_callback_not_available"><code>ERR_DOMAIN_CALLBACK_NOT_AVAILABLE</code></a></li>
<li><a href="#all_errors_err_domain_cannot_set_uncaught_exception_capture"><code>ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE</code></a></li>
<li><a href="#all_errors_err_duplicate_startup_snapshot_main_function"><code>ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION</code></a></li>
<li><a href="#all_errors_err_encoding_invalid_encoded_data"><code>ERR_ENCODING_INVALID_ENCODED_DATA</code></a></li>
<li><a href="#all_errors_err_encoding_not_supported"><code>ERR_ENCODING_NOT_SUPPORTED</code></a></li>
<li><a href="#all_errors_err_eval_esm_cannot_print"><code>ERR_EVAL_ESM_CANNOT_PRINT</code></a></li>
<li><a href="#all_errors_err_event_recursion"><code>ERR_EVENT_RECURSION</code></a></li>
<li><a href="#all_errors_err_execution_environment_not_available"><code>ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE</code></a></li>
<li><a href="#all_errors_err_falsy_value_rejection"><code>ERR_FALSY_VALUE_REJECTION</code></a></li>
<li><a href="#all_errors_err_feature_unavailable_on_platform"><code>ERR_FEATURE_UNAVAILABLE_ON_PLATFORM</code></a></li>
<li><a href="#all_errors_err_fs_cp_dir_to_non_dir"><code>ERR_FS_CP_DIR_TO_NON_DIR</code></a></li>
<li><a href="#all_errors_err_fs_cp_eexist"><code>ERR_FS_CP_EEXIST</code></a></li>
<li><a href="#all_errors_err_fs_cp_einval"><code>ERR_FS_CP_EINVAL</code></a></li>
<li><a href="#all_errors_err_http_body_not_allowed"><code>ERR_HTTP_BODY_NOT_ALLOWED</code></a></li>
<li><a href="#all_errors_err_http_content_length_mismatch"><code>ERR_HTTP_CONTENT_LENGTH_MISMATCH</code></a></li>
<li><a href="#all_errors_err_fs_cp_fifo_pipe"><code>ERR_FS_CP_FIFO_PIPE</code></a></li>
<li><a href="#all_errors_err_fs_cp_non_dir_to_dir"><code>ERR_FS_CP_NON_DIR_TO_DIR</code></a></li>
<li><a href="#all_errors_err_fs_cp_socket"><code>ERR_FS_CP_SOCKET</code></a></li>
<li><a href="#all_errors_err_fs_cp_symlink_to_subdirectory"><code>ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY</code></a></li>
<li><a href="#all_errors_err_fs_cp_unknown"><code>ERR_FS_CP_UNKNOWN</code></a></li>
<li><a href="#all_errors_err_fs_eisdir"><code>ERR_FS_EISDIR</code></a></li>
<li><a href="#all_errors_err_fs_file_too_large"><code>ERR_FS_FILE_TOO_LARGE</code></a></li>
<li><a href="#all_errors_err_fs_invalid_symlink_type"><code>ERR_FS_INVALID_SYMLINK_TYPE</code></a></li>
<li><a href="#all_errors_err_http_headers_sent"><code>ERR_HTTP_HEADERS_SENT</code></a></li>
<li><a href="#all_errors_err_http_invalid_header_value"><code>ERR_HTTP_INVALID_HEADER_VALUE</code></a></li>
<li><a href="#all_errors_err_http_invalid_status_code"><code>ERR_HTTP_INVALID_STATUS_CODE</code></a></li>
<li><a href="#all_errors_err_http_request_timeout"><code>ERR_HTTP_REQUEST_TIMEOUT</code></a></li>
<li><a href="#all_errors_err_http_socket_assigned"><code>ERR_HTTP_SOCKET_ASSIGNED</code></a></li>
<li><a href="#all_errors_err_http_socket_encoding"><code>ERR_HTTP_SOCKET_ENCODING</code></a></li>
<li><a href="#all_errors_err_http_trailer_invalid"><code>ERR_HTTP_TRAILER_INVALID</code></a></li>
<li><a href="#all_errors_err_http2_altsvc_invalid_origin"><code>ERR_HTTP2_ALTSVC_INVALID_ORIGIN</code></a></li>
<li><a href="#all_errors_err_http2_altsvc_length"><code>ERR_HTTP2_ALTSVC_LENGTH</code></a></li>
<li><a href="#all_errors_err_http2_connect_authority"><code>ERR_HTTP2_CONNECT_AUTHORITY</code></a></li>
<li><a href="#all_errors_err_http2_connect_path"><code>ERR_HTTP2_CONNECT_PATH</code></a></li>
<li><a href="#all_errors_err_http2_connect_scheme"><code>ERR_HTTP2_CONNECT_SCHEME</code></a></li>
<li><a href="#all_errors_err_http2_error"><code>ERR_HTTP2_ERROR</code></a></li>
<li><a href="#all_errors_err_http2_goaway_session"><code>ERR_HTTP2_GOAWAY_SESSION</code></a></li>
<li><a href="#all_errors_err_http2_header_single_value"><code>ERR_HTTP2_HEADER_SINGLE_VALUE</code></a></li>
<li><a href="#all_errors_err_http2_headers_after_respond"><code>ERR_HTTP2_HEADERS_AFTER_RESPOND</code></a></li>
<li><a href="#all_errors_err_http2_headers_sent"><code>ERR_HTTP2_HEADERS_SENT</code></a></li>
<li><a href="#all_errors_err_http2_info_status_not_allowed"><code>ERR_HTTP2_INFO_STATUS_NOT_ALLOWED</code></a></li>
<li><a href="#all_errors_err_http2_invalid_connection_headers"><code>ERR_HTTP2_INVALID_CONNECTION_HEADERS</code></a></li>
<li><a href="#all_errors_err_http2_invalid_header_value"><code>ERR_HTTP2_INVALID_HEADER_VALUE</code></a></li>
<li><a href="#all_errors_err_http2_invalid_info_status"><code>ERR_HTTP2_INVALID_INFO_STATUS</code></a></li>
<li><a href="#all_errors_err_http2_invalid_origin"><code>ERR_HTTP2_INVALID_ORIGIN</code></a></li>
<li><a href="#all_errors_err_http2_invalid_packed_settings_length"><code>ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH</code></a></li>
<li><a href="#all_errors_err_http2_invalid_pseudoheader"><code>ERR_HTTP2_INVALID_PSEUDOHEADER</code></a></li>
<li><a href="#all_errors_err_http2_invalid_session"><code>ERR_HTTP2_INVALID_SESSION</code></a></li>
<li><a href="#all_errors_err_http2_invalid_setting_value"><code>ERR_HTTP2_INVALID_SETTING_VALUE</code></a></li>
<li><a href="#all_errors_err_http2_invalid_stream"><code>ERR_HTTP2_INVALID_STREAM</code></a></li>
<li><a href="#all_errors_err_http2_max_pending_settings_ack"><code>ERR_HTTP2_MAX_PENDING_SETTINGS_ACK</code></a></li>
<li><a href="#all_errors_err_http2_nested_push"><code>ERR_HTTP2_NESTED_PUSH</code></a></li>
<li><a href="#all_errors_err_http2_no_mem"><code>ERR_HTTP2_NO_MEM</code></a></li>
<li><a href="#all_errors_err_http2_no_socket_manipulation"><code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code></a></li>
<li><a href="#all_errors_err_http2_origin_length"><code>ERR_HTTP2_ORIGIN_LENGTH</code></a></li>
<li><a href="#all_errors_err_http2_out_of_streams"><code>ERR_HTTP2_OUT_OF_STREAMS</code></a></li>
<li><a href="#all_errors_err_http2_payload_forbidden"><code>ERR_HTTP2_PAYLOAD_FORBIDDEN</code></a></li>
<li><a href="#all_errors_err_http2_ping_cancel"><code>ERR_HTTP2_PING_CANCEL</code></a></li>
<li><a href="#all_errors_err_http2_ping_length"><code>ERR_HTTP2_PING_LENGTH</code></a></li>
<li><a href="#all_errors_err_http2_pseudoheader_not_allowed"><code>ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED</code></a></li>
<li><a href="#all_errors_err_http2_push_disabled"><code>ERR_HTTP2_PUSH_DISABLED</code></a></li>
<li><a href="#all_errors_err_http2_send_file"><code>ERR_HTTP2_SEND_FILE</code></a></li>
<li><a href="#all_errors_err_http2_send_file_noseek"><code>ERR_HTTP2_SEND_FILE_NOSEEK</code></a></li>
<li><a href="#all_errors_err_http2_session_error"><code>ERR_HTTP2_SESSION_ERROR</code></a></li>
<li><a href="#all_errors_err_http2_settings_cancel"><code>ERR_HTTP2_SETTINGS_CANCEL</code></a></li>
<li><a href="#all_errors_err_http2_socket_bound"><code>ERR_HTTP2_SOCKET_BOUND</code></a></li>
<li><a href="#all_errors_err_http2_socket_unbound"><code>ERR_HTTP2_SOCKET_UNBOUND</code></a></li>
<li><a href="#all_errors_err_http2_status_101"><code>ERR_HTTP2_STATUS_101</code></a></li>
<li><a href="#all_errors_err_http2_status_invalid"><code>ERR_HTTP2_STATUS_INVALID</code></a></li>
<li><a href="#all_errors_err_http2_stream_cancel"><code>ERR_HTTP2_STREAM_CANCEL</code></a></li>
<li><a href="#all_errors_err_http2_stream_error"><code>ERR_HTTP2_STREAM_ERROR</code></a></li>
<li><a href="#all_errors_err_http2_stream_self_dependency"><code>ERR_HTTP2_STREAM_SELF_DEPENDENCY</code></a></li>
<li><a href="#all_errors_err_http2_too_many_custom_settings"><code>ERR_HTTP2_TOO_MANY_CUSTOM_SETTINGS</code></a></li>
<li><a href="#all_errors_err_http2_too_many_invalid_frames"><code>ERR_HTTP2_TOO_MANY_INVALID_FRAMES</code></a></li>
<li><a href="#all_errors_err_http2_trailers_already_sent"><code>ERR_HTTP2_TRAILERS_ALREADY_SENT</code></a></li>
<li><a href="#all_errors_err_http2_trailers_not_ready"><code>ERR_HTTP2_TRAILERS_NOT_READY</code></a></li>
<li><a href="#all_errors_err_http2_unsupported_protocol"><code>ERR_HTTP2_UNSUPPORTED_PROTOCOL</code></a></li>
<li><a href="#all_errors_err_illegal_constructor"><code>ERR_ILLEGAL_CONSTRUCTOR</code></a></li>
<li><a href="#all_errors_err_import_assertion_type_failed"><code>ERR_IMPORT_ASSERTION_TYPE_FAILED</code></a></li>
<li><a href="#all_errors_err_import_assertion_type_missing"><code>ERR_IMPORT_ASSERTION_TYPE_MISSING</code></a></li>
<li><a href="#all_errors_err_import_assertion_type_unsupported"><code>ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED</code></a></li>
<li><a href="#all_errors_err_import_attribute_unsupported"><code>ERR_IMPORT_ATTRIBUTE_UNSUPPORTED</code></a></li>
<li><a href="#all_errors_err_incompatible_option_pair"><code>ERR_INCOMPATIBLE_OPTION_PAIR</code></a></li>
<li><span class="stability_1"><a href="#all_errors_err_input_type_not_allowed"><code>ERR_INPUT_TYPE_NOT_ALLOWED</code></a></span></li>
<li><a href="#all_errors_err_inspector_already_activated"><code>ERR_INSPECTOR_ALREADY_ACTIVATED</code></a></li>
<li><a href="#all_errors_err_inspector_already_connected"><code>ERR_INSPECTOR_ALREADY_CONNECTED</code></a></li>
<li><a href="#all_errors_err_inspector_closed"><code>ERR_INSPECTOR_CLOSED</code></a></li>
<li><a href="#all_errors_err_inspector_command"><code>ERR_INSPECTOR_COMMAND</code></a></li>
<li><a href="#all_errors_err_inspector_not_active"><code>ERR_INSPECTOR_NOT_ACTIVE</code></a></li>
<li><a href="#all_errors_err_inspector_not_available"><code>ERR_INSPECTOR_NOT_AVAILABLE</code></a></li>
<li><a href="#all_errors_err_inspector_not_connected"><code>ERR_INSPECTOR_NOT_CONNECTED</code></a></li>
<li><a href="#all_errors_err_inspector_not_worker"><code>ERR_INSPECTOR_NOT_WORKER</code></a></li>
<li><a href="#all_errors_err_internal_assertion"><code>ERR_INTERNAL_ASSERTION</code></a></li>
<li><a href="#all_errors_err_invalid_address"><code>ERR_INVALID_ADDRESS</code></a></li>
<li><a href="#all_errors_err_invalid_address_family"><code>ERR_INVALID_ADDRESS_FAMILY</code></a></li>
<li><a href="#all_errors_err_invalid_arg_type"><code>ERR_INVALID_ARG_TYPE</code></a></li>
<li><a href="#all_errors_err_invalid_arg_value"><code>ERR_INVALID_ARG_VALUE</code></a></li>
<li><a href="#all_errors_err_invalid_async_id"><code>ERR_INVALID_ASYNC_ID</code></a></li>
<li><a href="#all_errors_err_invalid_buffer_size"><code>ERR_INVALID_BUFFER_SIZE</code></a></li>
<li><a href="#all_errors_err_invalid_char"><code>ERR_INVALID_CHAR</code></a></li>
<li><a href="#all_errors_err_invalid_cursor_pos"><code>ERR_INVALID_CURSOR_POS</code></a></li>
<li><a href="#all_errors_err_invalid_fd"><code>ERR_INVALID_FD</code></a></li>
<li><a href="#all_errors_err_invalid_fd_type"><code>ERR_INVALID_FD_TYPE</code></a></li>
<li><a href="#all_errors_err_invalid_file_url_host"><code>ERR_INVALID_FILE_URL_HOST</code></a></li>
<li><a href="#all_errors_err_invalid_file_url_path"><code>ERR_INVALID_FILE_URL_PATH</code></a></li>
<li><a href="#all_errors_err_invalid_handle_type"><code>ERR_INVALID_HANDLE_TYPE</code></a></li>
<li><a href="#all_errors_err_invalid_http_token"><code>ERR_INVALID_HTTP_TOKEN</code></a></li>
<li><a href="#all_errors_err_invalid_ip_address"><code>ERR_INVALID_IP_ADDRESS</code></a></li>
<li><a href="#all_errors_err_invalid_mime_syntax"><code>ERR_INVALID_MIME_SYNTAX</code></a></li>
<li><a href="#all_errors_err_invalid_module"><code>ERR_INVALID_MODULE</code></a></li>
<li><a href="#all_errors_err_invalid_module_specifier"><code>ERR_INVALID_MODULE_SPECIFIER</code></a></li>
<li><a href="#all_errors_err_invalid_object_define_property"><code>ERR_INVALID_OBJECT_DEFINE_PROPERTY</code></a></li>
<li><a href="#all_errors_err_invalid_package_config"><code>ERR_INVALID_PACKAGE_CONFIG</code></a></li>
<li><a href="#all_errors_err_invalid_package_target"><code>ERR_INVALID_PACKAGE_TARGET</code></a></li>
<li><a href="#all_errors_err_invalid_performance_mark"><code>ERR_INVALID_PERFORMANCE_MARK</code></a></li>
<li><a href="#all_errors_err_invalid_protocol"><code>ERR_INVALID_PROTOCOL</code></a></li>
<li><a href="#all_errors_err_invalid_repl_eval_config"><code>ERR_INVALID_REPL_EVAL_CONFIG</code></a></li>
<li><a href="#all_errors_err_invalid_repl_input"><code>ERR_INVALID_REPL_INPUT</code></a></li>
<li><a href="#all_errors_err_invalid_return_property"><code>ERR_INVALID_RETURN_PROPERTY</code></a></li>
<li><a href="#all_errors_err_invalid_return_property_value"><code>ERR_INVALID_RETURN_PROPERTY_VALUE</code></a></li>
<li><a href="#all_errors_err_invalid_return_value"><code>ERR_INVALID_RETURN_VALUE</code></a></li>
<li><a href="#all_errors_err_invalid_state"><code>ERR_INVALID_STATE</code></a></li>
<li><a href="#all_errors_err_invalid_sync_fork_input"><code>ERR_INVALID_SYNC_FORK_INPUT</code></a></li>
<li><a href="#all_errors_err_invalid_this"><code>ERR_INVALID_THIS</code></a></li>
<li><a href="#all_errors_err_invalid_transfer_object"><code>ERR_INVALID_TRANSFER_OBJECT</code></a></li>
<li><a href="#all_errors_err_invalid_tuple"><code>ERR_INVALID_TUPLE</code></a></li>
<li><a href="#all_errors_err_invalid_uri"><code>ERR_INVALID_URI</code></a></li>
<li><a href="#all_errors_err_invalid_url"><code>ERR_INVALID_URL</code></a></li>
<li><a href="#all_errors_err_invalid_url_scheme"><code>ERR_INVALID_URL_SCHEME</code></a></li>
<li><a href="#all_errors_err_ipc_channel_closed"><code>ERR_IPC_CHANNEL_CLOSED</code></a></li>
<li><a href="#all_errors_err_ipc_disconnected"><code>ERR_IPC_DISCONNECTED</code></a></li>
<li><a href="#all_errors_err_ipc_one_pipe"><code>ERR_IPC_ONE_PIPE</code></a></li>
<li><a href="#all_errors_err_ipc_sync_fork"><code>ERR_IPC_SYNC_FORK</code></a></li>
<li><a href="#all_errors_err_loader_chain_incomplete"><code>ERR_LOADER_CHAIN_INCOMPLETE</code></a></li>
<li><a href="#all_errors_err_manifest_assert_integrity"><code>ERR_MANIFEST_ASSERT_INTEGRITY</code></a></li>
<li><a href="#all_errors_err_manifest_dependency_missing"><code>ERR_MANIFEST_DEPENDENCY_MISSING</code></a></li>
<li><a href="#all_errors_err_manifest_integrity_mismatch"><code>ERR_MANIFEST_INTEGRITY_MISMATCH</code></a></li>
<li><a href="#all_errors_err_manifest_invalid_resource_field"><code>ERR_MANIFEST_INVALID_RESOURCE_FIELD</code></a></li>
<li><a href="#all_errors_err_manifest_invalid_specifier"><code>ERR_MANIFEST_INVALID_SPECIFIER</code></a></li>
<li><a href="#all_errors_err_manifest_parse_policy"><code>ERR_MANIFEST_PARSE_POLICY</code></a></li>
<li><a href="#all_errors_err_manifest_tdz"><code>ERR_MANIFEST_TDZ</code></a></li>
<li><a href="#all_errors_err_manifest_unknown_onerror"><code>ERR_MANIFEST_UNKNOWN_ONERROR</code></a></li>
<li><a href="#all_errors_err_memory_allocation_failed"><code>ERR_MEMORY_ALLOCATION_FAILED</code></a></li>
<li><a href="#all_errors_err_message_target_context_unavailable"><code>ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE</code></a></li>
<li><a href="#all_errors_err_method_not_implemented"><code>ERR_METHOD_NOT_IMPLEMENTED</code></a></li>
<li><a href="#all_errors_err_missing_args"><code>ERR_MISSING_ARGS</code></a></li>
<li><a href="#all_errors_err_missing_option"><code>ERR_MISSING_OPTION</code></a></li>
<li><a href="#all_errors_err_missing_passphrase"><code>ERR_MISSING_PASSPHRASE</code></a></li>
<li><a href="#all_errors_err_missing_platform_for_worker"><code>ERR_MISSING_PLATFORM_FOR_WORKER</code></a></li>
<li><a href="#all_errors_err_missing_transferable_in_transfer_list"><code>ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST</code></a></li>
<li><a href="#all_errors_err_module_not_found"><code>ERR_MODULE_NOT_FOUND</code></a></li>
<li><a href="#all_errors_err_multiple_callback"><code>ERR_MULTIPLE_CALLBACK</code></a></li>
<li><a href="#all_errors_err_napi_cons_function"><code>ERR_NAPI_CONS_FUNCTION</code></a></li>
<li><a href="#all_errors_err_napi_invalid_dataview_args"><code>ERR_NAPI_INVALID_DATAVIEW_ARGS</code></a></li>
<li><a href="#all_errors_err_napi_invalid_typedarray_alignment"><code>ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT</code></a></li>
<li><a href="#all_errors_err_napi_invalid_typedarray_length"><code>ERR_NAPI_INVALID_TYPEDARRAY_LENGTH</code></a></li>
<li><a href="#all_errors_err_napi_tsfn_call_js"><code>ERR_NAPI_TSFN_CALL_JS</code></a></li>
<li><a href="#all_errors_err_napi_tsfn_get_undefined"><code>ERR_NAPI_TSFN_GET_UNDEFINED</code></a></li>
<li><a href="#all_errors_err_napi_tsfn_start_idle_loop"><code>ERR_NAPI_TSFN_START_IDLE_LOOP</code></a></li>
<li><a href="#all_errors_err_napi_tsfn_stop_idle_loop"><code>ERR_NAPI_TSFN_STOP_IDLE_LOOP</code></a></li>
<li><a href="#all_errors_err_not_building_snapshot"><code>ERR_NOT_BUILDING_SNAPSHOT</code></a></li>
<li><a href="#all_errors_err_not_in_single_executable_application"><code>ERR_NOT_IN_SINGLE_EXECUTABLE_APPLICATION</code></a></li>
<li><a href="#all_errors_err_not_supported_in_snapshot"><code>ERR_NOT_SUPPORTED_IN_SNAPSHOT</code></a></li>
<li><a href="#all_errors_err_no_crypto"><code>ERR_NO_CRYPTO</code></a></li>
<li><a href="#all_errors_err_no_icu"><code>ERR_NO_ICU</code></a></li>
<li><a href="#all_errors_err_non_context_aware_disabled"><code>ERR_NON_CONTEXT_AWARE_DISABLED</code></a></li>
<li><a href="#all_errors_err_out_of_range"><code>ERR_OUT_OF_RANGE</code></a></li>
<li><a href="#all_errors_err_package_import_not_defined"><code>ERR_PACKAGE_IMPORT_NOT_DEFINED</code></a></li>
<li><a href="#all_errors_err_package_path_not_exported"><code>ERR_PACKAGE_PATH_NOT_EXPORTED</code></a></li>
<li><a href="#all_errors_err_parse_args_invalid_option_value"><code>ERR_PARSE_ARGS_INVALID_OPTION_VALUE</code></a></li>
<li><a href="#all_errors_err_parse_args_unexpected_positional"><code>ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL</code></a></li>
<li><a href="#all_errors_err_parse_args_unknown_option"><code>ERR_PARSE_ARGS_UNKNOWN_OPTION</code></a></li>
<li><a href="#all_errors_err_performance_invalid_timestamp"><code>ERR_PERFORMANCE_INVALID_TIMESTAMP</code></a></li>
<li><a href="#all_errors_err_performance_measure_invalid_options"><code>ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS</code></a></li>
<li><a href="#all_errors_err_proto_access"><code>ERR_PROTO_ACCESS</code></a></li>
<li><span class="stability_1"><a href="#all_errors_err_require_cycle_module"><code>ERR_REQUIRE_CYCLE_MODULE</code></a></span></li>
<li><span class="stability_1"><a href="#all_errors_err_require_async_module"><code>ERR_REQUIRE_ASYNC_MODULE</code></a></span></li>
<li><span class="stability_0"><a href="#all_errors_err_require_esm"><code>ERR_REQUIRE_ESM</code></a></span></li>
<li><a href="#all_errors_err_script_execution_interrupted"><code>ERR_SCRIPT_EXECUTION_INTERRUPTED</code></a></li>
<li><a href="#all_errors_err_script_execution_timeout"><code>ERR_SCRIPT_EXECUTION_TIMEOUT</code></a></li>
<li><a href="#all_errors_err_server_already_listen"><code>ERR_SERVER_ALREADY_LISTEN</code></a></li>
<li><a href="#all_errors_err_server_not_running"><code>ERR_SERVER_NOT_RUNNING</code></a></li>
<li><a href="#all_errors_err_single_executable_application_asset_not_found"><code>ERR_SINGLE_EXECUTABLE_APPLICATION_ASSET_NOT_FOUND</code></a></li>
<li><a href="#all_errors_err_socket_already_bound"><code>ERR_SOCKET_ALREADY_BOUND</code></a></li>
<li><a href="#all_errors_err_socket_bad_buffer_size"><code>ERR_SOCKET_BAD_BUFFER_SIZE</code></a></li>
<li><a href="#all_errors_err_socket_bad_port"><code>ERR_SOCKET_BAD_PORT</code></a></li>
<li><a href="#all_errors_err_socket_bad_type"><code>ERR_SOCKET_BAD_TYPE</code></a></li>
<li><a href="#all_errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a></li>
<li><a href="#all_errors_err_socket_closed"><code>ERR_SOCKET_CLOSED</code></a></li>
<li><a href="#all_errors_err_socket_closed_before_connection"><code>ERR_SOCKET_CLOSED_BEFORE_CONNECTION</code></a></li>
<li><a href="#all_errors_err_socket_connection_timeout"><code>ERR_SOCKET_CONNECTION_TIMEOUT</code></a></li>
<li><a href="#all_errors_err_socket_dgram_is_connected"><code>ERR_SOCKET_DGRAM_IS_CONNECTED</code></a></li>
<li><a href="#all_errors_err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a></li>
<li><a href="#all_errors_err_socket_dgram_not_running"><code>ERR_SOCKET_DGRAM_NOT_RUNNING</code></a></li>
<li><a href="#all_errors_err_sri_parse"><code>ERR_SRI_PARSE</code></a></li>
<li><a href="#all_errors_err_stream_already_finished"><code>ERR_STREAM_ALREADY_FINISHED</code></a></li>
<li><a href="#all_errors_err_stream_cannot_pipe"><code>ERR_STREAM_CANNOT_PIPE</code></a></li>
<li><a href="#all_errors_err_stream_destroyed"><code>ERR_STREAM_DESTROYED</code></a></li>
<li><a href="#all_errors_err_stream_null_values"><code>ERR_STREAM_NULL_VALUES</code></a></li>
<li><a href="#all_errors_err_stream_premature_close"><code>ERR_STREAM_PREMATURE_CLOSE</code></a></li>
<li><a href="#all_errors_err_stream_push_after_eof"><code>ERR_STREAM_PUSH_AFTER_EOF</code></a></li>
<li><a href="#all_errors_err_stream_unshift_after_end_event"><code>ERR_STREAM_UNSHIFT_AFTER_END_EVENT</code></a></li>
<li><a href="#all_errors_err_stream_wrap"><code>ERR_STREAM_WRAP</code></a></li>
<li><a href="#all_errors_err_stream_write_after_end"><code>ERR_STREAM_WRITE_AFTER_END</code></a></li>
<li><a href="#all_errors_err_string_too_long"><code>ERR_STRING_TOO_LONG</code></a></li>
<li><a href="#all_errors_err_synthetic"><code>ERR_SYNTHETIC</code></a></li>
<li><a href="#all_errors_err_system_error"><code>ERR_SYSTEM_ERROR</code></a></li>
<li><a href="#all_errors_err_test_failure"><code>ERR_TEST_FAILURE</code></a></li>
<li><a href="#all_errors_err_tls_alpn_callback_invalid_result"><code>ERR_TLS_ALPN_CALLBACK_INVALID_RESULT</code></a></li>
<li><a href="#all_errors_err_tls_alpn_callback_with_protocols"><code>ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS</code></a></li>
<li><a href="#all_errors_err_tls_cert_altname_format"><code>ERR_TLS_CERT_ALTNAME_FORMAT</code></a></li>
<li><a href="#all_errors_err_tls_cert_altname_invalid"><code>ERR_TLS_CERT_ALTNAME_INVALID</code></a></li>
<li><a href="#all_errors_err_tls_dh_param_size"><code>ERR_TLS_DH_PARAM_SIZE</code></a></li>
<li><a href="#all_errors_err_tls_handshake_timeout"><code>ERR_TLS_HANDSHAKE_TIMEOUT</code></a></li>
<li><a href="#all_errors_err_tls_invalid_context"><code>ERR_TLS_INVALID_CONTEXT</code></a></li>
<li><a href="#all_errors_err_tls_invalid_protocol_method"><code>ERR_TLS_INVALID_PROTOCOL_METHOD</code></a></li>
<li><a href="#all_errors_err_tls_invalid_protocol_version"><code>ERR_TLS_INVALID_PROTOCOL_VERSION</code></a></li>
<li><a href="#all_errors_err_tls_invalid_state"><code>ERR_TLS_INVALID_STATE</code></a></li>
<li><a href="#all_errors_err_tls_protocol_version_conflict"><code>ERR_TLS_PROTOCOL_VERSION_CONFLICT</code></a></li>
<li><a href="#all_errors_err_tls_psk_set_identiy_hint_failed"><code>ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED</code></a></li>
<li><a href="#all_errors_err_tls_renegotiation_disabled"><code>ERR_TLS_RENEGOTIATION_DISABLED</code></a></li>
<li><a href="#all_errors_err_tls_required_server_name"><code>ERR_TLS_REQUIRED_SERVER_NAME</code></a></li>
<li><a href="#all_errors_err_tls_session_attack"><code>ERR_TLS_SESSION_ATTACK</code></a></li>
<li><a href="#all_errors_err_tls_sni_from_server"><code>ERR_TLS_SNI_FROM_SERVER</code></a></li>
<li><a href="#all_errors_err_trace_events_category_required"><code>ERR_TRACE_EVENTS_CATEGORY_REQUIRED</code></a></li>
<li><a href="#all_errors_err_trace_events_unavailable"><code>ERR_TRACE_EVENTS_UNAVAILABLE</code></a></li>
<li><a href="#all_errors_err_transform_already_transforming"><code>ERR_TRANSFORM_ALREADY_TRANSFORMING</code></a></li>
<li><a href="#all_errors_err_transform_with_length_0"><code>ERR_TRANSFORM_WITH_LENGTH_0</code></a></li>
<li><a href="#all_errors_err_tty_init_failed"><code>ERR_TTY_INIT_FAILED</code></a></li>
<li><a href="#all_errors_err_unavailable_during_exit"><code>ERR_UNAVAILABLE_DURING_EXIT</code></a></li>
<li><a href="#all_errors_err_uncaught_exception_capture_already_set"><code>ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET</code></a></li>
<li><a href="#all_errors_err_unescaped_characters"><code>ERR_UNESCAPED_CHARACTERS</code></a></li>
<li><a href="#all_errors_err_unhandled_error"><code>ERR_UNHANDLED_ERROR</code></a></li>
<li><a href="#all_errors_err_unknown_builtin_module"><code>ERR_UNKNOWN_BUILTIN_MODULE</code></a></li>
<li><a href="#all_errors_err_unknown_credential"><code>ERR_UNKNOWN_CREDENTIAL</code></a></li>
<li><a href="#all_errors_err_unknown_encoding"><code>ERR_UNKNOWN_ENCODING</code></a></li>
<li><span class="stability_1"><a href="#all_errors_err_unknown_file_extension"><code>ERR_UNKNOWN_FILE_EXTENSION</code></a></span></li>
<li><span class="stability_1"><a href="#all_errors_err_unknown_module_format"><code>ERR_UNKNOWN_MODULE_FORMAT</code></a></span></li>
<li><a href="#all_errors_err_unknown_signal"><code>ERR_UNKNOWN_SIGNAL</code></a></li>
<li><a href="#all_errors_err_unsupported_dir_import"><code>ERR_UNSUPPORTED_DIR_IMPORT</code></a></li>
<li><a href="#all_errors_err_unsupported_esm_url_scheme"><code>ERR_UNSUPPORTED_ESM_URL_SCHEME</code></a></li>
<li><a href="#all_errors_err_unsupported_resolve_request"><code>ERR_UNSUPPORTED_RESOLVE_REQUEST</code></a></li>
<li><span class="stability_1"><a href="#all_errors_err_use_after_close"><code>ERR_USE_AFTER_CLOSE</code></a></span></li>
<li><a href="#all_errors_err_valid_performance_entry_type"><code>ERR_VALID_PERFORMANCE_ENTRY_TYPE</code></a></li>
<li><a href="#all_errors_err_vm_dynamic_import_callback_missing_flag"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code></a></li>
<li><a href="#all_errors_err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a></li>
<li><a href="#all_errors_err_vm_module_already_linked"><code>ERR_VM_MODULE_ALREADY_LINKED</code></a></li>
<li><a href="#all_errors_err_vm_module_cached_data_rejected"><code>ERR_VM_MODULE_CACHED_DATA_REJECTED</code></a></li>
<li><a href="#all_errors_err_vm_module_cannot_create_cached_data"><code>ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA</code></a></li>
<li><a href="#all_errors_err_vm_module_different_context"><code>ERR_VM_MODULE_DIFFERENT_CONTEXT</code></a></li>
<li><a href="#all_errors_err_vm_module_link_failure"><code>ERR_VM_MODULE_LINK_FAILURE</code></a></li>
<li><a href="#all_errors_err_vm_module_not_module"><code>ERR_VM_MODULE_NOT_MODULE</code></a></li>
<li><a href="#all_errors_err_vm_module_status"><code>ERR_VM_MODULE_STATUS</code></a></li>
<li><a href="#all_errors_err_wasi_already_started"><code>ERR_WASI_ALREADY_STARTED</code></a></li>
<li><a href="#all_errors_err_wasi_not_started"><code>ERR_WASI_NOT_STARTED</code></a></li>
<li><a href="#all_errors_err_webassembly_response"><code>ERR_WEBASSEMBLY_RESPONSE</code></a></li>
<li><a href="#all_errors_err_worker_init_failed"><code>ERR_WORKER_INIT_FAILED</code></a></li>
<li><a href="#all_errors_err_worker_invalid_exec_argv"><code>ERR_WORKER_INVALID_EXEC_ARGV</code></a></li>
<li><a href="#all_errors_err_worker_not_running"><code>ERR_WORKER_NOT_RUNNING</code></a></li>
<li><a href="#all_errors_err_worker_out_of_memory"><code>ERR_WORKER_OUT_OF_MEMORY</code></a></li>
<li><a href="#all_errors_err_worker_path"><code>ERR_WORKER_PATH</code></a></li>
<li><span class="stability_1"><a href="#all_errors_err_worker_messaging_errored"><code>ERR_WORKER_MESSAGING_ERRORED</code></a></span></li>
<li><span class="stability_1"><a href="#all_errors_err_worker_messaging_failed"><code>ERR_WORKER_MESSAGING_FAILED</code></a></span></li>
<li><span class="stability_1"><a href="#all_errors_err_worker_messaging_same_thread"><code>ERR_WORKER_MESSAGING_SAME_THREAD</code></a></span></li>
<li><span class="stability_1"><a href="#all_errors_err_worker_messaging_timeout"><code>ERR_WORKER_MESSAGING_TIMEOUT</code></a></span></li>
<li><a href="#all_errors_err_worker_unserializable_error"><code>ERR_WORKER_UNSERIALIZABLE_ERROR</code></a></li>
<li><a href="#all_errors_err_worker_unsupported_operation"><code>ERR_WORKER_UNSUPPORTED_OPERATION</code></a></li>
<li><a href="#all_errors_err_zlib_initialization_failed"><code>ERR_ZLIB_INITIALIZATION_FAILED</code></a></li>
<li><a href="#all_errors_hpe_header_overflow"><code>HPE_HEADER_OVERFLOW</code></a></li>
<li><a href="#all_errors_hpe_chunk_extensions_overflow"><code>HPE_CHUNK_EXTENSIONS_OVERFLOW</code></a></li>
<li><a href="#all_errors_hpe_unexpected_content_length"><code>HPE_UNEXPECTED_CONTENT_LENGTH</code></a></li>
<li><a href="#all_errors_module_not_found"><code>MODULE_NOT_FOUND</code></a></li>
</ul>
</li>
<li><span class="stability_0"><a href="#all_errors_legacy-nodejs-error-codes">Legacy Node.js error codes</a></span>
<ul>
<li><a href="#all_errors_err_cannot_transfer_object"><code>ERR_CANNOT_TRANSFER_OBJECT</code></a></li>
<li><a href="#all_errors_err_crypto_hash_digest_no_utf16"><code>ERR_CRYPTO_HASH_DIGEST_NO_UTF16</code></a></li>
<li><a href="#all_errors_err_http2_frame_error"><code>ERR_HTTP2_FRAME_ERROR</code></a></li>
<li><a href="#all_errors_err_http2_headers_object"><code>ERR_HTTP2_HEADERS_OBJECT</code></a></li>
<li><a href="#all_errors_err_http2_header_required"><code>ERR_HTTP2_HEADER_REQUIRED</code></a></li>
<li><a href="#all_errors_err_http2_info_headers_after_respond"><code>ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND</code></a></li>
<li><a href="#all_errors_err_http2_stream_closed"><code>ERR_HTTP2_STREAM_CLOSED</code></a></li>
<li><a href="#all_errors_err_http_invalid_char"><code>ERR_HTTP_INVALID_CHAR</code></a></li>
<li><a href="#all_errors_err_index_out_of_range"><code>ERR_INDEX_OUT_OF_RANGE</code></a></li>
<li><a href="#all_errors_err_invalid_opt_value"><code>ERR_INVALID_OPT_VALUE</code></a></li>
<li><a href="#all_errors_err_invalid_opt_value_encoding"><code>ERR_INVALID_OPT_VALUE_ENCODING</code></a></li>
<li><a href="#all_errors_err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a></li>
<li><a href="#all_errors_err_napi_cons_prototype_object"><code>ERR_NAPI_CONS_PROTOTYPE_OBJECT</code></a></li>
<li><span class="stability_1"><a href="#all_errors_err_network_import_bad_response"><code>ERR_NETWORK_IMPORT_BAD_RESPONSE</code></a></span></li>
<li><span class="stability_1"><a href="#all_errors_err_network_import_disallowed"><code>ERR_NETWORK_IMPORT_DISALLOWED</code></a></span></li>
<li><a href="#all_errors_err_no_longer_supported"><code>ERR_NO_LONGER_SUPPORTED</code></a></li>
<li><a href="#all_errors_err_operation_failed"><code>ERR_OPERATION_FAILED</code></a></li>
<li><a href="#all_errors_err_outofmemory"><code>ERR_OUTOFMEMORY</code></a></li>
<li><a href="#all_errors_err_parse_history_data"><code>ERR_PARSE_HISTORY_DATA</code></a></li>
<li><a href="#all_errors_err_socket_cannot_send"><code>ERR_SOCKET_CANNOT_SEND</code></a></li>
<li><a href="#all_errors_err_stderr_close"><code>ERR_STDERR_CLOSE</code></a></li>
<li><a href="#all_errors_err_stdout_close"><code>ERR_STDOUT_CLOSE</code></a></li>
<li><a href="#all_errors_err_stream_read_not_implemented"><code>ERR_STREAM_READ_NOT_IMPLEMENTED</code></a></li>
<li><a href="#all_errors_err_tap_lexer_error"><code>ERR_TAP_LEXER_ERROR</code></a></li>
<li><a href="#all_errors_err_tap_parser_error"><code>ERR_TAP_PARSER_ERROR</code></a></li>
<li><a href="#all_errors_err_tap_validation_error"><code>ERR_TAP_VALIDATION_ERROR</code></a></li>
<li><a href="#all_errors_err_tls_renegotiation_failed"><code>ERR_TLS_RENEGOTIATION_FAILED</code></a></li>
<li><a href="#all_errors_err_transferring_externalized_sharedarraybuffer"><code>ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER</code></a></li>
<li><a href="#all_errors_err_unknown_stdin_type"><code>ERR_UNKNOWN_STDIN_TYPE</code></a></li>
<li><a href="#all_errors_err_unknown_stream_type"><code>ERR_UNKNOWN_STREAM_TYPE</code></a></li>
<li><a href="#all_errors_err_v8breakiterator"><code>ERR_V8BREAKITERATOR</code></a></li>
<li><a href="#all_errors_err_value_out_of_range"><code>ERR_VALUE_OUT_OF_RANGE</code></a></li>
<li><a href="#all_errors_err_vm_module_not_linked"><code>ERR_VM_MODULE_NOT_LINKED</code></a></li>
<li><a href="#all_errors_err_vm_module_linking_errored"><code>ERR_VM_MODULE_LINKING_ERRORED</code></a></li>
<li><a href="#all_errors_err_worker_unsupported_extension"><code>ERR_WORKER_UNSUPPORTED_EXTENSION</code></a></li>
<li><a href="#all_errors_err_zlib_binding_closed"><code>ERR_ZLIB_BINDING_CLOSED</code></a></li>
<li><a href="#all_errors_err_cpu_usage"><code>ERR_CPU_USAGE</code></a></li>
</ul>
</li>
<li><a href="#all_errors_openssl-error-codes">OpenSSL Error Codes</a>
<ul>
<li><a href="#all_errors_time-validity-errors">Time Validity Errors</a>
<ul>
<li><a href="#all_errors_cert_not_yet_valid"><code>CERT_NOT_YET_VALID</code></a></li>
<li><a href="#all_errors_cert_has_expired"><code>CERT_HAS_EXPIRED</code></a></li>
<li><a href="#all_errors_crl_not_yet_valid"><code>CRL_NOT_YET_VALID</code></a></li>
<li><a href="#all_errors_crl_has_expired"><code>CRL_HAS_EXPIRED</code></a></li>
<li><a href="#all_errors_cert_revoked"><code>CERT_REVOKED</code></a></li>
</ul>
</li>
<li><a href="#all_errors_trust-or-chain-related-errors">Trust or Chain Related Errors</a>
<ul>
<li><a href="#all_errors_unable_to_get_issuer_cert"><code>UNABLE_TO_GET_ISSUER_CERT</code></a></li>
<li><a href="#all_errors_unable_to_get_issuer_cert_locally"><code>UNABLE_TO_GET_ISSUER_CERT_LOCALLY</code></a></li>
<li><a href="#all_errors_depth_zero_self_signed_cert"><code>DEPTH_ZERO_SELF_SIGNED_CERT</code></a></li>
<li><a href="#all_errors_self_signed_cert_in_chain"><code>SELF_SIGNED_CERT_IN_CHAIN</code></a></li>
<li><a href="#all_errors_cert_chain_too_long"><code>CERT_CHAIN_TOO_LONG</code></a></li>
<li><a href="#all_errors_unable_to_get_crl"><code>UNABLE_TO_GET_CRL</code></a></li>
<li><a href="#all_errors_unable_to_verify_leaf_signature"><code>UNABLE_TO_VERIFY_LEAF_SIGNATURE</code></a></li>
<li><a href="#all_errors_cert_untrusted"><code>CERT_UNTRUSTED</code></a></li>
</ul>
</li>
<li><a href="#all_errors_basic-extension-errors">Basic Extension Errors</a>
<ul>
<li><a href="#all_errors_invalid_ca"><code>INVALID_CA</code></a></li>
<li><a href="#all_errors_path_length_exceeded"><code>PATH_LENGTH_EXCEEDED</code></a></li>
</ul>
</li>
<li><a href="#all_errors_name-related-errors">Name Related Errors</a>
<ul>
<li><a href="#all_errors_hostname_mismatch"><code>HOSTNAME_MISMATCH</code></a></li>
</ul>
</li>
<li><a href="#all_errors_usage-and-policy-errors">Usage and Policy Errors</a>
<ul>
<li><a href="#all_errors_invalid_purpose"><code>INVALID_PURPOSE</code></a></li>
<li><a href="#all_errors_cert_rejected"><code>CERT_REJECTED</code></a></li>
</ul>
</li>
<li><a href="#all_errors_formatting-errors">Formatting Errors</a>
<ul>
<li><a href="#all_errors_cert_signature_failure"><code>CERT_SIGNATURE_FAILURE</code></a></li>
<li><a href="#all_errors_crl_signature_failure"><code>CRL_SIGNATURE_FAILURE</code></a></li>
<li><a href="#all_errors_error_in_cert_not_before_field"><code>ERROR_IN_CERT_NOT_BEFORE_FIELD</code></a></li>
<li><a href="#all_errors_error_in_cert_not_after_field"><code>ERROR_IN_CERT_NOT_AFTER_FIELD</code></a></li>
<li><a href="#all_errors_error_in_crl_last_update_field"><code>ERROR_IN_CRL_LAST_UPDATE_FIELD</code></a></li>
<li><a href="#all_errors_error_in_crl_next_update_field"><code>ERROR_IN_CRL_NEXT_UPDATE_FIELD</code></a></li>
<li><a href="#all_errors_unable_to_decrypt_cert_signature"><code>UNABLE_TO_DECRYPT_CERT_SIGNATURE</code></a></li>
<li><a href="#all_errors_unable_to_decrypt_crl_signature"><code>UNABLE_TO_DECRYPT_CRL_SIGNATURE</code></a></li>
<li><a href="#all_errors_unable_to_decode_issuer_public_key"><code>UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY</code></a></li>
</ul>
</li>
<li><a href="#all_errors_other-openssl-errors">Other OpenSSL Errors</a>
<ul>
<li><a href="#all_errors_out_of_mem"><code>OUT_OF_MEM</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_events_events">Events</a></span>
<ul>
<li><a href="#all_events_passing-arguments-and-this-to-listeners">Passing arguments and <code>this</code> to listeners</a></li>
<li><a href="#all_events_asynchronous-vs-synchronous">Asynchronous vs. synchronous</a></li>
<li><a href="#all_events_handling-events-only-once">Handling events only once</a></li>
<li><a href="#all_events_error-events">Error events</a></li>
<li><a href="#all_events_capture-rejections-of-promises">Capture rejections of promises</a></li>
<li><a href="#all_events_class-eventemitter">Class: <code>EventEmitter</code></a>
<ul>
<li><a href="#all_events_event-newlistener">Event: <code>'newListener'</code></a></li>
<li><a href="#all_events_event-removelistener">Event: <code>'removeListener'</code></a></li>
<li><a href="#all_events_emitteraddlistenereventname-listener"><code>emitter.addListener(eventName, listener)</code></a></li>
<li><a href="#all_events_emitteremiteventname-args"><code>emitter.emit(eventName[, ...args])</code></a></li>
<li><a href="#all_events_emittereventnames"><code>emitter.eventNames()</code></a></li>
<li><a href="#all_events_emittergetmaxlisteners"><code>emitter.getMaxListeners()</code></a></li>
<li><a href="#all_events_emitterlistenercounteventname-listener"><code>emitter.listenerCount(eventName[, listener])</code></a></li>
<li><a href="#all_events_emitterlistenerseventname"><code>emitter.listeners(eventName)</code></a></li>
<li><a href="#all_events_emitteroffeventname-listener"><code>emitter.off(eventName, listener)</code></a></li>
<li><a href="#all_events_emitteroneventname-listener"><code>emitter.on(eventName, listener)</code></a></li>
<li><a href="#all_events_emitteronceeventname-listener"><code>emitter.once(eventName, listener)</code></a></li>
<li><a href="#all_events_emitterprependlistenereventname-listener"><code>emitter.prependListener(eventName, listener)</code></a></li>
<li><a href="#all_events_emitterprependoncelistenereventname-listener"><code>emitter.prependOnceListener(eventName, listener)</code></a></li>
<li><a href="#all_events_emitterremovealllistenerseventname"><code>emitter.removeAllListeners([eventName])</code></a></li>
<li><a href="#all_events_emitterremovelistenereventname-listener"><code>emitter.removeListener(eventName, listener)</code></a></li>
<li><a href="#all_events_emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a></li>
<li><a href="#all_events_emitterrawlistenerseventname"><code>emitter.rawListeners(eventName)</code></a></li>
<li><a href="#all_events_emittersymbolfornodejsrejectionerr-eventname-args"><code>emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])</code></a></li>
</ul>
</li>
<li><a href="#all_events_eventsdefaultmaxlisteners"><code>events.defaultMaxListeners</code></a></li>
<li><a href="#all_events_eventserrormonitor"><code>events.errorMonitor</code></a></li>
<li><a href="#all_events_eventsgeteventlistenersemitterortarget-eventname"><code>events.getEventListeners(emitterOrTarget, eventName)</code></a></li>
<li><a href="#all_events_eventsgetmaxlistenersemitterortarget"><code>events.getMaxListeners(emitterOrTarget)</code></a></li>
<li><a href="#all_events_eventsonceemitter-name-options"><code>events.once(emitter, name[, options])</code></a>
<ul>
<li><a href="#all_events_awaiting-multiple-events-emitted-on-processnexttick">Awaiting multiple events emitted on <code>process.nextTick()</code></a></li>
</ul>
</li>
<li><a href="#all_events_eventscapturerejections"><code>events.captureRejections</code></a></li>
<li><a href="#all_events_eventscapturerejectionsymbol"><code>events.captureRejectionSymbol</code></a></li>
<li><span class="stability_0"><a href="#all_events_eventslistenercountemitter-eventname"><code>events.listenerCount(emitter, eventName)</code></a></span></li>
<li><a href="#all_events_eventsonemitter-eventname-options"><code>events.on(emitter, eventName[, options])</code></a></li>
<li><a href="#all_events_eventssetmaxlistenersn-eventtargets"><code>events.setMaxListeners(n[, ...eventTargets])</code></a></li>
<li><span class="stability_1"><a href="#all_events_eventsaddabortlistenersignal-listener"><code>events.addAbortListener(signal, listener)</code></a></span></li>
<li><a href="#all_events_class-eventseventemitterasyncresource-extends-eventemitter">Class: <code>events.EventEmitterAsyncResource extends EventEmitter</code></a>
<ul>
<li><a href="#all_events_new-eventseventemitterasyncresourceoptions"><code>new events.EventEmitterAsyncResource([options])</code></a></li>
<li><a href="#all_events_eventemitterasyncresourceasyncid"><code>eventemitterasyncresource.asyncId</code></a></li>
<li><a href="#all_events_eventemitterasyncresourceasyncresource"><code>eventemitterasyncresource.asyncResource</code></a></li>
<li><a href="#all_events_eventemitterasyncresourceemitdestroy"><code>eventemitterasyncresource.emitDestroy()</code></a></li>
<li><a href="#all_events_eventemitterasyncresourcetriggerasyncid"><code>eventemitterasyncresource.triggerAsyncId</code></a></li>
</ul>
</li>
<li><a href="#all_events_eventtarget-and-event-api"><code>EventTarget</code> and <code>Event</code> API</a>
<ul>
<li><a href="#all_events_nodejs-eventtarget-vs-dom-eventtarget">Node.js <code>EventTarget</code> vs. DOM <code>EventTarget</code></a></li>
<li><a href="#all_events_nodeeventtarget-vs-eventemitter"><code>NodeEventTarget</code> vs. <code>EventEmitter</code></a></li>
<li><a href="#all_events_event-listener">Event listener</a></li>
<li><a href="#all_events_eventtarget-error-handling"><code>EventTarget</code> error handling</a></li>
<li><a href="#all_events_class-event">Class: <code>Event</code></a>
<ul>
<li><a href="#all_events_eventbubbles"><code>event.bubbles</code></a></li>
<li><span class="stability_3"><a href="#all_events_eventcancelbubble"><code>event.cancelBubble</code></a></span></li>
<li><a href="#all_events_eventcancelable"><code>event.cancelable</code></a></li>
<li><a href="#all_events_eventcomposed"><code>event.composed</code></a></li>
<li><a href="#all_events_eventcomposedpath"><code>event.composedPath()</code></a></li>
<li><a href="#all_events_eventcurrenttarget"><code>event.currentTarget</code></a></li>
<li><a href="#all_events_eventdefaultprevented"><code>event.defaultPrevented</code></a></li>
<li><a href="#all_events_eventeventphase"><code>event.eventPhase</code></a></li>
<li><span class="stability_3"><a href="#all_events_eventiniteventtype-bubbles-cancelable"><code>event.initEvent(type[, bubbles[, cancelable]])</code></a></span></li>
<li><a href="#all_events_eventistrusted"><code>event.isTrusted</code></a></li>
<li><a href="#all_events_eventpreventdefault"><code>event.preventDefault()</code></a></li>
<li><span class="stability_3"><a href="#all_events_eventreturnvalue"><code>event.returnValue</code></a></span></li>
<li><span class="stability_3"><a href="#all_events_eventsrcelement"><code>event.srcElement</code></a></span></li>
<li><a href="#all_events_eventstopimmediatepropagation"><code>event.stopImmediatePropagation()</code></a></li>
<li><a href="#all_events_eventstoppropagation"><code>event.stopPropagation()</code></a></li>
<li><a href="#all_events_eventtarget"><code>event.target</code></a></li>
<li><a href="#all_events_eventtimestamp"><code>event.timeStamp</code></a></li>
<li><a href="#all_events_eventtype"><code>event.type</code></a></li>
</ul>
</li>
<li><a href="#all_events_class-eventtarget">Class: <code>EventTarget</code></a>
<ul>
<li><a href="#all_events_eventtargetaddeventlistenertype-listener-options"><code>eventTarget.addEventListener(type, listener[, options])</code></a></li>
<li><a href="#all_events_eventtargetdispatcheventevent"><code>eventTarget.dispatchEvent(event)</code></a></li>
<li><a href="#all_events_eventtargetremoveeventlistenertype-listener-options"><code>eventTarget.removeEventListener(type, listener[, options])</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_events_class-customevent">Class: <code>CustomEvent</code></a></span>
<ul>
<li><span class="stability_2"><a href="#all_events_eventdetail"><code>event.detail</code></a></span></li>
</ul>
</li>
<li><a href="#all_events_class-nodeeventtarget">Class: <code>NodeEventTarget</code></a>
<ul>
<li><a href="#all_events_nodeeventtargetaddlistenertype-listener"><code>nodeEventTarget.addListener(type, listener)</code></a></li>
<li><a href="#all_events_nodeeventtargetemittype-arg"><code>nodeEventTarget.emit(type, arg)</code></a></li>
<li><a href="#all_events_nodeeventtargeteventnames"><code>nodeEventTarget.eventNames()</code></a></li>
<li><a href="#all_events_nodeeventtargetlistenercounttype"><code>nodeEventTarget.listenerCount(type)</code></a></li>
<li><a href="#all_events_nodeeventtargetsetmaxlistenersn"><code>nodeEventTarget.setMaxListeners(n)</code></a></li>
<li><a href="#all_events_nodeeventtargetgetmaxlisteners"><code>nodeEventTarget.getMaxListeners()</code></a></li>
<li><a href="#all_events_nodeeventtargetofftype-listener-options"><code>nodeEventTarget.off(type, listener[, options])</code></a></li>
<li><a href="#all_events_nodeeventtargetontype-listener"><code>nodeEventTarget.on(type, listener)</code></a></li>
<li><a href="#all_events_nodeeventtargetoncetype-listener"><code>nodeEventTarget.once(type, listener)</code></a></li>
<li><a href="#all_events_nodeeventtargetremovealllistenerstype"><code>nodeEventTarget.removeAllListeners([type])</code></a></li>
<li><a href="#all_events_nodeeventtargetremovelistenertype-listener-options"><code>nodeEventTarget.removeListener(type, listener[, options])</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_fs_file-system">File system</a></span>
<ul>
<li><a href="#all_fs_promise-example">Promise example</a></li>
<li><a href="#all_fs_callback-example">Callback example</a></li>
<li><a href="#all_fs_synchronous-example">Synchronous example</a></li>
<li><a href="#all_fs_promises-api">Promises API</a>
<ul>
<li><a href="#all_fs_class-filehandle">Class: <code>FileHandle</code></a>
<ul>
<li><a href="#all_fs_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_fs_filehandleappendfiledata-options"><code>filehandle.appendFile(data[, options])</code></a></li>
<li><a href="#all_fs_filehandlechmodmode"><code>filehandle.chmod(mode)</code></a></li>
<li><a href="#all_fs_filehandlechownuid-gid"><code>filehandle.chown(uid, gid)</code></a></li>
<li><a href="#all_fs_filehandleclose"><code>filehandle.close()</code></a></li>
<li><a href="#all_fs_filehandlecreatereadstreamoptions"><code>filehandle.createReadStream([options])</code></a></li>
<li><a href="#all_fs_filehandlecreatewritestreamoptions"><code>filehandle.createWriteStream([options])</code></a></li>
<li><a href="#all_fs_filehandledatasync"><code>filehandle.datasync()</code></a></li>
<li><a href="#all_fs_filehandlefd"><code>filehandle.fd</code></a></li>
<li><a href="#all_fs_filehandlereadbuffer-offset-length-position"><code>filehandle.read(buffer, offset, length, position)</code></a></li>
<li><a href="#all_fs_filehandlereadoptions"><code>filehandle.read([options])</code></a></li>
<li><a href="#all_fs_filehandlereadbuffer-options"><code>filehandle.read(buffer[, options])</code></a></li>
<li><span class="stability_1"><a href="#all_fs_filehandlereadablewebstreamoptions"><code>filehandle.readableWebStream([options])</code></a></span></li>
<li><a href="#all_fs_filehandlereadfileoptions"><code>filehandle.readFile(options)</code></a></li>
<li><a href="#all_fs_filehandlereadlinesoptions"><code>filehandle.readLines([options])</code></a></li>
<li><a href="#all_fs_filehandlereadvbuffers-position"><code>filehandle.readv(buffers[, position])</code></a></li>
<li><a href="#all_fs_filehandlestatoptions"><code>filehandle.stat([options])</code></a></li>
<li><a href="#all_fs_filehandlesync"><code>filehandle.sync()</code></a></li>
<li><a href="#all_fs_filehandletruncatelen"><code>filehandle.truncate(len)</code></a></li>
<li><a href="#all_fs_filehandleutimesatime-mtime"><code>filehandle.utimes(atime, mtime)</code></a></li>
<li><a href="#all_fs_filehandlewritebuffer-offset-length-position"><code>filehandle.write(buffer, offset[, length[, position]])</code></a></li>
<li><a href="#all_fs_filehandlewritebuffer-options"><code>filehandle.write(buffer[, options])</code></a></li>
<li><a href="#all_fs_filehandlewritestring-position-encoding"><code>filehandle.write(string[, position[, encoding]])</code></a></li>
<li><a href="#all_fs_filehandlewritefiledata-options"><code>filehandle.writeFile(data, options)</code></a></li>
<li><a href="#all_fs_filehandlewritevbuffers-position"><code>filehandle.writev(buffers[, position])</code></a></li>
<li><span class="stability_1"><a href="#all_fs_filehandlesymbolasyncdispose"><code>filehandle[Symbol.asyncDispose]()</code></a></span></li>
</ul>
</li>
<li><a href="#all_fs_fspromisesaccesspath-mode"><code>fsPromises.access(path[, mode])</code></a></li>
<li><a href="#all_fs_fspromisesappendfilepath-data-options"><code>fsPromises.appendFile(path, data[, options])</code></a></li>
<li><a href="#all_fs_fspromiseschmodpath-mode"><code>fsPromises.chmod(path, mode)</code></a></li>
<li><a href="#all_fs_fspromiseschownpath-uid-gid"><code>fsPromises.chown(path, uid, gid)</code></a></li>
<li><a href="#all_fs_fspromisescopyfilesrc-dest-mode"><code>fsPromises.copyFile(src, dest[, mode])</code></a></li>
<li><span class="stability_1"><a href="#all_fs_fspromisescpsrc-dest-options"><code>fsPromises.cp(src, dest[, options])</code></a></span></li>
<li><a href="#all_fs_fspromiseslchmodpath-mode"><code>fsPromises.lchmod(path, mode)</code></a></li>
<li><a href="#all_fs_fspromiseslchownpath-uid-gid"><code>fsPromises.lchown(path, uid, gid)</code></a></li>
<li><a href="#all_fs_fspromiseslutimespath-atime-mtime"><code>fsPromises.lutimes(path, atime, mtime)</code></a></li>
<li><a href="#all_fs_fspromiseslinkexistingpath-newpath"><code>fsPromises.link(existingPath, newPath)</code></a></li>
<li><a href="#all_fs_fspromiseslstatpath-options"><code>fsPromises.lstat(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesmkdirpath-options"><code>fsPromises.mkdir(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesmkdtempprefix-options"><code>fsPromises.mkdtemp(prefix[, options])</code></a></li>
<li><a href="#all_fs_fspromisesopenpath-flags-mode"><code>fsPromises.open(path, flags[, mode])</code></a></li>
<li><a href="#all_fs_fspromisesopendirpath-options"><code>fsPromises.opendir(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesreaddirpath-options"><code>fsPromises.readdir(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesreadfilepath-options"><code>fsPromises.readFile(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesreadlinkpath-options"><code>fsPromises.readlink(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesrealpathpath-options"><code>fsPromises.realpath(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesrenameoldpath-newpath"><code>fsPromises.rename(oldPath, newPath)</code></a></li>
<li><a href="#all_fs_fspromisesrmdirpath-options"><code>fsPromises.rmdir(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesrmpath-options"><code>fsPromises.rm(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesstatpath-options"><code>fsPromises.stat(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesstatfspath-options"><code>fsPromises.statfs(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisessymlinktarget-path-type"><code>fsPromises.symlink(target, path[, type])</code></a></li>
<li><a href="#all_fs_fspromisestruncatepath-len"><code>fsPromises.truncate(path[, len])</code></a></li>
<li><a href="#all_fs_fspromisesunlinkpath"><code>fsPromises.unlink(path)</code></a></li>
<li><a href="#all_fs_fspromisesutimespath-atime-mtime"><code>fsPromises.utimes(path, atime, mtime)</code></a></li>
<li><a href="#all_fs_fspromiseswatchfilename-options"><code>fsPromises.watch(filename[, options])</code></a></li>
<li><a href="#all_fs_fspromiseswritefilefile-data-options"><code>fsPromises.writeFile(file, data[, options])</code></a></li>
<li><a href="#all_fs_fspromisesconstants"><code>fsPromises.constants</code></a></li>
</ul>
</li>
<li><a href="#all_fs_callback-api">Callback API</a>
<ul>
<li><a href="#all_fs_fsaccesspath-mode-callback"><code>fs.access(path[, mode], callback)</code></a></li>
<li><a href="#all_fs_fsappendfilepath-data-options-callback"><code>fs.appendFile(path, data[, options], callback)</code></a></li>
<li><a href="#all_fs_fschmodpath-mode-callback"><code>fs.chmod(path, mode, callback)</code></a>
<ul>
<li><a href="#all_fs_file-modes">File modes</a></li>
</ul>
</li>
<li><a href="#all_fs_fschownpath-uid-gid-callback"><code>fs.chown(path, uid, gid, callback)</code></a></li>
<li><a href="#all_fs_fsclosefd-callback"><code>fs.close(fd[, callback])</code></a></li>
<li><a href="#all_fs_fscopyfilesrc-dest-mode-callback"><code>fs.copyFile(src, dest[, mode], callback)</code></a></li>
<li><span class="stability_1"><a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp(src, dest[, options], callback)</code></a></span></li>
<li><a href="#all_fs_fscreatereadstreampath-options"><code>fs.createReadStream(path[, options])</code></a></li>
<li><a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream(path[, options])</code></a></li>
<li><span class="stability_0"><a href="#all_fs_fsexistspath-callback"><code>fs.exists(path, callback)</code></a></span></li>
<li><a href="#all_fs_fsfchmodfd-mode-callback"><code>fs.fchmod(fd, mode, callback)</code></a></li>
<li><a href="#all_fs_fsfchownfd-uid-gid-callback"><code>fs.fchown(fd, uid, gid, callback)</code></a></li>
<li><a href="#all_fs_fsfdatasyncfd-callback"><code>fs.fdatasync(fd, callback)</code></a></li>
<li><a href="#all_fs_fsfstatfd-options-callback"><code>fs.fstat(fd[, options], callback)</code></a></li>
<li><a href="#all_fs_fsfsyncfd-callback"><code>fs.fsync(fd, callback)</code></a></li>
<li><a href="#all_fs_fsftruncatefd-len-callback"><code>fs.ftruncate(fd[, len], callback)</code></a></li>
<li><a href="#all_fs_fsfutimesfd-atime-mtime-callback"><code>fs.futimes(fd, atime, mtime, callback)</code></a></li>
<li><a href="#all_fs_fslchmodpath-mode-callback"><code>fs.lchmod(path, mode, callback)</code></a></li>
<li><a href="#all_fs_fslchownpath-uid-gid-callback"><code>fs.lchown(path, uid, gid, callback)</code></a></li>
<li><a href="#all_fs_fslutimespath-atime-mtime-callback"><code>fs.lutimes(path, atime, mtime, callback)</code></a></li>
<li><a href="#all_fs_fslinkexistingpath-newpath-callback"><code>fs.link(existingPath, newPath, callback)</code></a></li>
<li><a href="#all_fs_fslstatpath-options-callback"><code>fs.lstat(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsmkdirpath-options-callback"><code>fs.mkdir(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsmkdtempprefix-options-callback"><code>fs.mkdtemp(prefix[, options], callback)</code></a></li>
<li><a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open(path[, flags[, mode]], callback)</code></a></li>
<li><span class="stability_1"><a href="#all_fs_fsopenasblobpath-options"><code>fs.openAsBlob(path[, options])</code></a></span></li>
<li><a href="#all_fs_fsopendirpath-options-callback"><code>fs.opendir(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsreadfd-buffer-offset-length-position-callback"><code>fs.read(fd, buffer, offset, length, position, callback)</code></a></li>
<li><a href="#all_fs_fsreadfd-options-callback"><code>fs.read(fd[, options], callback)</code></a></li>
<li><a href="#all_fs_fsreadfd-buffer-options-callback"><code>fs.read(fd, buffer[, options], callback)</code></a></li>
<li><a href="#all_fs_fsreaddirpath-options-callback"><code>fs.readdir(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsreadfilepath-options-callback"><code>fs.readFile(path[, options], callback)</code></a>
<ul>
<li><a href="#all_fs_file-descriptors">File descriptors</a></li>
<li><a href="#all_fs_performance-considerations">Performance Considerations</a></li>
</ul>
</li>
<li><a href="#all_fs_fsreadlinkpath-options-callback"><code>fs.readlink(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsreadvfd-buffers-position-callback"><code>fs.readv(fd, buffers[, position], callback)</code></a></li>
<li><a href="#all_fs_fsrealpathpath-options-callback"><code>fs.realpath(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsrealpathnativepath-options-callback"><code>fs.realpath.native(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsrenameoldpath-newpath-callback"><code>fs.rename(oldPath, newPath, callback)</code></a></li>
<li><a href="#all_fs_fsrmdirpath-options-callback"><code>fs.rmdir(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsrmpath-options-callback"><code>fs.rm(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsstatpath-options-callback"><code>fs.stat(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsstatfspath-options-callback"><code>fs.statfs(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fssymlinktarget-path-type-callback"><code>fs.symlink(target, path[, type], callback)</code></a></li>
<li><a href="#all_fs_fstruncatepath-len-callback"><code>fs.truncate(path[, len], callback)</code></a></li>
<li><a href="#all_fs_fsunlinkpath-callback"><code>fs.unlink(path, callback)</code></a></li>
<li><a href="#all_fs_fsunwatchfilefilename-listener"><code>fs.unwatchFile(filename[, listener])</code></a></li>
<li><a href="#all_fs_fsutimespath-atime-mtime-callback"><code>fs.utimes(path, atime, mtime, callback)</code></a></li>
<li><a href="#all_fs_fswatchfilename-options-listener"><code>fs.watch(filename[, options][, listener])</code></a>
<ul>
<li><a href="#all_fs_caveats">Caveats</a>
<ul>
<li><a href="#all_fs_availability">Availability</a></li>
<li><a href="#all_fs_inodes">Inodes</a></li>
<li><a href="#all_fs_filename-argument">Filename argument</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_fs_fswatchfilefilename-options-listener"><code>fs.watchFile(filename[, options], listener)</code></a></li>
<li><a href="#all_fs_fswritefd-buffer-offset-length-position-callback"><code>fs.write(fd, buffer, offset[, length[, position]], callback)</code></a></li>
<li><a href="#all_fs_fswritefd-buffer-options-callback"><code>fs.write(fd, buffer[, options], callback)</code></a></li>
<li><a href="#all_fs_fswritefd-string-position-encoding-callback"><code>fs.write(fd, string[, position[, encoding]], callback)</code></a></li>
<li><a href="#all_fs_fswritefilefile-data-options-callback"><code>fs.writeFile(file, data[, options], callback)</code></a>
<ul>
<li><a href="#all_fs_using-fswritefile-with-file-descriptors">Using <code>fs.writeFile()</code> with file descriptors</a></li>
</ul>
</li>
<li><a href="#all_fs_fswritevfd-buffers-position-callback"><code>fs.writev(fd, buffers[, position], callback)</code></a></li>
</ul>
</li>
<li><a href="#all_fs_synchronous-api">Synchronous API</a>
<ul>
<li><a href="#all_fs_fsaccesssyncpath-mode"><code>fs.accessSync(path[, mode])</code></a></li>
<li><a href="#all_fs_fsappendfilesyncpath-data-options"><code>fs.appendFileSync(path, data[, options])</code></a></li>
<li><a href="#all_fs_fschmodsyncpath-mode"><code>fs.chmodSync(path, mode)</code></a></li>
<li><a href="#all_fs_fschownsyncpath-uid-gid"><code>fs.chownSync(path, uid, gid)</code></a></li>
<li><a href="#all_fs_fsclosesyncfd"><code>fs.closeSync(fd)</code></a></li>
<li><a href="#all_fs_fscopyfilesyncsrc-dest-mode"><code>fs.copyFileSync(src, dest[, mode])</code></a></li>
<li><span class="stability_1"><a href="#all_fs_fscpsyncsrc-dest-options"><code>fs.cpSync(src, dest[, options])</code></a></span></li>
<li><a href="#all_fs_fsexistssyncpath"><code>fs.existsSync(path)</code></a></li>
<li><a href="#all_fs_fsfchmodsyncfd-mode"><code>fs.fchmodSync(fd, mode)</code></a></li>
<li><a href="#all_fs_fsfchownsyncfd-uid-gid"><code>fs.fchownSync(fd, uid, gid)</code></a></li>
<li><a href="#all_fs_fsfdatasyncsyncfd"><code>fs.fdatasyncSync(fd)</code></a></li>
<li><a href="#all_fs_fsfstatsyncfd-options"><code>fs.fstatSync(fd[, options])</code></a></li>
<li><a href="#all_fs_fsfsyncsyncfd"><code>fs.fsyncSync(fd)</code></a></li>
<li><a href="#all_fs_fsftruncatesyncfd-len"><code>fs.ftruncateSync(fd[, len])</code></a></li>
<li><a href="#all_fs_fsfutimessyncfd-atime-mtime"><code>fs.futimesSync(fd, atime, mtime)</code></a></li>
<li><a href="#all_fs_fslchmodsyncpath-mode"><code>fs.lchmodSync(path, mode)</code></a></li>
<li><a href="#all_fs_fslchownsyncpath-uid-gid"><code>fs.lchownSync(path, uid, gid)</code></a></li>
<li><a href="#all_fs_fslutimessyncpath-atime-mtime"><code>fs.lutimesSync(path, atime, mtime)</code></a></li>
<li><a href="#all_fs_fslinksyncexistingpath-newpath"><code>fs.linkSync(existingPath, newPath)</code></a></li>
<li><a href="#all_fs_fslstatsyncpath-options"><code>fs.lstatSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsmkdirsyncpath-options"><code>fs.mkdirSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsmkdtempsyncprefix-options"><code>fs.mkdtempSync(prefix[, options])</code></a></li>
<li><a href="#all_fs_fsopendirsyncpath-options"><code>fs.opendirSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsopensyncpath-flags-mode"><code>fs.openSync(path[, flags[, mode]])</code></a></li>
<li><a href="#all_fs_fsreaddirsyncpath-options"><code>fs.readdirSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsreadfilesyncpath-options"><code>fs.readFileSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsreadlinksyncpath-options"><code>fs.readlinkSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsreadsyncfd-buffer-offset-length-position"><code>fs.readSync(fd, buffer, offset, length[, position])</code></a></li>
<li><a href="#all_fs_fsreadsyncfd-buffer-options"><code>fs.readSync(fd, buffer[, options])</code></a></li>
<li><a href="#all_fs_fsreadvsyncfd-buffers-position"><code>fs.readvSync(fd, buffers[, position])</code></a></li>
<li><a href="#all_fs_fsrealpathsyncpath-options"><code>fs.realpathSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsrealpathsyncnativepath-options"><code>fs.realpathSync.native(path[, options])</code></a></li>
<li><a href="#all_fs_fsrenamesyncoldpath-newpath"><code>fs.renameSync(oldPath, newPath)</code></a></li>
<li><a href="#all_fs_fsrmdirsyncpath-options"><code>fs.rmdirSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsrmsyncpath-options"><code>fs.rmSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsstatsyncpath-options"><code>fs.statSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsstatfssyncpath-options"><code>fs.statfsSync(path[, options])</code></a></li>
<li><a href="#all_fs_fssymlinksynctarget-path-type"><code>fs.symlinkSync(target, path[, type])</code></a></li>
<li><a href="#all_fs_fstruncatesyncpath-len"><code>fs.truncateSync(path[, len])</code></a></li>
<li><a href="#all_fs_fsunlinksyncpath"><code>fs.unlinkSync(path)</code></a></li>
<li><a href="#all_fs_fsutimessyncpath-atime-mtime"><code>fs.utimesSync(path, atime, mtime)</code></a></li>
<li><a href="#all_fs_fswritefilesyncfile-data-options"><code>fs.writeFileSync(file, data[, options])</code></a></li>
<li><a href="#all_fs_fswritesyncfd-buffer-offset-length-position"><code>fs.writeSync(fd, buffer, offset[, length[, position]])</code></a></li>
<li><a href="#all_fs_fswritesyncfd-buffer-options"><code>fs.writeSync(fd, buffer[, options])</code></a></li>
<li><a href="#all_fs_fswritesyncfd-string-position-encoding"><code>fs.writeSync(fd, string[, position[, encoding]])</code></a></li>
<li><a href="#all_fs_fswritevsyncfd-buffers-position"><code>fs.writevSync(fd, buffers[, position])</code></a></li>
</ul>
</li>
<li><a href="#all_fs_common-objects">Common Objects</a>
<ul>
<li><a href="#all_fs_class-fsdir">Class: <code>fs.Dir</code></a>
<ul>
<li><a href="#all_fs_dirclose"><code>dir.close()</code></a></li>
<li><a href="#all_fs_dirclosecallback"><code>dir.close(callback)</code></a></li>
<li><a href="#all_fs_dirclosesync"><code>dir.closeSync()</code></a></li>
<li><a href="#all_fs_dirpath"><code>dir.path</code></a></li>
<li><a href="#all_fs_dirread"><code>dir.read()</code></a></li>
<li><a href="#all_fs_dirreadcallback"><code>dir.read(callback)</code></a></li>
<li><a href="#all_fs_dirreadsync"><code>dir.readSync()</code></a></li>
<li><a href="#all_fs_dirsymbolasynciterator"><code>dir[Symbol.asyncIterator]()</code></a></li>
</ul>
</li>
<li><a href="#all_fs_class-fsdirent">Class: <code>fs.Dirent</code></a>
<ul>
<li><a href="#all_fs_direntisblockdevice"><code>dirent.isBlockDevice()</code></a></li>
<li><a href="#all_fs_direntischaracterdevice"><code>dirent.isCharacterDevice()</code></a></li>
<li><a href="#all_fs_direntisdirectory"><code>dirent.isDirectory()</code></a></li>
<li><a href="#all_fs_direntisfifo"><code>dirent.isFIFO()</code></a></li>
<li><a href="#all_fs_direntisfile"><code>dirent.isFile()</code></a></li>
<li><a href="#all_fs_direntissocket"><code>dirent.isSocket()</code></a></li>
<li><a href="#all_fs_direntissymboliclink"><code>dirent.isSymbolicLink()</code></a></li>
<li><a href="#all_fs_direntname"><code>dirent.name</code></a></li>
<li><span class="stability_1"><a href="#all_fs_direntparentpath"><code>dirent.parentPath</code></a></span></li>
<li><span class="stability_0"><a href="#all_fs_direntpath"><code>dirent.path</code></a></span></li>
</ul>
</li>
<li><a href="#all_fs_class-fsfswatcher">Class: <code>fs.FSWatcher</code></a>
<ul>
<li><a href="#all_fs_event-change">Event: <code>'change'</code></a></li>
<li><a href="#all_fs_event-close_1">Event: <code>'close'</code></a></li>
<li><a href="#all_fs_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_fs_watcherclose"><code>watcher.close()</code></a></li>
<li><a href="#all_fs_watcherref"><code>watcher.ref()</code></a></li>
<li><a href="#all_fs_watcherunref"><code>watcher.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_fs_class-fsstatwatcher">Class: <code>fs.StatWatcher</code></a>
<ul>
<li><a href="#all_fs_watcherref_1"><code>watcher.ref()</code></a></li>
<li><a href="#all_fs_watcherunref_1"><code>watcher.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_fs_class-fsreadstream">Class: <code>fs.ReadStream</code></a>
<ul>
<li><a href="#all_fs_event-close_2">Event: <code>'close'</code></a></li>
<li><a href="#all_fs_event-open">Event: <code>'open'</code></a></li>
<li><a href="#all_fs_event-ready">Event: <code>'ready'</code></a></li>
<li><a href="#all_fs_readstreambytesread"><code>readStream.bytesRead</code></a></li>
<li><a href="#all_fs_readstreampath"><code>readStream.path</code></a></li>
<li><a href="#all_fs_readstreampending"><code>readStream.pending</code></a></li>
</ul>
</li>
<li><a href="#all_fs_class-fsstats">Class: <code>fs.Stats</code></a>
<ul>
<li><a href="#all_fs_statsisblockdevice"><code>stats.isBlockDevice()</code></a></li>
<li><a href="#all_fs_statsischaracterdevice"><code>stats.isCharacterDevice()</code></a></li>
<li><a href="#all_fs_statsisdirectory"><code>stats.isDirectory()</code></a></li>
<li><a href="#all_fs_statsisfifo"><code>stats.isFIFO()</code></a></li>
<li><a href="#all_fs_statsisfile"><code>stats.isFile()</code></a></li>
<li><a href="#all_fs_statsissocket"><code>stats.isSocket()</code></a></li>
<li><a href="#all_fs_statsissymboliclink"><code>stats.isSymbolicLink()</code></a></li>
<li><a href="#all_fs_statsdev"><code>stats.dev</code></a></li>
<li><a href="#all_fs_statsino"><code>stats.ino</code></a></li>
<li><a href="#all_fs_statsmode"><code>stats.mode</code></a></li>
<li><a href="#all_fs_statsnlink"><code>stats.nlink</code></a></li>
<li><a href="#all_fs_statsuid"><code>stats.uid</code></a></li>
<li><a href="#all_fs_statsgid"><code>stats.gid</code></a></li>
<li><a href="#all_fs_statsrdev"><code>stats.rdev</code></a></li>
<li><a href="#all_fs_statssize"><code>stats.size</code></a></li>
<li><a href="#all_fs_statsblksize"><code>stats.blksize</code></a></li>
<li><a href="#all_fs_statsblocks"><code>stats.blocks</code></a></li>
<li><a href="#all_fs_statsatimems"><code>stats.atimeMs</code></a></li>
<li><a href="#all_fs_statsmtimems"><code>stats.mtimeMs</code></a></li>
<li><a href="#all_fs_statsctimems"><code>stats.ctimeMs</code></a></li>
<li><a href="#all_fs_statsbirthtimems"><code>stats.birthtimeMs</code></a></li>
<li><a href="#all_fs_statsatimens"><code>stats.atimeNs</code></a></li>
<li><a href="#all_fs_statsmtimens"><code>stats.mtimeNs</code></a></li>
<li><a href="#all_fs_statsctimens"><code>stats.ctimeNs</code></a></li>
<li><a href="#all_fs_statsbirthtimens"><code>stats.birthtimeNs</code></a></li>
<li><a href="#all_fs_statsatime"><code>stats.atime</code></a></li>
<li><a href="#all_fs_statsmtime"><code>stats.mtime</code></a></li>
<li><a href="#all_fs_statsctime"><code>stats.ctime</code></a></li>
<li><a href="#all_fs_statsbirthtime"><code>stats.birthtime</code></a></li>
<li><a href="#all_fs_stat-time-values">Stat time values</a></li>
</ul>
</li>
<li><a href="#all_fs_class-fsstatfs">Class: <code>fs.StatFs</code></a>
<ul>
<li><a href="#all_fs_statfsbavail"><code>statfs.bavail</code></a></li>
<li><a href="#all_fs_statfsbfree"><code>statfs.bfree</code></a></li>
<li><a href="#all_fs_statfsblocks"><code>statfs.blocks</code></a></li>
<li><a href="#all_fs_statfsbsize"><code>statfs.bsize</code></a></li>
<li><a href="#all_fs_statfsffree"><code>statfs.ffree</code></a></li>
<li><a href="#all_fs_statfsfiles"><code>statfs.files</code></a></li>
<li><a href="#all_fs_statfstype"><code>statfs.type</code></a></li>
</ul>
</li>
<li><a href="#all_fs_class-fswritestream">Class: <code>fs.WriteStream</code></a>
<ul>
<li><a href="#all_fs_event-close_3">Event: <code>'close'</code></a></li>
<li><a href="#all_fs_event-open_1">Event: <code>'open'</code></a></li>
<li><a href="#all_fs_event-ready_1">Event: <code>'ready'</code></a></li>
<li><a href="#all_fs_writestreambyteswritten"><code>writeStream.bytesWritten</code></a></li>
<li><a href="#all_fs_writestreamclosecallback"><code>writeStream.close([callback])</code></a></li>
<li><a href="#all_fs_writestreampath"><code>writeStream.path</code></a></li>
<li><a href="#all_fs_writestreampending"><code>writeStream.pending</code></a></li>
</ul>
</li>
<li><a href="#all_fs_fsconstants"><code>fs.constants</code></a>
<ul>
<li><a href="#all_fs_fs-constants">FS constants</a>
<ul>
<li><a href="#all_fs_file-access-constants">File access constants</a></li>
<li><a href="#all_fs_file-copy-constants">File copy constants</a></li>
<li><a href="#all_fs_file-open-constants">File open constants</a></li>
<li><a href="#all_fs_file-type-constants">File type constants</a></li>
<li><a href="#all_fs_file-mode-constants">File mode constants</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_fs_notes">Notes</a>
<ul>
<li><a href="#all_fs_ordering-of-callback-and-promise-based-operations">Ordering of callback and promise-based operations</a></li>
<li><a href="#all_fs_file-paths">File paths</a>
<ul>
<li><a href="#all_fs_string-paths">String paths</a></li>
<li><a href="#all_fs_file-url-paths">File URL paths</a>
<ul>
<li><a href="#all_fs_platform-specific-considerations">Platform-specific considerations</a></li>
</ul>
</li>
<li><a href="#all_fs_buffer-paths">Buffer paths</a></li>
<li><a href="#all_fs_per-drive-working-directories-on-windows">Per-drive working directories on Windows</a></li>
</ul>
</li>
<li><a href="#all_fs_file-descriptors_1">File descriptors</a></li>
<li><a href="#all_fs_threadpool-usage">Threadpool usage</a></li>
<li><a href="#all_fs_file-system-flags">File system flags</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_globals_global-objects">Global objects</a>
<ul>
<li><a href="#all_globals_class-abortcontroller">Class: <code>AbortController</code></a>
<ul>
<li><a href="#all_globals_abortcontrollerabortreason"><code>abortController.abort([reason])</code></a></li>
<li><a href="#all_globals_abortcontrollersignal"><code>abortController.signal</code></a></li>
<li><a href="#all_globals_class-abortsignal">Class: <code>AbortSignal</code></a>
<ul>
<li><a href="#all_globals_static-method-abortsignalabortreason">Static method: <code>AbortSignal.abort([reason])</code></a></li>
<li><a href="#all_globals_static-method-abortsignaltimeoutdelay">Static method: <code>AbortSignal.timeout(delay)</code></a></li>
<li><a href="#all_globals_static-method-abortsignalanysignals">Static method: <code>AbortSignal.any(signals)</code></a></li>
<li><a href="#all_globals_event-abort">Event: <code>'abort'</code></a></li>
<li><a href="#all_globals_abortsignalaborted"><code>abortSignal.aborted</code></a></li>
<li><a href="#all_globals_abortsignalonabort"><code>abortSignal.onabort</code></a></li>
<li><a href="#all_globals_abortsignalreason"><code>abortSignal.reason</code></a></li>
<li><a href="#all_globals_abortsignalthrowifaborted"><code>abortSignal.throwIfAborted()</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_globals_class-blob">Class: <code>Blob</code></a></li>
<li><a href="#all_globals_class-buffer">Class: <code>Buffer</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-bytelengthqueuingstrategy">Class: <code>ByteLengthQueuingStrategy</code></a></span></li>
<li><a href="#all_globals___dirname"><code>__dirname</code></a></li>
<li><a href="#all_globals___filename"><code>__filename</code></a></li>
<li><span class="stability_3"><a href="#all_globals_atobdata"><code>atob(data)</code></a></span></li>
<li><a href="#all_globals_broadcastchannel"><code>BroadcastChannel</code></a></li>
<li><span class="stability_3"><a href="#all_globals_btoadata"><code>btoa(data)</code></a></span></li>
<li><a href="#all_globals_clearimmediateimmediateobject"><code>clearImmediate(immediateObject)</code></a></li>
<li><a href="#all_globals_clearintervalintervalobject"><code>clearInterval(intervalObject)</code></a></li>
<li><a href="#all_globals_cleartimeouttimeoutobject"><code>clearTimeout(timeoutObject)</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-compressionstream">Class: <code>CompressionStream</code></a></span></li>
<li><a href="#all_globals_console"><code>console</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-countqueuingstrategy">Class: <code>CountQueuingStrategy</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_crypto"><code>Crypto</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_crypto_1"><code>crypto</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_cryptokey"><code>CryptoKey</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_customevent"><code>CustomEvent</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-decompressionstream">Class: <code>DecompressionStream</code></a></span></li>
<li><a href="#all_globals_event"><code>Event</code></a></li>
<li><span class="stability_1"><a href="#all_globals_eventsource"><code>EventSource</code></a></span></li>
<li><a href="#all_globals_eventtarget"><code>EventTarget</code></a></li>
<li><a href="#all_globals_exports"><code>exports</code></a></li>
<li><span class="stability_1"><a href="#all_globals_fetch"><code>fetch</code></a></span></li>
<li><a href="#all_globals_class-file">Class: <code>File</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-formdata">Class <code>FormData</code></a></span></li>
<li><span class="stability_3"><a href="#all_globals_global"><code>global</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-headers">Class <code>Headers</code></a></span></li>
<li><a href="#all_globals_messagechannel"><code>MessageChannel</code></a></li>
<li><a href="#all_globals_messageevent"><code>MessageEvent</code></a></li>
<li><a href="#all_globals_messageport"><code>MessagePort</code></a></li>
<li><a href="#all_globals_module"><code>module</code></a></li>
<li><a href="#all_globals_performanceentry"><code>PerformanceEntry</code></a></li>
<li><a href="#all_globals_performancemark"><code>PerformanceMark</code></a></li>
<li><a href="#all_globals_performancemeasure"><code>PerformanceMeasure</code></a></li>
<li><a href="#all_globals_performanceobserver"><code>PerformanceObserver</code></a></li>
<li><a href="#all_globals_performanceobserverentrylist"><code>PerformanceObserverEntryList</code></a></li>
<li><a href="#all_globals_performanceresourcetiming"><code>PerformanceResourceTiming</code></a></li>
<li><a href="#all_globals_performance"><code>performance</code></a></li>
<li><a href="#all_globals_process"><code>process</code></a></li>
<li><a href="#all_globals_queuemicrotaskcallback"><code>queueMicrotask(callback)</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-readablebytestreamcontroller">Class: <code>ReadableByteStreamController</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-readablestream">Class: <code>ReadableStream</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-readablestreambyobreader">Class: <code>ReadableStreamBYOBReader</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-readablestreambyobrequest">Class: <code>ReadableStreamBYOBRequest</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-readablestreamdefaultcontroller">Class: <code>ReadableStreamDefaultController</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-readablestreamdefaultreader">Class: <code>ReadableStreamDefaultReader</code></a></span></li>
<li><a href="#all_globals_require"><code>require()</code></a></li>
<li><span class="stability_1"><a href="#all_globals_response"><code>Response</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_request"><code>Request</code></a></span></li>
<li><a href="#all_globals_setimmediatecallback-args"><code>setImmediate(callback[, ...args])</code></a></li>
<li><a href="#all_globals_setintervalcallback-delay-args"><code>setInterval(callback, delay[, ...args])</code></a></li>
<li><a href="#all_globals_settimeoutcallback-delay-args"><code>setTimeout(callback, delay[, ...args])</code></a></li>
<li><a href="#all_globals_structuredclonevalue-options"><code>structuredClone(value[, options])</code></a></li>
<li><span class="stability_1"><a href="#all_globals_subtlecrypto"><code>SubtleCrypto</code></a></span></li>
<li><a href="#all_globals_domexception"><code>DOMException</code></a></li>
<li><a href="#all_globals_textdecoder"><code>TextDecoder</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-textdecoderstream">Class: <code>TextDecoderStream</code></a></span></li>
<li><a href="#all_globals_textencoder"><code>TextEncoder</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-textencoderstream">Class: <code>TextEncoderStream</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-transformstream">Class: <code>TransformStream</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-transformstreamdefaultcontroller">Class: <code>TransformStreamDefaultController</code></a></span></li>
<li><a href="#all_globals_url"><code>URL</code></a></li>
<li><a href="#all_globals_urlsearchparams"><code>URLSearchParams</code></a></li>
<li><a href="#all_globals_webassembly"><code>WebAssembly</code></a></li>
<li><span class="stability_1"><a href="#all_globals_websocket"><code>WebSocket</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-writablestream">Class: <code>WritableStream</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-writablestreamdefaultcontroller">Class: <code>WritableStreamDefaultController</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-writablestreamdefaultwriter">Class: <code>WritableStreamDefaultWriter</code></a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_http_http">HTTP</a></span>
<ul>
<li><a href="#all_http_class-httpagent">Class: <code>http.Agent</code></a>
<ul>
<li><a href="#all_http_new-agentoptions"><code>new Agent([options])</code></a></li>
<li><a href="#all_http_agentcreateconnectionoptions-callback"><code>agent.createConnection(options[, callback])</code></a></li>
<li><a href="#all_http_agentkeepsocketalivesocket"><code>agent.keepSocketAlive(socket)</code></a></li>
<li><a href="#all_http_agentreusesocketsocket-request"><code>agent.reuseSocket(socket, request)</code></a></li>
<li><a href="#all_http_agentdestroy"><code>agent.destroy()</code></a></li>
<li><a href="#all_http_agentfreesockets"><code>agent.freeSockets</code></a></li>
<li><a href="#all_http_agentgetnameoptions"><code>agent.getName([options])</code></a></li>
<li><a href="#all_http_agentmaxfreesockets"><code>agent.maxFreeSockets</code></a></li>
<li><a href="#all_http_agentmaxsockets"><code>agent.maxSockets</code></a></li>
<li><a href="#all_http_agentmaxtotalsockets"><code>agent.maxTotalSockets</code></a></li>
<li><a href="#all_http_agentrequests"><code>agent.requests</code></a></li>
<li><a href="#all_http_agentsockets"><code>agent.sockets</code></a></li>
</ul>
</li>
<li><a href="#all_http_class-httpclientrequest">Class: <code>http.ClientRequest</code></a>
<ul>
<li><span class="stability_0"><a href="#all_http_event-abort">Event: <code>'abort'</code></a></span></li>
<li><a href="#all_http_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_http_event-connect">Event: <code>'connect'</code></a></li>
<li><a href="#all_http_event-continue">Event: <code>'continue'</code></a></li>
<li><a href="#all_http_event-finish">Event: <code>'finish'</code></a></li>
<li><a href="#all_http_event-information">Event: <code>'information'</code></a></li>
<li><a href="#all_http_event-response">Event: <code>'response'</code></a></li>
<li><a href="#all_http_event-socket">Event: <code>'socket'</code></a></li>
<li><a href="#all_http_event-timeout">Event: <code>'timeout'</code></a></li>
<li><a href="#all_http_event-upgrade">Event: <code>'upgrade'</code></a></li>
<li><span class="stability_0"><a href="#all_http_requestabort"><code>request.abort()</code></a></span></li>
<li><span class="stability_0"><a href="#all_http_requestaborted"><code>request.aborted</code></a></span></li>
<li><span class="stability_0"><a href="#all_http_requestconnection"><code>request.connection</code></a></span></li>
<li><a href="#all_http_requestcork"><code>request.cork()</code></a></li>
<li><a href="#all_http_requestenddata-encoding-callback"><code>request.end([data[, encoding]][, callback])</code></a></li>
<li><a href="#all_http_requestdestroyerror"><code>request.destroy([error])</code></a>
<ul>
<li><a href="#all_http_requestdestroyed"><code>request.destroyed</code></a></li>
</ul>
</li>
<li><span class="stability_0"><a href="#all_http_requestfinished"><code>request.finished</code></a></span></li>
<li><a href="#all_http_requestflushheaders"><code>request.flushHeaders()</code></a></li>
<li><a href="#all_http_requestgetheadername"><code>request.getHeader(name)</code></a></li>
<li><a href="#all_http_requestgetheadernames"><code>request.getHeaderNames()</code></a></li>
<li><a href="#all_http_requestgetheaders"><code>request.getHeaders()</code></a></li>
<li><a href="#all_http_requestgetrawheadernames"><code>request.getRawHeaderNames()</code></a></li>
<li><a href="#all_http_requesthasheadername"><code>request.hasHeader(name)</code></a></li>
<li><a href="#all_http_requestmaxheaderscount"><code>request.maxHeadersCount</code></a></li>
<li><a href="#all_http_requestpath"><code>request.path</code></a></li>
<li><a href="#all_http_requestmethod"><code>request.method</code></a></li>
<li><a href="#all_http_requesthost"><code>request.host</code></a></li>
<li><a href="#all_http_requestprotocol"><code>request.protocol</code></a></li>
<li><a href="#all_http_requestremoveheadername"><code>request.removeHeader(name)</code></a></li>
<li><a href="#all_http_requestreusedsocket"><code>request.reusedSocket</code></a></li>
<li><a href="#all_http_requestsetheadername-value"><code>request.setHeader(name, value)</code></a></li>
<li><a href="#all_http_requestsetnodelaynodelay"><code>request.setNoDelay([noDelay])</code></a></li>
<li><a href="#all_http_requestsetsocketkeepaliveenable-initialdelay"><code>request.setSocketKeepAlive([enable][, initialDelay])</code></a></li>
<li><a href="#all_http_requestsettimeouttimeout-callback"><code>request.setTimeout(timeout[, callback])</code></a></li>
<li><a href="#all_http_requestsocket"><code>request.socket</code></a></li>
<li><a href="#all_http_requestuncork"><code>request.uncork()</code></a></li>
<li><a href="#all_http_requestwritableended"><code>request.writableEnded</code></a></li>
<li><a href="#all_http_requestwritablefinished"><code>request.writableFinished</code></a></li>
<li><a href="#all_http_requestwritechunk-encoding-callback"><code>request.write(chunk[, encoding][, callback])</code></a></li>
</ul>
</li>
<li><a href="#all_http_class-httpserver">Class: <code>http.Server</code></a>
<ul>
<li><a href="#all_http_event-checkcontinue">Event: <code>'checkContinue'</code></a></li>
<li><a href="#all_http_event-checkexpectation">Event: <code>'checkExpectation'</code></a></li>
<li><a href="#all_http_event-clienterror">Event: <code>'clientError'</code></a></li>
<li><a href="#all_http_event-close_1">Event: <code>'close'</code></a></li>
<li><a href="#all_http_event-connect_1">Event: <code>'connect'</code></a></li>
<li><a href="#all_http_event-connection">Event: <code>'connection'</code></a></li>
<li><a href="#all_http_event-droprequest">Event: <code>'dropRequest'</code></a></li>
<li><a href="#all_http_event-request">Event: <code>'request'</code></a></li>
<li><a href="#all_http_event-upgrade_1">Event: <code>'upgrade'</code></a></li>
<li><a href="#all_http_serverclosecallback"><code>server.close([callback])</code></a></li>
<li><a href="#all_http_servercloseallconnections"><code>server.closeAllConnections()</code></a></li>
<li><a href="#all_http_servercloseidleconnections"><code>server.closeIdleConnections()</code></a></li>
<li><a href="#all_http_serverheaderstimeout"><code>server.headersTimeout</code></a></li>
<li><a href="#all_http_serverlisten"><code>server.listen()</code></a></li>
<li><a href="#all_http_serverlistening"><code>server.listening</code></a></li>
<li><a href="#all_http_servermaxheaderscount"><code>server.maxHeadersCount</code></a></li>
<li><a href="#all_http_serverrequesttimeout"><code>server.requestTimeout</code></a></li>
<li><a href="#all_http_serversettimeoutmsecs-callback"><code>server.setTimeout([msecs][, callback])</code></a></li>
<li><a href="#all_http_servermaxrequestspersocket"><code>server.maxRequestsPerSocket</code></a></li>
<li><a href="#all_http_servertimeout"><code>server.timeout</code></a></li>
<li><a href="#all_http_serverkeepalivetimeout"><code>server.keepAliveTimeout</code></a></li>
<li><span class="stability_1"><a href="#all_http_serversymbolasyncdispose"><code>server[Symbol.asyncDispose]()</code></a></span></li>
</ul>
</li>
<li><a href="#all_http_class-httpserverresponse">Class: <code>http.ServerResponse</code></a>
<ul>
<li><a href="#all_http_event-close_2">Event: <code>'close'</code></a></li>
<li><a href="#all_http_event-finish_1">Event: <code>'finish'</code></a></li>
<li><a href="#all_http_responseaddtrailersheaders"><code>response.addTrailers(headers)</code></a></li>
<li><span class="stability_0"><a href="#all_http_responseconnection"><code>response.connection</code></a></span></li>
<li><a href="#all_http_responsecork"><code>response.cork()</code></a></li>
<li><a href="#all_http_responseenddata-encoding-callback"><code>response.end([data[, encoding]][, callback])</code></a></li>
<li><span class="stability_0"><a href="#all_http_responsefinished"><code>response.finished</code></a></span></li>
<li><a href="#all_http_responseflushheaders"><code>response.flushHeaders()</code></a></li>
<li><a href="#all_http_responsegetheadername"><code>response.getHeader(name)</code></a></li>
<li><a href="#all_http_responsegetheadernames"><code>response.getHeaderNames()</code></a></li>
<li><a href="#all_http_responsegetheaders"><code>response.getHeaders()</code></a></li>
<li><a href="#all_http_responsehasheadername"><code>response.hasHeader(name)</code></a></li>
<li><a href="#all_http_responseheaderssent"><code>response.headersSent</code></a></li>
<li><a href="#all_http_responseremoveheadername"><code>response.removeHeader(name)</code></a></li>
<li><a href="#all_http_responsereq"><code>response.req</code></a></li>
<li><a href="#all_http_responsesenddate"><code>response.sendDate</code></a></li>
<li><a href="#all_http_responsesetheadername-value"><code>response.setHeader(name, value)</code></a></li>
<li><a href="#all_http_responsesettimeoutmsecs-callback"><code>response.setTimeout(msecs[, callback])</code></a></li>
<li><a href="#all_http_responsesocket"><code>response.socket</code></a></li>
<li><a href="#all_http_responsestatuscode"><code>response.statusCode</code></a></li>
<li><a href="#all_http_responsestatusmessage"><code>response.statusMessage</code></a></li>
<li><a href="#all_http_responsestrictcontentlength"><code>response.strictContentLength</code></a></li>
<li><a href="#all_http_responseuncork"><code>response.uncork()</code></a></li>
<li><a href="#all_http_responsewritableended"><code>response.writableEnded</code></a></li>
<li><a href="#all_http_responsewritablefinished"><code>response.writableFinished</code></a></li>
<li><a href="#all_http_responsewritechunk-encoding-callback"><code>response.write(chunk[, encoding][, callback])</code></a></li>
<li><a href="#all_http_responsewritecontinue"><code>response.writeContinue()</code></a></li>
<li><a href="#all_http_responsewriteearlyhintshints-callback"><code>response.writeEarlyHints(hints[, callback])</code></a></li>
<li><a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead(statusCode[, statusMessage][, headers])</code></a></li>
<li><a href="#all_http_responsewriteprocessing"><code>response.writeProcessing()</code></a></li>
</ul>
</li>
<li><a href="#all_http_class-httpincomingmessage">Class: <code>http.IncomingMessage</code></a>
<ul>
<li><span class="stability_0"><a href="#all_http_event-aborted">Event: <code>'aborted'</code></a></span></li>
<li><a href="#all_http_event-close_3">Event: <code>'close'</code></a></li>
<li><span class="stability_0"><a href="#all_http_messageaborted"><code>message.aborted</code></a></span></li>
<li><a href="#all_http_messagecomplete"><code>message.complete</code></a></li>
<li><span class="stability_0"><a href="#all_http_messageconnection"><code>message.connection</code></a></span></li>
<li><a href="#all_http_messagedestroyerror"><code>message.destroy([error])</code></a></li>
<li><a href="#all_http_messageheaders"><code>message.headers</code></a></li>
<li><a href="#all_http_messageheadersdistinct"><code>message.headersDistinct</code></a></li>
<li><a href="#all_http_messagehttpversion"><code>message.httpVersion</code></a></li>
<li><a href="#all_http_messagemethod"><code>message.method</code></a></li>
<li><a href="#all_http_messagerawheaders"><code>message.rawHeaders</code></a></li>
<li><a href="#all_http_messagerawtrailers"><code>message.rawTrailers</code></a></li>
<li><a href="#all_http_messagesettimeoutmsecs-callback"><code>message.setTimeout(msecs[, callback])</code></a></li>
<li><a href="#all_http_messagesocket"><code>message.socket</code></a></li>
<li><a href="#all_http_messagestatuscode"><code>message.statusCode</code></a></li>
<li><a href="#all_http_messagestatusmessage"><code>message.statusMessage</code></a></li>
<li><a href="#all_http_messagetrailers"><code>message.trailers</code></a></li>
<li><a href="#all_http_messagetrailersdistinct"><code>message.trailersDistinct</code></a></li>
<li><a href="#all_http_messageurl"><code>message.url</code></a></li>
</ul>
</li>
<li><a href="#all_http_class-httpoutgoingmessage">Class: <code>http.OutgoingMessage</code></a>
<ul>
<li><a href="#all_http_event-drain">Event: <code>'drain'</code></a></li>
<li><a href="#all_http_event-finish_2">Event: <code>'finish'</code></a></li>
<li><a href="#all_http_event-prefinish">Event: <code>'prefinish'</code></a></li>
<li><a href="#all_http_outgoingmessageaddtrailersheaders"><code>outgoingMessage.addTrailers(headers)</code></a></li>
<li><a href="#all_http_outgoingmessageappendheadername-value"><code>outgoingMessage.appendHeader(name, value)</code></a></li>
<li><span class="stability_0"><a href="#all_http_outgoingmessageconnection"><code>outgoingMessage.connection</code></a></span></li>
<li><a href="#all_http_outgoingmessagecork"><code>outgoingMessage.cork()</code></a></li>
<li><a href="#all_http_outgoingmessagedestroyerror"><code>outgoingMessage.destroy([error])</code></a></li>
<li><a href="#all_http_outgoingmessageendchunk-encoding-callback"><code>outgoingMessage.end(chunk[, encoding][, callback])</code></a></li>
<li><a href="#all_http_outgoingmessageflushheaders"><code>outgoingMessage.flushHeaders()</code></a></li>
<li><a href="#all_http_outgoingmessagegetheadername"><code>outgoingMessage.getHeader(name)</code></a></li>
<li><a href="#all_http_outgoingmessagegetheadernames"><code>outgoingMessage.getHeaderNames()</code></a></li>
<li><a href="#all_http_outgoingmessagegetheaders"><code>outgoingMessage.getHeaders()</code></a></li>
<li><a href="#all_http_outgoingmessagehasheadername"><code>outgoingMessage.hasHeader(name)</code></a></li>
<li><a href="#all_http_outgoingmessageheaderssent"><code>outgoingMessage.headersSent</code></a></li>
<li><a href="#all_http_outgoingmessagepipe"><code>outgoingMessage.pipe()</code></a></li>
<li><a href="#all_http_outgoingmessageremoveheadername"><code>outgoingMessage.removeHeader(name)</code></a></li>
<li><a href="#all_http_outgoingmessagesetheadername-value"><code>outgoingMessage.setHeader(name, value)</code></a></li>
<li><a href="#all_http_outgoingmessagesetheadersheaders"><code>outgoingMessage.setHeaders(headers)</code></a></li>
<li><a href="#all_http_outgoingmessagesettimeoutmsesc-callback"><code>outgoingMessage.setTimeout(msesc[, callback])</code></a></li>
<li><a href="#all_http_outgoingmessagesocket"><code>outgoingMessage.socket</code></a></li>
<li><a href="#all_http_outgoingmessageuncork"><code>outgoingMessage.uncork()</code></a></li>
<li><a href="#all_http_outgoingmessagewritablecorked"><code>outgoingMessage.writableCorked</code></a></li>
<li><a href="#all_http_outgoingmessagewritableended"><code>outgoingMessage.writableEnded</code></a></li>
<li><a href="#all_http_outgoingmessagewritablefinished"><code>outgoingMessage.writableFinished</code></a></li>
<li><a href="#all_http_outgoingmessagewritablehighwatermark"><code>outgoingMessage.writableHighWaterMark</code></a></li>
<li><a href="#all_http_outgoingmessagewritablelength"><code>outgoingMessage.writableLength</code></a></li>
<li><a href="#all_http_outgoingmessagewritableobjectmode"><code>outgoingMessage.writableObjectMode</code></a></li>
<li><a href="#all_http_outgoingmessagewritechunk-encoding-callback"><code>outgoingMessage.write(chunk[, encoding][, callback])</code></a></li>
</ul>
</li>
<li><a href="#all_http_httpmethods"><code>http.METHODS</code></a></li>
<li><a href="#all_http_httpstatus_codes"><code>http.STATUS_CODES</code></a></li>
<li><a href="#all_http_httpcreateserveroptions-requestlistener"><code>http.createServer([options][, requestListener])</code></a></li>
<li><a href="#all_http_httpgetoptions-callback"><code>http.get(options[, callback])</code></a></li>
<li><a href="#all_http_httpgeturl-options-callback"><code>http.get(url[, options][, callback])</code></a></li>
<li><a href="#all_http_httpglobalagent"><code>http.globalAgent</code></a></li>
<li><a href="#all_http_httpmaxheadersize"><code>http.maxHeaderSize</code></a></li>
<li><a href="#all_http_httprequestoptions-callback"><code>http.request(options[, callback])</code></a></li>
<li><a href="#all_http_httprequesturl-options-callback"><code>http.request(url[, options][, callback])</code></a></li>
<li><a href="#all_http_httpvalidateheadernamename-label"><code>http.validateHeaderName(name[, label])</code></a></li>
<li><a href="#all_http_httpvalidateheadervaluename-value"><code>http.validateHeaderValue(name, value)</code></a></li>
<li><a href="#all_http_httpsetmaxidlehttpparsersmax"><code>http.setMaxIdleHTTPParsers(max)</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_http2_http2">HTTP/2</a></span>
<ul>
<li><a href="#all_http2_determining-if-crypto-support-is-unavailable">Determining if crypto support is unavailable</a></li>
<li><a href="#all_http2_core-api">Core API</a>
<ul>
<li><a href="#all_http2_server-side-example">Server-side example</a></li>
<li><a href="#all_http2_client-side-example">Client-side example</a></li>
<li><a href="#all_http2_class-http2session">Class: <code>Http2Session</code></a>
<ul>
<li><a href="#all_http2_http2session-and-sockets"><code>Http2Session</code> and sockets</a></li>
<li><a href="#all_http2_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_http2_event-connect">Event: <code>'connect'</code></a></li>
<li><a href="#all_http2_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_http2_event-frameerror">Event: <code>'frameError'</code></a></li>
<li><a href="#all_http2_event-goaway">Event: <code>'goaway'</code></a></li>
<li><a href="#all_http2_event-localsettings">Event: <code>'localSettings'</code></a></li>
<li><a href="#all_http2_event-ping">Event: <code>'ping'</code></a></li>
<li><a href="#all_http2_event-remotesettings">Event: <code>'remoteSettings'</code></a></li>
<li><a href="#all_http2_event-stream">Event: <code>'stream'</code></a></li>
<li><a href="#all_http2_event-timeout">Event: <code>'timeout'</code></a></li>
<li><a href="#all_http2_http2sessionalpnprotocol"><code>http2session.alpnProtocol</code></a></li>
<li><a href="#all_http2_http2sessionclosecallback"><code>http2session.close([callback])</code></a></li>
<li><a href="#all_http2_http2sessionclosed"><code>http2session.closed</code></a></li>
<li><a href="#all_http2_http2sessionconnecting"><code>http2session.connecting</code></a></li>
<li><a href="#all_http2_http2sessiondestroyerror-code"><code>http2session.destroy([error][, code])</code></a></li>
<li><a href="#all_http2_http2sessiondestroyed"><code>http2session.destroyed</code></a></li>
<li><a href="#all_http2_http2sessionencrypted"><code>http2session.encrypted</code></a></li>
<li><a href="#all_http2_http2sessiongoawaycode-laststreamid-opaquedata"><code>http2session.goaway([code[, lastStreamID[, opaqueData]]])</code></a></li>
<li><a href="#all_http2_http2sessionlocalsettings"><code>http2session.localSettings</code></a></li>
<li><a href="#all_http2_http2sessionoriginset"><code>http2session.originSet</code></a></li>
<li><a href="#all_http2_http2sessionpendingsettingsack"><code>http2session.pendingSettingsAck</code></a></li>
<li><a href="#all_http2_http2sessionpingpayload-callback"><code>http2session.ping([payload, ]callback)</code></a></li>
<li><a href="#all_http2_http2sessionref"><code>http2session.ref()</code></a></li>
<li><a href="#all_http2_http2sessionremotesettings"><code>http2session.remoteSettings</code></a></li>
<li><a href="#all_http2_http2sessionsetlocalwindowsizewindowsize"><code>http2session.setLocalWindowSize(windowSize)</code></a></li>
<li><a href="#all_http2_http2sessionsettimeoutmsecs-callback"><code>http2session.setTimeout(msecs, callback)</code></a></li>
<li><a href="#all_http2_http2sessionsocket"><code>http2session.socket</code></a></li>
<li><a href="#all_http2_http2sessionstate"><code>http2session.state</code></a></li>
<li><a href="#all_http2_http2sessionsettingssettings-callback"><code>http2session.settings([settings][, callback])</code></a></li>
<li><a href="#all_http2_http2sessiontype"><code>http2session.type</code></a></li>
<li><a href="#all_http2_http2sessionunref"><code>http2session.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-serverhttp2session">Class: <code>ServerHttp2Session</code></a>
<ul>
<li><a href="#all_http2_serverhttp2sessionaltsvcalt-originorstream"><code>serverhttp2session.altsvc(alt, originOrStream)</code></a></li>
<li><a href="#all_http2_specifying-alternative-services">Specifying alternative services</a></li>
<li><a href="#all_http2_serverhttp2sessionoriginorigins"><code>serverhttp2session.origin(...origins)</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-clienthttp2session">Class: <code>ClientHttp2Session</code></a>
<ul>
<li><a href="#all_http2_event-altsvc">Event: <code>'altsvc'</code></a></li>
<li><a href="#all_http2_event-origin">Event: <code>'origin'</code></a></li>
<li><a href="#all_http2_clienthttp2sessionrequestheaders-options"><code>clienthttp2session.request(headers[, options])</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-http2stream">Class: <code>Http2Stream</code></a>
<ul>
<li><a href="#all_http2_http2stream-lifecycle"><code>Http2Stream</code> Lifecycle</a>
<ul>
<li><a href="#all_http2_creation">Creation</a></li>
<li><a href="#all_http2_destruction">Destruction</a></li>
</ul>
</li>
<li><a href="#all_http2_event-aborted">Event: <code>'aborted'</code></a></li>
<li><a href="#all_http2_event-close_1">Event: <code>'close'</code></a></li>
<li><a href="#all_http2_event-error_1">Event: <code>'error'</code></a></li>
<li><a href="#all_http2_event-frameerror_1">Event: <code>'frameError'</code></a></li>
<li><a href="#all_http2_event-ready">Event: <code>'ready'</code></a></li>
<li><a href="#all_http2_event-timeout_1">Event: <code>'timeout'</code></a></li>
<li><a href="#all_http2_event-trailers">Event: <code>'trailers'</code></a></li>
<li><a href="#all_http2_event-wanttrailers">Event: <code>'wantTrailers'</code></a></li>
<li><a href="#all_http2_http2streamaborted"><code>http2stream.aborted</code></a></li>
<li><a href="#all_http2_http2streambuffersize"><code>http2stream.bufferSize</code></a></li>
<li><a href="#all_http2_http2streamclosecode-callback"><code>http2stream.close(code[, callback])</code></a></li>
<li><a href="#all_http2_http2streamclosed"><code>http2stream.closed</code></a></li>
<li><a href="#all_http2_http2streamdestroyed"><code>http2stream.destroyed</code></a></li>
<li><a href="#all_http2_http2streamendafterheaders"><code>http2stream.endAfterHeaders</code></a></li>
<li><a href="#all_http2_http2streamid"><code>http2stream.id</code></a></li>
<li><a href="#all_http2_http2streampending"><code>http2stream.pending</code></a></li>
<li><a href="#all_http2_http2streampriorityoptions"><code>http2stream.priority(options)</code></a></li>
<li><a href="#all_http2_http2streamrstcode"><code>http2stream.rstCode</code></a></li>
<li><a href="#all_http2_http2streamsentheaders"><code>http2stream.sentHeaders</code></a></li>
<li><a href="#all_http2_http2streamsentinfoheaders"><code>http2stream.sentInfoHeaders</code></a></li>
<li><a href="#all_http2_http2streamsenttrailers"><code>http2stream.sentTrailers</code></a></li>
<li><a href="#all_http2_http2streamsession"><code>http2stream.session</code></a></li>
<li><a href="#all_http2_http2streamsettimeoutmsecs-callback"><code>http2stream.setTimeout(msecs, callback)</code></a></li>
<li><a href="#all_http2_http2streamstate"><code>http2stream.state</code></a></li>
<li><a href="#all_http2_http2streamsendtrailersheaders"><code>http2stream.sendTrailers(headers)</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-clienthttp2stream">Class: <code>ClientHttp2Stream</code></a>
<ul>
<li><a href="#all_http2_event-continue">Event: <code>'continue'</code></a></li>
<li><a href="#all_http2_event-headers">Event: <code>'headers'</code></a></li>
<li><a href="#all_http2_event-push">Event: <code>'push'</code></a></li>
<li><a href="#all_http2_event-response">Event: <code>'response'</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-serverhttp2stream">Class: <code>ServerHttp2Stream</code></a>
<ul>
<li><a href="#all_http2_http2streamadditionalheadersheaders"><code>http2stream.additionalHeaders(headers)</code></a></li>
<li><a href="#all_http2_http2streamheaderssent"><code>http2stream.headersSent</code></a></li>
<li><a href="#all_http2_http2streampushallowed"><code>http2stream.pushAllowed</code></a></li>
<li><a href="#all_http2_http2streampushstreamheaders-options-callback"><code>http2stream.pushStream(headers[, options], callback)</code></a></li>
<li><a href="#all_http2_http2streamrespondheaders-options"><code>http2stream.respond([headers[, options]])</code></a></li>
<li><a href="#all_http2_http2streamrespondwithfdfd-headers-options"><code>http2stream.respondWithFD(fd[, headers[, options]])</code></a></li>
<li><a href="#all_http2_http2streamrespondwithfilepath-headers-options"><code>http2stream.respondWithFile(path[, headers[, options]])</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-http2server">Class: <code>Http2Server</code></a>
<ul>
<li><a href="#all_http2_event-checkcontinue">Event: <code>'checkContinue'</code></a></li>
<li><a href="#all_http2_event-connection">Event: <code>'connection'</code></a></li>
<li><a href="#all_http2_event-request">Event: <code>'request'</code></a></li>
<li><a href="#all_http2_event-session">Event: <code>'session'</code></a></li>
<li><a href="#all_http2_event-sessionerror">Event: <code>'sessionError'</code></a></li>
<li><a href="#all_http2_event-stream_1">Event: <code>'stream'</code></a></li>
<li><a href="#all_http2_event-timeout_2">Event: <code>'timeout'</code></a></li>
<li><a href="#all_http2_serverclosecallback"><code>server.close([callback])</code></a></li>
<li><span class="stability_1"><a href="#all_http2_serversymbolasyncdispose"><code>server[Symbol.asyncDispose]()</code></a></span></li>
<li><a href="#all_http2_serversettimeoutmsecs-callback"><code>server.setTimeout([msecs][, callback])</code></a></li>
<li><a href="#all_http2_servertimeout"><code>server.timeout</code></a></li>
<li><a href="#all_http2_serverupdatesettingssettings"><code>server.updateSettings([settings])</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-http2secureserver">Class: <code>Http2SecureServer</code></a>
<ul>
<li><a href="#all_http2_event-checkcontinue_1">Event: <code>'checkContinue'</code></a></li>
<li><a href="#all_http2_event-connection_1">Event: <code>'connection'</code></a></li>
<li><a href="#all_http2_event-request_1">Event: <code>'request'</code></a></li>
<li><a href="#all_http2_event-session_1">Event: <code>'session'</code></a></li>
<li><a href="#all_http2_event-sessionerror_1">Event: <code>'sessionError'</code></a></li>
<li><a href="#all_http2_event-stream_2">Event: <code>'stream'</code></a></li>
<li><a href="#all_http2_event-timeout_3">Event: <code>'timeout'</code></a></li>
<li><a href="#all_http2_event-unknownprotocol">Event: <code>'unknownProtocol'</code></a></li>
<li><a href="#all_http2_serverclosecallback_1"><code>server.close([callback])</code></a></li>
<li><a href="#all_http2_serversettimeoutmsecs-callback_1"><code>server.setTimeout([msecs][, callback])</code></a></li>
<li><a href="#all_http2_servertimeout_1"><code>server.timeout</code></a></li>
<li><a href="#all_http2_serverupdatesettingssettings_1"><code>server.updateSettings([settings])</code></a></li>
</ul>
</li>
<li><a href="#all_http2_http2createserveroptions-onrequesthandler"><code>http2.createServer([options][, onRequestHandler])</code></a></li>
<li><a href="#all_http2_http2createsecureserveroptions-onrequesthandler"><code>http2.createSecureServer(options[, onRequestHandler])</code></a></li>
<li><a href="#all_http2_http2connectauthority-options-listener"><code>http2.connect(authority[, options][, listener])</code></a></li>
<li><a href="#all_http2_http2constants"><code>http2.constants</code></a>
<ul>
<li><a href="#all_http2_error-codes-for-rst_stream-and-goaway">Error codes for <code>RST_STREAM</code> and <code>GOAWAY</code></a></li>
</ul>
</li>
<li><a href="#all_http2_http2getdefaultsettings"><code>http2.getDefaultSettings()</code></a></li>
<li><a href="#all_http2_http2getpackedsettingssettings"><code>http2.getPackedSettings([settings])</code></a></li>
<li><a href="#all_http2_http2getunpackedsettingsbuf"><code>http2.getUnpackedSettings(buf)</code></a></li>
<li><a href="#all_http2_http2performserverhandshakesocket-options"><code>http2.performServerHandshake(socket[, options])</code></a></li>
<li><a href="#all_http2_http2sensitiveheaders"><code>http2.sensitiveHeaders</code></a></li>
<li><a href="#all_http2_headers-object">Headers object</a>
<ul>
<li><a href="#all_http2_sensitive-headers">Sensitive headers</a></li>
</ul>
</li>
<li><a href="#all_http2_settings-object">Settings object</a></li>
<li><a href="#all_http2_error-handling">Error handling</a></li>
<li><a href="#all_http2_invalid-character-handling-in-header-names-and-values">Invalid character handling in header names and values</a></li>
<li><a href="#all_http2_push-streams-on-the-client">Push streams on the client</a></li>
<li><a href="#all_http2_supporting-the-connect-method">Supporting the <code>CONNECT</code> method</a></li>
<li><a href="#all_http2_the-extended-connect-protocol">The extended <code>CONNECT</code> protocol</a></li>
</ul>
</li>
<li><a href="#all_http2_compatibility-api">Compatibility API</a>
<ul>
<li><a href="#all_http2_alpn-negotiation">ALPN negotiation</a></li>
<li><a href="#all_http2_class-http2http2serverrequest">Class: <code>http2.Http2ServerRequest</code></a>
<ul>
<li><a href="#all_http2_event-aborted_1">Event: <code>'aborted'</code></a></li>
<li><a href="#all_http2_event-close_2">Event: <code>'close'</code></a></li>
<li><a href="#all_http2_requestaborted"><code>request.aborted</code></a></li>
<li><a href="#all_http2_requestauthority"><code>request.authority</code></a></li>
<li><a href="#all_http2_requestcomplete"><code>request.complete</code></a></li>
<li><span class="stability_0"><a href="#all_http2_requestconnection"><code>request.connection</code></a></span></li>
<li><a href="#all_http2_requestdestroyerror"><code>request.destroy([error])</code></a></li>
<li><a href="#all_http2_requestheaders"><code>request.headers</code></a></li>
<li><a href="#all_http2_requesthttpversion"><code>request.httpVersion</code></a></li>
<li><a href="#all_http2_requestmethod"><code>request.method</code></a></li>
<li><a href="#all_http2_requestrawheaders"><code>request.rawHeaders</code></a></li>
<li><a href="#all_http2_requestrawtrailers"><code>request.rawTrailers</code></a></li>
<li><a href="#all_http2_requestscheme"><code>request.scheme</code></a></li>
<li><a href="#all_http2_requestsettimeoutmsecs-callback"><code>request.setTimeout(msecs, callback)</code></a></li>
<li><a href="#all_http2_requestsocket"><code>request.socket</code></a></li>
<li><a href="#all_http2_requeststream"><code>request.stream</code></a></li>
<li><a href="#all_http2_requesttrailers"><code>request.trailers</code></a></li>
<li><a href="#all_http2_requesturl"><code>request.url</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-http2http2serverresponse">Class: <code>http2.Http2ServerResponse</code></a>
<ul>
<li><a href="#all_http2_event-close_3">Event: <code>'close'</code></a></li>
<li><a href="#all_http2_event-finish">Event: <code>'finish'</code></a></li>
<li><a href="#all_http2_responseaddtrailersheaders"><code>response.addTrailers(headers)</code></a></li>
<li><a href="#all_http2_responseappendheadername-value"><code>response.appendHeader(name, value)</code></a></li>
<li><span class="stability_0"><a href="#all_http2_responseconnection"><code>response.connection</code></a></span></li>
<li><a href="#all_http2_responsecreatepushresponseheaders-callback"><code>response.createPushResponse(headers, callback)</code></a></li>
<li><a href="#all_http2_responseenddata-encoding-callback"><code>response.end([data[, encoding]][, callback])</code></a></li>
<li><span class="stability_0"><a href="#all_http2_responsefinished"><code>response.finished</code></a></span></li>
<li><a href="#all_http2_responsegetheadername"><code>response.getHeader(name)</code></a></li>
<li><a href="#all_http2_responsegetheadernames"><code>response.getHeaderNames()</code></a></li>
<li><a href="#all_http2_responsegetheaders"><code>response.getHeaders()</code></a></li>
<li><a href="#all_http2_responsehasheadername"><code>response.hasHeader(name)</code></a></li>
<li><a href="#all_http2_responseheaderssent"><code>response.headersSent</code></a></li>
<li><a href="#all_http2_responseremoveheadername"><code>response.removeHeader(name)</code></a></li>
<li><a href="#all_http2_responsereq"><code>response.req</code></a></li>
<li><a href="#all_http2_responsesenddate"><code>response.sendDate</code></a></li>
<li><a href="#all_http2_responsesetheadername-value"><code>response.setHeader(name, value)</code></a></li>
<li><a href="#all_http2_responsesettimeoutmsecs-callback"><code>response.setTimeout(msecs[, callback])</code></a></li>
<li><a href="#all_http2_responsesocket"><code>response.socket</code></a></li>
<li><a href="#all_http2_responsestatuscode"><code>response.statusCode</code></a></li>
<li><a href="#all_http2_responsestatusmessage"><code>response.statusMessage</code></a></li>
<li><a href="#all_http2_responsestream"><code>response.stream</code></a></li>
<li><a href="#all_http2_responsewritableended"><code>response.writableEnded</code></a></li>
<li><a href="#all_http2_responsewritechunk-encoding-callback"><code>response.write(chunk[, encoding][, callback])</code></a></li>
<li><a href="#all_http2_responsewritecontinue"><code>response.writeContinue()</code></a></li>
<li><a href="#all_http2_responsewriteearlyhintshints"><code>response.writeEarlyHints(hints)</code></a></li>
<li><a href="#all_http2_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead(statusCode[, statusMessage][, headers])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_http2_collecting-http2-performance-metrics">Collecting HTTP/2 performance metrics</a></li>
<li><a href="#all_http2_note-on-authority-and-host">Note on <code>:authority</code> and <code>host</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_https_https">HTTPS</a></span>
<ul>
<li><a href="#all_https_determining-if-crypto-support-is-unavailable">Determining if crypto support is unavailable</a></li>
<li><a href="#all_https_class-httpsagent">Class: <code>https.Agent</code></a>
<ul>
<li><a href="#all_https_new-agentoptions"><code>new Agent([options])</code></a>
<ul>
<li><a href="#all_https_event-keylog">Event: <code>'keylog'</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_https_class-httpsserver">Class: <code>https.Server</code></a>
<ul>
<li><a href="#all_https_serverclosecallback"><code>server.close([callback])</code></a></li>
<li><span class="stability_1"><a href="#all_https_serversymbolasyncdispose"><code>server[Symbol.asyncDispose]()</code></a></span></li>
<li><a href="#all_https_servercloseallconnections"><code>server.closeAllConnections()</code></a></li>
<li><a href="#all_https_servercloseidleconnections"><code>server.closeIdleConnections()</code></a></li>
<li><a href="#all_https_serverheaderstimeout"><code>server.headersTimeout</code></a></li>
<li><a href="#all_https_serverlisten"><code>server.listen()</code></a></li>
<li><a href="#all_https_servermaxheaderscount"><code>server.maxHeadersCount</code></a></li>
<li><a href="#all_https_serverrequesttimeout"><code>server.requestTimeout</code></a></li>
<li><a href="#all_https_serversettimeoutmsecs-callback"><code>server.setTimeout([msecs][, callback])</code></a></li>
<li><a href="#all_https_servertimeout"><code>server.timeout</code></a></li>
<li><a href="#all_https_serverkeepalivetimeout"><code>server.keepAliveTimeout</code></a></li>
</ul>
</li>
<li><a href="#all_https_httpscreateserveroptions-requestlistener"><code>https.createServer([options][, requestListener])</code></a></li>
<li><a href="#all_https_httpsgetoptions-callback"><code>https.get(options[, callback])</code></a></li>
<li><a href="#all_https_httpsgeturl-options-callback"><code>https.get(url[, options][, callback])</code></a></li>
<li><a href="#all_https_httpsglobalagent"><code>https.globalAgent</code></a></li>
<li><a href="#all_https_httpsrequestoptions-callback"><code>https.request(options[, callback])</code></a></li>
<li><a href="#all_https_httpsrequesturl-options-callback"><code>https.request(url[, options][, callback])</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_inspector_inspector">Inspector</a></span>
<ul>
<li><span class="stability_1"><a href="#all_inspector_promises-api">Promises API</a></span>
<ul>
<li><a href="#all_inspector_class-inspectorsession">Class: <code>inspector.Session</code></a>
<ul>
<li><a href="#all_inspector_new-inspectorsession"><code>new inspector.Session()</code></a></li>
<li><a href="#all_inspector_event-inspectornotification">Event: <code>'inspectorNotification'</code></a></li>
<li><a href="#all_inspector_event-inspector-protocol-method">Event: <code><inspector-protocol-method></code>;</a></li>
<li><a href="#all_inspector_sessionconnect"><code>session.connect()</code></a></li>
<li><a href="#all_inspector_sessionconnecttomainthread"><code>session.connectToMainThread()</code></a></li>
<li><a href="#all_inspector_sessiondisconnect"><code>session.disconnect()</code></a></li>
<li><a href="#all_inspector_sessionpostmethod-params"><code>session.post(method[, params])</code></a></li>
<li><a href="#all_inspector_example-usage">Example usage</a>
<ul>
<li><a href="#all_inspector_cpu-profiler">CPU profiler</a></li>
<li><a href="#all_inspector_heap-profiler">Heap profiler</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_inspector_callback-api">Callback API</a>
<ul>
<li><a href="#all_inspector_class-inspectorsession_1">Class: <code>inspector.Session</code></a>
<ul>
<li><a href="#all_inspector_new-inspectorsession_1"><code>new inspector.Session()</code></a></li>
<li><a href="#all_inspector_event-inspectornotification_1">Event: <code>'inspectorNotification'</code></a></li>
<li><a href="#all_inspector_event-inspector-protocol-method_1">Event: <code><inspector-protocol-method></code>;</a></li>
<li><a href="#all_inspector_sessionconnect_1"><code>session.connect()</code></a></li>
<li><a href="#all_inspector_sessionconnecttomainthread_1"><code>session.connectToMainThread()</code></a></li>
<li><a href="#all_inspector_sessiondisconnect_1"><code>session.disconnect()</code></a></li>
<li><a href="#all_inspector_sessionpostmethod-params-callback"><code>session.post(method[, params][, callback])</code></a></li>
<li><a href="#all_inspector_example-usage_1">Example usage</a>
<ul>
<li><a href="#all_inspector_cpu-profiler_1">CPU profiler</a></li>
<li><a href="#all_inspector_heap-profiler_1">Heap profiler</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_inspector_common-objects">Common Objects</a>
<ul>
<li><a href="#all_inspector_inspectorclose"><code>inspector.close()</code></a></li>
<li><a href="#all_inspector_inspectorconsole"><code>inspector.console</code></a></li>
<li><a href="#all_inspector_inspectoropenport-host-wait"><code>inspector.open([port[, host[, wait]]])</code></a></li>
<li><a href="#all_inspector_inspectorurl"><code>inspector.url()</code></a></li>
<li><a href="#all_inspector_inspectorwaitfordebugger"><code>inspector.waitForDebugger()</code></a></li>
</ul>
</li>
<li><a href="#all_inspector_integration-with-devtools">Integration with DevTools</a>
<ul>
<li><span class="stability_1"><a href="#all_inspector_inspectornetworkrequestwillbesentparams"><code>inspector.Network.requestWillBeSent([params])</code></a></span></li>
<li><span class="stability_1"><a href="#all_inspector_inspectornetworkresponsereceivedparams"><code>inspector.Network.responseReceived([params])</code></a></span></li>
<li><span class="stability_1"><a href="#all_inspector_inspectornetworkloadingfinishedparams"><code>inspector.Network.loadingFinished([params])</code></a></span></li>
<li><span class="stability_1"><a href="#all_inspector_inspectornetworkloadingfailedparams"><code>inspector.Network.loadingFailed([params])</code></a></span></li>
</ul>
</li>
<li><a href="#all_inspector_support-of-breakpoints">Support of breakpoints</a></li>
</ul>
</li>
<li><a href="#all_intl_internationalization-support">Internationalization support</a>
<ul>
<li><a href="#all_intl_options-for-building-nodejs">Options for building Node.js</a>
<ul>
<li><a href="#all_intl_disable-all-internationalization-features-none">Disable all internationalization features (<code>none</code>)</a></li>
<li><a href="#all_intl_build-with-a-pre-installed-icu-system-icu">Build with a pre-installed ICU (<code>system-icu</code>)</a></li>
<li><a href="#all_intl_embed-a-limited-set-of-icu-data-small-icu">Embed a limited set of ICU data (<code>small-icu</code>)</a>
<ul>
<li><a href="#all_intl_providing-icu-data-at-runtime">Providing ICU data at runtime</a></li>
</ul>
</li>
<li><a href="#all_intl_embed-the-entire-icu-full-icu">Embed the entire ICU (<code>full-icu</code>)</a></li>
</ul>
</li>
<li><a href="#all_intl_detecting-internationalization-support">Detecting internationalization support</a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_modules_modules-commonjs-modules">Modules: CommonJS modules</a></span>
<ul>
<li><a href="#all_modules_enabling">Enabling</a></li>
<li><a href="#all_modules_accessing-the-main-module">Accessing the main module</a></li>
<li><a href="#all_modules_package-manager-tips">Package manager tips</a></li>
<li><span class="stability_1"><a href="#all_modules_loading-ecmascript-modules-using-require">Loading ECMAScript modules using <code>require()</code></a></span></li>
<li><a href="#all_modules_all-together">All together</a></li>
<li><a href="#all_modules_caching">Caching</a>
<ul>
<li><a href="#all_modules_module-caching-caveats">Module caching caveats</a></li>
</ul>
</li>
<li><a href="#all_modules_built-in-modules">Built-in modules</a>
<ul>
<li><a href="#all_modules_built-in-modules-with-mandatory-node-prefix">Built-in modules with mandatory <code>node:</code> prefix</a></li>
</ul>
</li>
<li><a href="#all_modules_cycles">Cycles</a></li>
<li><a href="#all_modules_file-modules">File modules</a></li>
<li><span class="stability_3"><a href="#all_modules_folders-as-modules">Folders as modules</a></span></li>
<li><a href="#all_modules_loading-from-node_modules-folders">Loading from <code>node_modules</code> folders</a></li>
<li><a href="#all_modules_loading-from-the-global-folders">Loading from the global folders</a></li>
<li><a href="#all_modules_the-module-wrapper">The module wrapper</a></li>
<li><a href="#all_modules_the-module-scope">The module scope</a>
<ul>
<li><a href="#all_modules___dirname"><code>__dirname</code></a></li>
<li><a href="#all_modules___filename"><code>__filename</code></a></li>
<li><a href="#all_modules_exports"><code>exports</code></a></li>
<li><a href="#all_modules_module"><code>module</code></a></li>
<li><a href="#all_modules_requireid"><code>require(id)</code></a>
<ul>
<li><a href="#all_modules_requirecache"><code>require.cache</code></a></li>
<li><span class="stability_0"><a href="#all_modules_requireextensions"><code>require.extensions</code></a></span></li>
<li><a href="#all_modules_requiremain"><code>require.main</code></a></li>
<li><a href="#all_modules_requireresolverequest-options"><code>require.resolve(request[, options])</code></a>
<ul>
<li><a href="#all_modules_requireresolvepathsrequest"><code>require.resolve.paths(request)</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_modules_the-module-object">The <code>module</code> object</a>
<ul>
<li><a href="#all_modules_modulechildren"><code>module.children</code></a></li>
<li><a href="#all_modules_moduleexports"><code>module.exports</code></a>
<ul>
<li><a href="#all_modules_exports-shortcut"><code>exports</code> shortcut</a></li>
</ul>
</li>
<li><a href="#all_modules_modulefilename"><code>module.filename</code></a></li>
<li><a href="#all_modules_moduleid"><code>module.id</code></a></li>
<li><a href="#all_modules_moduleispreloading"><code>module.isPreloading</code></a></li>
<li><a href="#all_modules_moduleloaded"><code>module.loaded</code></a></li>
<li><span class="stability_0"><a href="#all_modules_moduleparent"><code>module.parent</code></a></span></li>
<li><a href="#all_modules_modulepath"><code>module.path</code></a></li>
<li><a href="#all_modules_modulepaths"><code>module.paths</code></a></li>
<li><a href="#all_modules_modulerequireid"><code>module.require(id)</code></a></li>
</ul>
</li>
<li><a href="#all_modules_the-module-object_1">The <code>Module</code> object</a></li>
<li><a href="#all_modules_source-map-v3-support">Source map v3 support</a></li>
</ul>
</li>
<li><a href="#all_esm_modules-ecmascript-modules">Modules: ECMAScript modules</a>
<ul>
<li><a href="#all_esm_introduction">Introduction</a></li>
<li><a href="#all_esm_enabling">Enabling</a></li>
<li><a href="#all_esm_packages">Packages</a></li>
<li><a href="#all_esm_import-specifiers"><code>import</code> Specifiers</a>
<ul>
<li><a href="#all_esm_terminology">Terminology</a></li>
<li><a href="#all_esm_mandatory-file-extensions">Mandatory file extensions</a></li>
<li><a href="#all_esm_urls">URLs</a>
<ul>
<li><a href="#all_esm_file-urls"><code>file:</code> URLs</a></li>
<li><a href="#all_esm_data-imports"><code>data:</code> imports</a></li>
<li><a href="#all_esm_node-imports"><code>node:</code> imports</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_esm_import-attributes">Import attributes</a></span></li>
<li><a href="#all_esm_built-in-modules">Built-in modules</a></li>
<li><a href="#all_esm_import-expressions"><code>import()</code> expressions</a></li>
<li><a href="#all_esm_importmeta"><code>import.meta</code></a>
<ul>
<li><span class="stability_1"><a href="#all_esm_importmetadirname"><code>import.meta.dirname</code></a></span></li>
<li><span class="stability_1"><a href="#all_esm_importmetafilename"><code>import.meta.filename</code></a></span></li>
<li><a href="#all_esm_importmetaurl"><code>import.meta.url</code></a></li>
<li><span class="stability_1"><a href="#all_esm_importmetaresolvespecifier"><code>import.meta.resolve(specifier)</code></a></span></li>
</ul>
</li>
<li><a href="#all_esm_interoperability-with-commonjs">Interoperability with CommonJS</a>
<ul>
<li><a href="#all_esm_import-statements"><code>import</code> statements</a></li>
<li><a href="#all_esm_require"><code>require</code></a></li>
<li><a href="#all_esm_commonjs-namespaces">CommonJS Namespaces</a></li>
<li><a href="#all_esm_differences-between-es-modules-and-commonjs">Differences between ES modules and CommonJS</a>
<ul>
<li><a href="#all_esm_no-require-exports-or-moduleexports">No <code>require</code>, <code>exports</code>, or <code>module.exports</code></a></li>
<li><a href="#all_esm_no-__filename-or-__dirname">No <code>__filename</code> or <code>__dirname</code></a></li>
<li><a href="#all_esm_no-addon-loading">No Addon Loading</a></li>
<li><a href="#all_esm_no-requireresolve">No <code>require.resolve</code></a></li>
<li><a href="#all_esm_no-node_path">No <code>NODE_PATH</code></a></li>
<li><a href="#all_esm_no-requireextensions">No <code>require.extensions</code></a></li>
<li><a href="#all_esm_no-requirecache">No <code>require.cache</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_esm_json-modules">JSON modules</a></span></li>
<li><span class="stability_1"><a href="#all_esm_wasm-modules">Wasm modules</a></span></li>
<li><a href="#all_esm_top-level-await">Top-level <code>await</code></a></li>
<li><span class="stability_1"><a href="#all_esm_https-and-http-imports">HTTPS and HTTP imports</a></span>
<ul>
<li><a href="#all_esm_imports-are-limited-to-http1">Imports are limited to HTTP/1</a></li>
<li><a href="#all_esm_http-is-limited-to-loopback-addresses">HTTP is limited to loopback addresses</a></li>
<li><a href="#all_esm_authentication-is-never-sent-to-the-destination-server">Authentication is never sent to the destination server.</a></li>
<li><a href="#all_esm_cors-is-never-checked-on-the-destination-server">CORS is never checked on the destination server</a></li>
<li><a href="#all_esm_cannot-load-non-network-dependencies">Cannot load non-network dependencies</a></li>
<li><a href="#all_esm_network-based-loading-is-not-enabled-by-default">Network-based loading is not enabled by default</a></li>
</ul>
</li>
<li><a href="#all_esm_loaders">Loaders</a></li>
<li><a href="#all_esm_resolution-and-loading-algorithm">Resolution and loading algorithm</a>
<ul>
<li><a href="#all_esm_features">Features</a></li>
<li><a href="#all_esm_resolution-algorithm">Resolution algorithm</a></li>
<li><a href="#all_esm_resolution-algorithm-specification">Resolution Algorithm Specification</a></li>
<li><a href="#all_esm_customizing-esm-specifier-resolution-algorithm">Customizing ESM specifier resolution algorithm</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_module_modules-nodemodule-api">Modules: <code>node:module</code> API</a>
<ul>
<li><a href="#all_module_the-module-object">The <code>Module</code> object</a>
<ul>
<li><a href="#all_module_modulebuiltinmodules"><code>module.builtinModules</code></a></li>
<li><a href="#all_module_modulecreaterequirefilename"><code>module.createRequire(filename)</code></a></li>
<li><a href="#all_module_moduleisbuiltinmodulename"><code>module.isBuiltin(moduleName)</code></a></li>
<li><span class="stability_1"><a href="#all_module_moduleregisterspecifier-parenturl-options"><code>module.register(specifier[, parentURL][, options])</code></a></span></li>
<li><a href="#all_module_modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_module_customization-hooks">Customization Hooks</a></span>
<ul>
<li><a href="#all_module_enabling">Enabling</a></li>
<li><a href="#all_module_chaining">Chaining</a></li>
<li><a href="#all_module_communication-with-module-customization-hooks">Communication with module customization hooks</a></li>
<li><a href="#all_module_hooks">Hooks</a>
<ul>
<li><span class="stability_1"><a href="#all_module_initialize"><code>initialize()</code></a></span></li>
<li><span class="stability_1"><a href="#all_module_resolvespecifier-context-nextresolve"><code>resolve(specifier, context, nextResolve)</code></a></span></li>
<li><span class="stability_1"><a href="#all_module_loadurl-context-nextload"><code>load(url, context, nextLoad)</code></a></span></li>
<li><span class="stability_1"><a href="#all_module_globalpreload"><code>globalPreload()</code></a></span></li>
</ul>
</li>
<li><a href="#all_module_examples">Examples</a>
<ul>
<li><a href="#all_module_import-from-https">Import from HTTPS</a></li>
<li><a href="#all_module_transpilation">Transpilation</a></li>
<li><a href="#all_module_import-maps">Import maps</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_module_source-map-v3-support">Source map v3 support</a></span>
<ul>
<li><a href="#all_module_modulefindsourcemappath"><code>module.findSourceMap(path)</code></a></li>
<li><a href="#all_module_class-modulesourcemap">Class: <code>module.SourceMap</code></a>
<ul>
<li><a href="#all_module_new-sourcemappayload--linelengths-"><code>new SourceMap(payload[, { lineLengths }])</code></a></li>
<li><a href="#all_module_sourcemappayload"><code>sourceMap.payload</code></a></li>
<li><a href="#all_module_sourcemapfindentrylineoffset-columnoffset"><code>sourceMap.findEntry(lineOffset, columnOffset)</code></a></li>
<li><a href="#all_module_sourcemapfindoriginlinenumber-columnnumber"><code>sourceMap.findOrigin(lineNumber, columnNumber)</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_packages_modules-packages">Modules: Packages</a>
<ul>
<li><a href="#all_packages_introduction">Introduction</a></li>
<li><a href="#all_packages_determining-module-system">Determining module system</a>
<ul>
<li><a href="#all_packages_introduction_1">Introduction</a></li>
<li><span class="stability_1"><a href="#all_packages_syntax-detection">Syntax detection</a></span></li>
<li><a href="#all_packages_modules-loaders">Modules loaders</a></li>
<li><a href="#all_packages_packagejson-and-file-extensions"><code>package.json</code> and file extensions</a></li>
<li><a href="#all_packages_--input-type-flag"><code>--input-type</code> flag</a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_packages_determining-package-manager">Determining package manager</a></span></li>
<li><a href="#all_packages_package-entry-points">Package entry points</a>
<ul>
<li><a href="#all_packages_main-entry-point-export">Main entry point export</a></li>
<li><a href="#all_packages_subpath-exports">Subpath exports</a>
<ul>
<li><a href="#all_packages_extensions-in-subpaths">Extensions in subpaths</a></li>
</ul>
</li>
<li><a href="#all_packages_exports-sugar">Exports sugar</a></li>
<li><a href="#all_packages_subpath-imports">Subpath imports</a></li>
<li><a href="#all_packages_subpath-patterns">Subpath patterns</a></li>
<li><a href="#all_packages_conditional-exports">Conditional exports</a></li>
<li><a href="#all_packages_nested-conditions">Nested conditions</a></li>
<li><a href="#all_packages_resolving-user-conditions">Resolving user conditions</a></li>
<li><a href="#all_packages_community-conditions-definitions">Community Conditions Definitions</a></li>
<li><a href="#all_packages_self-referencing-a-package-using-its-name">Self-referencing a package using its name</a></li>
</ul>
</li>
<li><a href="#all_packages_dual-commonjses-module-packages">Dual CommonJS/ES module packages</a></li>
<li><a href="#all_packages_nodejs-packagejson-field-definitions">Node.js <code>package.json</code> field definitions</a>
<ul>
<li><a href="#all_packages_name"><code>"name"</code></a></li>
<li><a href="#all_packages_main"><code>"main"</code></a></li>
<li><span class="stability_1"><a href="#all_packages_packagemanager"><code>"packageManager"</code></a></span></li>
<li><a href="#all_packages_type"><code>"type"</code></a></li>
<li><a href="#all_packages_exports"><code>"exports"</code></a></li>
<li><a href="#all_packages_imports"><code>"imports"</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_net_net">Net</a></span>
<ul>
<li><a href="#all_net_ipc-support">IPC support</a>
<ul>
<li><a href="#all_net_identifying-paths-for-ipc-connections">Identifying paths for IPC connections</a></li>
</ul>
</li>
<li><a href="#all_net_class-netblocklist">Class: <code>net.BlockList</code></a>
<ul>
<li><a href="#all_net_blocklistaddaddressaddress-type"><code>blockList.addAddress(address[, type])</code></a></li>
<li><a href="#all_net_blocklistaddrangestart-end-type"><code>blockList.addRange(start, end[, type])</code></a></li>
<li><a href="#all_net_blocklistaddsubnetnet-prefix-type"><code>blockList.addSubnet(net, prefix[, type])</code></a></li>
<li><a href="#all_net_blocklistcheckaddress-type"><code>blockList.check(address[, type])</code></a></li>
<li><a href="#all_net_blocklistrules"><code>blockList.rules</code></a></li>
</ul>
</li>
<li><a href="#all_net_class-netsocketaddress">Class: <code>net.SocketAddress</code></a>
<ul>
<li><a href="#all_net_new-netsocketaddressoptions"><code>new net.SocketAddress([options])</code></a></li>
<li><a href="#all_net_socketaddressaddress"><code>socketaddress.address</code></a></li>
<li><a href="#all_net_socketaddressfamily"><code>socketaddress.family</code></a></li>
<li><a href="#all_net_socketaddressflowlabel"><code>socketaddress.flowlabel</code></a></li>
<li><a href="#all_net_socketaddressport"><code>socketaddress.port</code></a></li>
</ul>
</li>
<li><a href="#all_net_class-netserver">Class: <code>net.Server</code></a>
<ul>
<li><a href="#all_net_new-netserveroptions-connectionlistener"><code>new net.Server([options][, connectionListener])</code></a></li>
<li><a href="#all_net_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_net_event-connection">Event: <code>'connection'</code></a></li>
<li><a href="#all_net_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_net_event-listening">Event: <code>'listening'</code></a></li>
<li><a href="#all_net_event-drop">Event: <code>'drop'</code></a></li>
<li><a href="#all_net_serveraddress"><code>server.address()</code></a></li>
<li><a href="#all_net_serverclosecallback"><code>server.close([callback])</code></a></li>
<li><span class="stability_1"><a href="#all_net_serversymbolasyncdispose"><code>server[Symbol.asyncDispose]()</code></a></span></li>
<li><a href="#all_net_servergetconnectionscallback"><code>server.getConnections(callback)</code></a></li>
<li><a href="#all_net_serverlisten"><code>server.listen()</code></a>
<ul>
<li><a href="#all_net_serverlistenhandle-backlog-callback"><code>server.listen(handle[, backlog][, callback])</code></a></li>
<li><a href="#all_net_serverlistenoptions-callback"><code>server.listen(options[, callback])</code></a></li>
<li><a href="#all_net_serverlistenpath-backlog-callback"><code>server.listen(path[, backlog][, callback])</code></a></li>
<li><a href="#all_net_serverlistenport-host-backlog-callback"><code>server.listen([port[, host[, backlog]]][, callback])</code></a></li>
</ul>
</li>
<li><a href="#all_net_serverlistening"><code>server.listening</code></a></li>
<li><a href="#all_net_servermaxconnections"><code>server.maxConnections</code></a></li>
<li><a href="#all_net_serverref"><code>server.ref()</code></a></li>
<li><a href="#all_net_serverunref"><code>server.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_net_class-netsocket">Class: <code>net.Socket</code></a>
<ul>
<li><a href="#all_net_new-netsocketoptions"><code>new net.Socket([options])</code></a></li>
<li><a href="#all_net_event-close_1">Event: <code>'close'</code></a></li>
<li><a href="#all_net_event-connect">Event: <code>'connect'</code></a></li>
<li><a href="#all_net_event-connectionattempt">Event: <code>'connectionAttempt'</code></a></li>
<li><a href="#all_net_event-connectionattemptfailed">Event: <code>'connectionAttemptFailed'</code></a></li>
<li><a href="#all_net_event-connectionattempttimeout">Event: <code>'connectionAttemptTimeout'</code></a></li>
<li><a href="#all_net_event-data">Event: <code>'data'</code></a></li>
<li><a href="#all_net_event-drain">Event: <code>'drain'</code></a></li>
<li><a href="#all_net_event-end">Event: <code>'end'</code></a></li>
<li><a href="#all_net_event-error_1">Event: <code>'error'</code></a></li>
<li><a href="#all_net_event-lookup">Event: <code>'lookup'</code></a></li>
<li><a href="#all_net_event-ready">Event: <code>'ready'</code></a></li>
<li><a href="#all_net_event-timeout">Event: <code>'timeout'</code></a></li>
<li><a href="#all_net_socketaddress"><code>socket.address()</code></a></li>
<li><a href="#all_net_socketautoselectfamilyattemptedaddresses"><code>socket.autoSelectFamilyAttemptedAddresses</code></a></li>
<li><span class="stability_0"><a href="#all_net_socketbuffersize"><code>socket.bufferSize</code></a></span></li>
<li><a href="#all_net_socketbytesread"><code>socket.bytesRead</code></a></li>
<li><a href="#all_net_socketbyteswritten"><code>socket.bytesWritten</code></a></li>
<li><a href="#all_net_socketconnect"><code>socket.connect()</code></a>
<ul>
<li><a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a></li>
<li><a href="#all_net_socketconnectpath-connectlistener"><code>socket.connect(path[, connectListener])</code></a></li>
<li><a href="#all_net_socketconnectport-host-connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a></li>
</ul>
</li>
<li><a href="#all_net_socketconnecting"><code>socket.connecting</code></a></li>
<li><a href="#all_net_socketdestroyerror"><code>socket.destroy([error])</code></a></li>
<li><a href="#all_net_socketdestroyed"><code>socket.destroyed</code></a></li>
<li><a href="#all_net_socketdestroysoon"><code>socket.destroySoon()</code></a></li>
<li><a href="#all_net_socketenddata-encoding-callback"><code>socket.end([data[, encoding]][, callback])</code></a></li>
<li><a href="#all_net_socketlocaladdress"><code>socket.localAddress</code></a></li>
<li><a href="#all_net_socketlocalport"><code>socket.localPort</code></a></li>
<li><a href="#all_net_socketlocalfamily"><code>socket.localFamily</code></a></li>
<li><a href="#all_net_socketpause"><code>socket.pause()</code></a></li>
<li><a href="#all_net_socketpending"><code>socket.pending</code></a></li>
<li><a href="#all_net_socketref"><code>socket.ref()</code></a></li>
<li><a href="#all_net_socketremoteaddress"><code>socket.remoteAddress</code></a></li>
<li><a href="#all_net_socketremotefamily"><code>socket.remoteFamily</code></a></li>
<li><a href="#all_net_socketremoteport"><code>socket.remotePort</code></a></li>
<li><a href="#all_net_socketresetanddestroy"><code>socket.resetAndDestroy()</code></a></li>
<li><a href="#all_net_socketresume"><code>socket.resume()</code></a></li>
<li><a href="#all_net_socketsetencodingencoding"><code>socket.setEncoding([encoding])</code></a></li>
<li><a href="#all_net_socketsetkeepaliveenable-initialdelay"><code>socket.setKeepAlive([enable][, initialDelay])</code></a></li>
<li><a href="#all_net_socketsetnodelaynodelay"><code>socket.setNoDelay([noDelay])</code></a></li>
<li><a href="#all_net_socketsettimeouttimeout-callback"><code>socket.setTimeout(timeout[, callback])</code></a></li>
<li><a href="#all_net_sockettimeout"><code>socket.timeout</code></a></li>
<li><a href="#all_net_socketunref"><code>socket.unref()</code></a></li>
<li><a href="#all_net_socketwritedata-encoding-callback"><code>socket.write(data[, encoding][, callback])</code></a></li>
<li><a href="#all_net_socketreadystate"><code>socket.readyState</code></a></li>
</ul>
</li>
<li><a href="#all_net_netconnect"><code>net.connect()</code></a>
<ul>
<li><a href="#all_net_netconnectoptions-connectlistener"><code>net.connect(options[, connectListener])</code></a></li>
<li><a href="#all_net_netconnectpath-connectlistener"><code>net.connect(path[, connectListener])</code></a></li>
<li><a href="#all_net_netconnectport-host-connectlistener"><code>net.connect(port[, host][, connectListener])</code></a></li>
</ul>
</li>
<li><a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a>
<ul>
<li><a href="#all_net_netcreateconnectionoptions-connectlistener"><code>net.createConnection(options[, connectListener])</code></a></li>
<li><a href="#all_net_netcreateconnectionpath-connectlistener"><code>net.createConnection(path[, connectListener])</code></a></li>
<li><a href="#all_net_netcreateconnectionport-host-connectlistener"><code>net.createConnection(port[, host][, connectListener])</code></a></li>
</ul>
</li>
<li><a href="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer([options][, connectionListener])</code></a></li>
<li><a href="#all_net_netgetdefaultautoselectfamily"><code>net.getDefaultAutoSelectFamily()</code></a></li>
<li><a href="#all_net_netsetdefaultautoselectfamilyvalue"><code>net.setDefaultAutoSelectFamily(value)</code></a></li>
<li><a href="#all_net_netgetdefaultautoselectfamilyattempttimeout"><code>net.getDefaultAutoSelectFamilyAttemptTimeout()</code></a></li>
<li><a href="#all_net_netsetdefaultautoselectfamilyattempttimeoutvalue"><code>net.setDefaultAutoSelectFamilyAttemptTimeout(value)</code></a></li>
<li><a href="#all_net_netisipinput"><code>net.isIP(input)</code></a></li>
<li><a href="#all_net_netisipv4input"><code>net.isIPv4(input)</code></a></li>
<li><a href="#all_net_netisipv6input"><code>net.isIPv6(input)</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_os_os">OS</a></span>
<ul>
<li><a href="#all_os_oseol"><code>os.EOL</code></a></li>
<li><a href="#all_os_osavailableparallelism"><code>os.availableParallelism()</code></a></li>
<li><a href="#all_os_osarch"><code>os.arch()</code></a></li>
<li><a href="#all_os_osconstants"><code>os.constants</code></a></li>
<li><a href="#all_os_oscpus"><code>os.cpus()</code></a></li>
<li><a href="#all_os_osdevnull"><code>os.devNull</code></a></li>
<li><a href="#all_os_osendianness"><code>os.endianness()</code></a></li>
<li><a href="#all_os_osfreemem"><code>os.freemem()</code></a></li>
<li><a href="#all_os_osgetprioritypid"><code>os.getPriority([pid])</code></a></li>
<li><a href="#all_os_oshomedir"><code>os.homedir()</code></a></li>
<li><a href="#all_os_oshostname"><code>os.hostname()</code></a></li>
<li><a href="#all_os_osloadavg"><code>os.loadavg()</code></a></li>
<li><a href="#all_os_osmachine"><code>os.machine()</code></a></li>
<li><a href="#all_os_osnetworkinterfaces"><code>os.networkInterfaces()</code></a></li>
<li><a href="#all_os_osplatform"><code>os.platform()</code></a></li>
<li><a href="#all_os_osrelease"><code>os.release()</code></a></li>
<li><a href="#all_os_ossetprioritypid-priority"><code>os.setPriority([pid, ]priority)</code></a></li>
<li><a href="#all_os_ostmpdir"><code>os.tmpdir()</code></a></li>
<li><a href="#all_os_ostotalmem"><code>os.totalmem()</code></a></li>
<li><a href="#all_os_ostype"><code>os.type()</code></a></li>
<li><a href="#all_os_osuptime"><code>os.uptime()</code></a></li>
<li><a href="#all_os_osuserinfooptions"><code>os.userInfo([options])</code></a></li>
<li><a href="#all_os_osversion"><code>os.version()</code></a></li>
<li><a href="#all_os_os-constants">OS constants</a>
<ul>
<li><a href="#all_os_signal-constants">Signal constants</a></li>
<li><a href="#all_os_error-constants">Error constants</a>
<ul>
<li><a href="#all_os_posix-error-constants">POSIX error constants</a></li>
<li><a href="#all_os_windows-specific-error-constants">Windows-specific error constants</a></li>
</ul>
</li>
<li><a href="#all_os_dlopen-constants">dlopen constants</a></li>
<li><a href="#all_os_priority-constants">Priority constants</a></li>
<li><a href="#all_os_libuv-constants">libuv constants</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_path_path">Path</a></span>
<ul>
<li><a href="#all_path_windows-vs-posix">Windows vs. POSIX</a></li>
<li><a href="#all_path_pathbasenamepath-suffix"><code>path.basename(path[, suffix])</code></a></li>
<li><a href="#all_path_pathdelimiter"><code>path.delimiter</code></a></li>
<li><a href="#all_path_pathdirnamepath"><code>path.dirname(path)</code></a></li>
<li><a href="#all_path_pathextnamepath"><code>path.extname(path)</code></a></li>
<li><a href="#all_path_pathformatpathobject"><code>path.format(pathObject)</code></a></li>
<li><span class="stability_1"><a href="#all_path_pathmatchesglobpath-pattern"><code>path.matchesGlob(path, pattern)</code></a></span></li>
<li><a href="#all_path_pathisabsolutepath"><code>path.isAbsolute(path)</code></a></li>
<li><a href="#all_path_pathjoinpaths"><code>path.join([...paths])</code></a></li>
<li><a href="#all_path_pathnormalizepath"><code>path.normalize(path)</code></a></li>
<li><a href="#all_path_pathparsepath"><code>path.parse(path)</code></a></li>
<li><a href="#all_path_pathposix"><code>path.posix</code></a></li>
<li><a href="#all_path_pathrelativefrom-to"><code>path.relative(from, to)</code></a></li>
<li><a href="#all_path_pathresolvepaths"><code>path.resolve([...paths])</code></a></li>
<li><a href="#all_path_pathsep"><code>path.sep</code></a></li>
<li><a href="#all_path_pathtonamespacedpathpath"><code>path.toNamespacedPath(path)</code></a></li>
<li><a href="#all_path_pathwin32"><code>path.win32</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_perf_hooks_performance-measurement-apis">Performance measurement APIs</a></span>
<ul>
<li><a href="#all_perf_hooks_perf_hooksperformance"><code>perf_hooks.performance</code></a>
<ul>
<li><a href="#all_perf_hooks_performanceclearmarksname"><code>performance.clearMarks([name])</code></a></li>
<li><a href="#all_perf_hooks_performanceclearmeasuresname"><code>performance.clearMeasures([name])</code></a></li>
<li><a href="#all_perf_hooks_performanceclearresourcetimingsname"><code>performance.clearResourceTimings([name])</code></a></li>
<li><a href="#all_perf_hooks_performanceeventlooputilizationutilization1-utilization2"><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code></a></li>
<li><a href="#all_perf_hooks_performancegetentries"><code>performance.getEntries()</code></a></li>
<li><a href="#all_perf_hooks_performancegetentriesbynamename-type"><code>performance.getEntriesByName(name[, type])</code></a></li>
<li><a href="#all_perf_hooks_performancegetentriesbytypetype"><code>performance.getEntriesByType(type)</code></a></li>
<li><a href="#all_perf_hooks_performancemarkname-options"><code>performance.mark(name[, options])</code></a></li>
<li><a href="#all_perf_hooks_performancemarkresourcetimingtiminginfo-requestedurl-initiatortype-global-cachemode"><code>performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode)</code></a></li>
<li><a href="#all_perf_hooks_performancemeasurename-startmarkoroptions-endmark"><code>performance.measure(name[, startMarkOrOptions[, endMark]])</code></a></li>
<li><a href="#all_perf_hooks_performancenodetiming"><code>performance.nodeTiming</code></a></li>
<li><a href="#all_perf_hooks_performancenow"><code>performance.now()</code></a></li>
<li><a href="#all_perf_hooks_performancesetresourcetimingbuffersizemaxsize"><code>performance.setResourceTimingBufferSize(maxSize)</code></a></li>
<li><a href="#all_perf_hooks_performancetimeorigin"><code>performance.timeOrigin</code></a></li>
<li><a href="#all_perf_hooks_performancetimerifyfn-options"><code>performance.timerify(fn[, options])</code></a></li>
<li><a href="#all_perf_hooks_performancetojson"><code>performance.toJSON()</code></a>
<ul>
<li><a href="#all_perf_hooks_event-resourcetimingbufferfull">Event: <code>'resourcetimingbufferfull'</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performanceentry">Class: <code>PerformanceEntry</code></a>
<ul>
<li><a href="#all_perf_hooks_performanceentryduration"><code>performanceEntry.duration</code></a></li>
<li><a href="#all_perf_hooks_performanceentryentrytype"><code>performanceEntry.entryType</code></a></li>
<li><a href="#all_perf_hooks_performanceentryname"><code>performanceEntry.name</code></a></li>
<li><a href="#all_perf_hooks_performanceentrystarttime"><code>performanceEntry.startTime</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performancemark">Class: <code>PerformanceMark</code></a>
<ul>
<li><a href="#all_perf_hooks_performancemarkdetail"><code>performanceMark.detail</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performancemeasure">Class: <code>PerformanceMeasure</code></a>
<ul>
<li><a href="#all_perf_hooks_performancemeasuredetail"><code>performanceMeasure.detail</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performancenodeentry">Class: <code>PerformanceNodeEntry</code></a>
<ul>
<li><a href="#all_perf_hooks_performancenodeentrydetail"><code>performanceNodeEntry.detail</code></a></li>
<li><span class="stability_0"><a href="#all_perf_hooks_performancenodeentryflags"><code>performanceNodeEntry.flags</code></a></span></li>
<li><span class="stability_0"><a href="#all_perf_hooks_performancenodeentrykind"><code>performanceNodeEntry.kind</code></a></span></li>
<li><a href="#all_perf_hooks_garbage-collection-gc-details">Garbage Collection ('gc') Details</a></li>
<li><a href="#all_perf_hooks_http-http-details">HTTP ('http') Details</a></li>
<li><a href="#all_perf_hooks_http2-http2-details">HTTP/2 ('http2') Details</a></li>
<li><a href="#all_perf_hooks_timerify-function-details">Timerify ('function') Details</a></li>
<li><a href="#all_perf_hooks_net-net-details">Net ('net') Details</a></li>
<li><a href="#all_perf_hooks_dns-dns-details">DNS ('dns') Details</a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performancenodetiming">Class: <code>PerformanceNodeTiming</code></a>
<ul>
<li><a href="#all_perf_hooks_performancenodetimingbootstrapcomplete"><code>performanceNodeTiming.bootstrapComplete</code></a></li>
<li><a href="#all_perf_hooks_performancenodetimingenvironment"><code>performanceNodeTiming.environment</code></a></li>
<li><a href="#all_perf_hooks_performancenodetimingidletime"><code>performanceNodeTiming.idleTime</code></a></li>
<li><a href="#all_perf_hooks_performancenodetimingloopexit"><code>performanceNodeTiming.loopExit</code></a></li>
<li><a href="#all_perf_hooks_performancenodetimingloopstart"><code>performanceNodeTiming.loopStart</code></a></li>
<li><a href="#all_perf_hooks_performancenodetimingnodestart"><code>performanceNodeTiming.nodeStart</code></a></li>
<li><a href="#all_perf_hooks_performancenodetiminguvmetricsinfo"><code>performanceNodeTiming.uvMetricsInfo</code></a></li>
<li><a href="#all_perf_hooks_performancenodetimingv8start"><code>performanceNodeTiming.v8Start</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performanceresourcetiming">Class: <code>PerformanceResourceTiming</code></a>
<ul>
<li><a href="#all_perf_hooks_performanceresourcetimingworkerstart"><code>performanceResourceTiming.workerStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingredirectstart"><code>performanceResourceTiming.redirectStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingredirectend"><code>performanceResourceTiming.redirectEnd</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingfetchstart"><code>performanceResourceTiming.fetchStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingdomainlookupstart"><code>performanceResourceTiming.domainLookupStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingdomainlookupend"><code>performanceResourceTiming.domainLookupEnd</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingconnectstart"><code>performanceResourceTiming.connectStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingconnectend"><code>performanceResourceTiming.connectEnd</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingsecureconnectionstart"><code>performanceResourceTiming.secureConnectionStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingrequeststart"><code>performanceResourceTiming.requestStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingresponseend"><code>performanceResourceTiming.responseEnd</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingtransfersize"><code>performanceResourceTiming.transferSize</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingencodedbodysize"><code>performanceResourceTiming.encodedBodySize</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingdecodedbodysize"><code>performanceResourceTiming.decodedBodySize</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingtojson"><code>performanceResourceTiming.toJSON()</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performanceobserver">Class: <code>PerformanceObserver</code></a>
<ul>
<li><a href="#all_perf_hooks_performanceobserversupportedentrytypes"><code>PerformanceObserver.supportedEntryTypes</code></a></li>
<li><a href="#all_perf_hooks_new-performanceobservercallback"><code>new PerformanceObserver(callback)</code></a></li>
<li><a href="#all_perf_hooks_performanceobserverdisconnect"><code>performanceObserver.disconnect()</code></a></li>
<li><a href="#all_perf_hooks_performanceobserverobserveoptions"><code>performanceObserver.observe(options)</code></a></li>
<li><a href="#all_perf_hooks_performanceobservertakerecords"><code>performanceObserver.takeRecords()</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performanceobserverentrylist">Class: <code>PerformanceObserverEntryList</code></a>
<ul>
<li><a href="#all_perf_hooks_performanceobserverentrylistgetentries"><code>performanceObserverEntryList.getEntries()</code></a></li>
<li><a href="#all_perf_hooks_performanceobserverentrylistgetentriesbynamename-type"><code>performanceObserverEntryList.getEntriesByName(name[, type])</code></a></li>
<li><a href="#all_perf_hooks_performanceobserverentrylistgetentriesbytypetype"><code>performanceObserverEntryList.getEntriesByType(type)</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_perf_hookscreatehistogramoptions"><code>perf_hooks.createHistogram([options])</code></a></li>
<li><a href="#all_perf_hooks_perf_hooksmonitoreventloopdelayoptions"><code>perf_hooks.monitorEventLoopDelay([options])</code></a></li>
<li><a href="#all_perf_hooks_class-histogram">Class: <code>Histogram</code></a>
<ul>
<li><a href="#all_perf_hooks_histogramcount"><code>histogram.count</code></a></li>
<li><a href="#all_perf_hooks_histogramcountbigint"><code>histogram.countBigInt</code></a></li>
<li><a href="#all_perf_hooks_histogramexceeds"><code>histogram.exceeds</code></a></li>
<li><a href="#all_perf_hooks_histogramexceedsbigint"><code>histogram.exceedsBigInt</code></a></li>
<li><a href="#all_perf_hooks_histogrammax"><code>histogram.max</code></a></li>
<li><a href="#all_perf_hooks_histogrammaxbigint"><code>histogram.maxBigInt</code></a></li>
<li><a href="#all_perf_hooks_histogrammean"><code>histogram.mean</code></a></li>
<li><a href="#all_perf_hooks_histogrammin"><code>histogram.min</code></a></li>
<li><a href="#all_perf_hooks_histogramminbigint"><code>histogram.minBigInt</code></a></li>
<li><a href="#all_perf_hooks_histogrampercentilepercentile"><code>histogram.percentile(percentile)</code></a></li>
<li><a href="#all_perf_hooks_histogrampercentilebigintpercentile"><code>histogram.percentileBigInt(percentile)</code></a></li>
<li><a href="#all_perf_hooks_histogrampercentiles"><code>histogram.percentiles</code></a></li>
<li><a href="#all_perf_hooks_histogrampercentilesbigint"><code>histogram.percentilesBigInt</code></a></li>
<li><a href="#all_perf_hooks_histogramreset"><code>histogram.reset()</code></a></li>
<li><a href="#all_perf_hooks_histogramstddev"><code>histogram.stddev</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-intervalhistogram-extends-histogram">Class: <code>IntervalHistogram extends Histogram</code></a>
<ul>
<li><a href="#all_perf_hooks_histogramdisable"><code>histogram.disable()</code></a></li>
<li><a href="#all_perf_hooks_histogramenable"><code>histogram.enable()</code></a></li>
<li><a href="#all_perf_hooks_cloning-an-intervalhistogram">Cloning an <code>IntervalHistogram</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-recordablehistogram-extends-histogram">Class: <code>RecordableHistogram extends Histogram</code></a>
<ul>
<li><a href="#all_perf_hooks_histogramaddother"><code>histogram.add(other)</code></a></li>
<li><a href="#all_perf_hooks_histogramrecordval"><code>histogram.record(val)</code></a></li>
<li><a href="#all_perf_hooks_histogramrecorddelta"><code>histogram.recordDelta()</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_examples">Examples</a>
<ul>
<li><a href="#all_perf_hooks_measuring-the-duration-of-async-operations">Measuring the duration of async operations</a></li>
<li><a href="#all_perf_hooks_measuring-how-long-it-takes-to-load-dependencies">Measuring how long it takes to load dependencies</a></li>
<li><a href="#all_perf_hooks_measuring-how-long-one-http-round-trip-takes">Measuring how long one HTTP round-trip takes</a></li>
<li><a href="#all_perf_hooks_measuring-how-long-the-netconnect-only-for-tcp-takes-when-the-connection-is-successful">Measuring how long the <code>net.connect</code> (only for TCP) takes when the connection is successful</a></li>
<li><a href="#all_perf_hooks_measuring-how-long-the-dns-takes-when-the-request-is-successful">Measuring how long the DNS takes when the request is successful</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_permissions_permissions">Permissions</a>
<ul>
<li><a href="#all_permissions_module-based-permissions">Module-based permissions</a>
<ul>
<li><span class="stability_0"><a href="#all_permissions_policies">Policies</a></span>
<ul>
<li><a href="#all_permissions_enabling">Enabling</a></li>
<li><a href="#all_permissions_features">Features</a>
<ul>
<li><a href="#all_permissions_error-behavior">Error behavior</a></li>
<li><a href="#all_permissions_integrity-checks">Integrity checks</a></li>
<li><a href="#all_permissions_dependency-redirection">Dependency redirection</a></li>
<li><a href="#all_permissions_example-patched-dependency">Example: Patched dependency</a></li>
</ul>
</li>
<li><a href="#all_permissions_scopes">Scopes</a>
<ul>
<li><a href="#all_permissions_example">Example</a></li>
<li><a href="#all_permissions_integrity-using-scopes">Integrity using scopes</a></li>
<li><a href="#all_permissions_dependency-redirection-using-scopes">Dependency redirection using scopes</a></li>
<li><a href="#all_permissions_example-import-maps-emulation">Example: import maps emulation</a></li>
</ul>
</li>
<li><a href="#all_permissions_guarantees">Guarantees</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_permissions_process-based-permissions">Process-based permissions</a>
<ul>
<li><span class="stability_1"><a href="#all_permissions_permission-model">Permission Model</a></span>
<ul>
<li><a href="#all_permissions_runtime-api">Runtime API</a>
<ul>
<li><a href="#all_permissions_permissionhasscope-reference"><code>permission.has(scope[, reference])</code></a></li>
</ul>
</li>
<li><a href="#all_permissions_file-system-permissions">File System Permissions</a></li>
<li><a href="#all_permissions_permission-model-constraints">Permission Model constraints</a></li>
<li><a href="#all_permissions_limitations-and-known-issues">Limitations and Known Issues</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_process_process">Process</a>
<ul>
<li><a href="#all_process_process-events">Process events</a>
<ul>
<li><a href="#all_process_event-beforeexit">Event: <code>'beforeExit'</code></a></li>
<li><a href="#all_process_event-disconnect">Event: <code>'disconnect'</code></a></li>
<li><a href="#all_process_event-exit">Event: <code>'exit'</code></a></li>
<li><a href="#all_process_event-message">Event: <code>'message'</code></a></li>
<li><span class="stability_0"><a href="#all_process_event-multipleresolves">Event: <code>'multipleResolves'</code></a></span></li>
<li><a href="#all_process_event-rejectionhandled">Event: <code>'rejectionHandled'</code></a></li>
<li><a href="#all_process_event-workermessage">Event: <code>'workerMessage'</code></a></li>
<li><a href="#all_process_event-uncaughtexception">Event: <code>'uncaughtException'</code></a>
<ul>
<li><a href="#all_process_warning-using-uncaughtexception-correctly">Warning: Using <code>'uncaughtException'</code> correctly</a></li>
</ul>
</li>
<li><a href="#all_process_event-uncaughtexceptionmonitor">Event: <code>'uncaughtExceptionMonitor'</code></a></li>
<li><a href="#all_process_event-unhandledrejection">Event: <code>'unhandledRejection'</code></a></li>
<li><a href="#all_process_event-warning">Event: <code>'warning'</code></a>
<ul>
<li><a href="#all_process_emitting-custom-warnings">Emitting custom warnings</a></li>
<li><a href="#all_process_nodejs-warning-names">Node.js warning names</a></li>
</ul>
</li>
<li><a href="#all_process_event-worker">Event: <code>'worker'</code></a></li>
<li><a href="#all_process_signal-events">Signal events</a></li>
</ul>
</li>
<li><a href="#all_process_processabort"><code>process.abort()</code></a></li>
<li><a href="#all_process_processallowednodeenvironmentflags"><code>process.allowedNodeEnvironmentFlags</code></a></li>
<li><a href="#all_process_processarch"><code>process.arch</code></a></li>
<li><a href="#all_process_processargv"><code>process.argv</code></a></li>
<li><a href="#all_process_processargv0"><code>process.argv0</code></a></li>
<li><a href="#all_process_processchannel"><code>process.channel</code></a>
<ul>
<li><a href="#all_process_processchannelref"><code>process.channel.ref()</code></a></li>
<li><a href="#all_process_processchannelunref"><code>process.channel.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_process_processchdirdirectory"><code>process.chdir(directory)</code></a></li>
<li><a href="#all_process_processconfig"><code>process.config</code></a></li>
<li><a href="#all_process_processconnected"><code>process.connected</code></a></li>
<li><span class="stability_1"><a href="#all_process_processconstrainedmemory"><code>process.constrainedMemory()</code></a></span></li>
<li><span class="stability_1"><a href="#all_process_processavailablememory"><code>process.availableMemory()</code></a></span></li>
<li><a href="#all_process_processcpuusagepreviousvalue"><code>process.cpuUsage([previousValue])</code></a></li>
<li><a href="#all_process_processcwd"><code>process.cwd()</code></a></li>
<li><a href="#all_process_processdebugport"><code>process.debugPort</code></a></li>
<li><a href="#all_process_processdisconnect"><code>process.disconnect()</code></a></li>
<li><a href="#all_process_processdlopenmodule-filename-flags"><code>process.dlopen(module, filename[, flags])</code></a></li>
<li><a href="#all_process_processemitwarningwarning-options"><code>process.emitWarning(warning[, options])</code></a></li>
<li><a href="#all_process_processemitwarningwarning-type-code-ctor"><code>process.emitWarning(warning[, type[, code]][, ctor])</code></a>
<ul>
<li><a href="#all_process_avoiding-duplicate-warnings">Avoiding duplicate warnings</a></li>
</ul>
</li>
<li><a href="#all_process_processenv"><code>process.env</code></a></li>
<li><a href="#all_process_processexecargv"><code>process.execArgv</code></a></li>
<li><a href="#all_process_processexecpath"><code>process.execPath</code></a></li>
<li><a href="#all_process_processexitcode"><code>process.exit([code])</code></a></li>
<li><a href="#all_process_processexitcode_1"><code>process.exitCode</code></a></li>
<li><a href="#all_process_processfeaturescached_builtins"><code>process.features.cached_builtins</code></a></li>
<li><a href="#all_process_processfeaturesdebug"><code>process.features.debug</code></a></li>
<li><a href="#all_process_processfeaturesinspector"><code>process.features.inspector</code></a></li>
<li><a href="#all_process_processfeaturesipv6"><code>process.features.ipv6</code></a></li>
<li><a href="#all_process_processfeaturesrequire_module"><code>process.features.require_module</code></a></li>
<li><a href="#all_process_processfeaturestls"><code>process.features.tls</code></a></li>
<li><a href="#all_process_processfeaturestls_alpn"><code>process.features.tls_alpn</code></a></li>
<li><a href="#all_process_processfeaturestls_ocsp"><code>process.features.tls_ocsp</code></a></li>
<li><a href="#all_process_processfeaturestls_sni"><code>process.features.tls_sni</code></a></li>
<li><a href="#all_process_processfeaturesuv"><code>process.features.uv</code></a></li>
<li><span class="stability_1"><a href="#all_process_processgetactiveresourcesinfo"><code>process.getActiveResourcesInfo()</code></a></span></li>
<li><a href="#all_process_processgetbuiltinmoduleid"><code>process.getBuiltinModule(id)</code></a></li>
<li><a href="#all_process_processgetegid"><code>process.getegid()</code></a></li>
<li><a href="#all_process_processgeteuid"><code>process.geteuid()</code></a></li>
<li><a href="#all_process_processgetgid"><code>process.getgid()</code></a></li>
<li><a href="#all_process_processgetgroups"><code>process.getgroups()</code></a></li>
<li><a href="#all_process_processgetuid"><code>process.getuid()</code></a></li>
<li><a href="#all_process_processhasuncaughtexceptioncapturecallback"><code>process.hasUncaughtExceptionCaptureCallback()</code></a></li>
<li><span class="stability_3"><a href="#all_process_processhrtimetime"><code>process.hrtime([time])</code></a></span></li>
<li><a href="#all_process_processhrtimebigint"><code>process.hrtime.bigint()</code></a></li>
<li><a href="#all_process_processinitgroupsuser-extragroup"><code>process.initgroups(user, extraGroup)</code></a></li>
<li><a href="#all_process_processkillpid-signal"><code>process.kill(pid[, signal])</code></a></li>
<li><span class="stability_1"><a href="#all_process_processloadenvfilepath"><code>process.loadEnvFile(path)</code></a></span></li>
<li><span class="stability_0"><a href="#all_process_processmainmodule"><code>process.mainModule</code></a></span></li>
<li><a href="#all_process_processmemoryusage"><code>process.memoryUsage()</code></a></li>
<li><a href="#all_process_processmemoryusagerss"><code>process.memoryUsage.rss()</code></a></li>
<li><span class="stability_3"><a href="#all_process_processnexttickcallback-args"><code>process.nextTick(callback[, ...args])</code></a></span>
<ul>
<li><a href="#all_process_when-to-use-queuemicrotask-vs-processnexttick">When to use <code>queueMicrotask()</code> vs. <code>process.nextTick()</code></a></li>
</ul>
</li>
<li><a href="#all_process_processnodeprecation"><code>process.noDeprecation</code></a></li>
<li><a href="#all_process_processpermission"><code>process.permission</code></a>
<ul>
<li><a href="#all_process_processpermissionhasscope-reference"><code>process.permission.has(scope[, reference])</code></a></li>
</ul>
</li>
<li><a href="#all_process_processpid"><code>process.pid</code></a></li>
<li><a href="#all_process_processplatform"><code>process.platform</code></a></li>
<li><a href="#all_process_processppid"><code>process.ppid</code></a></li>
<li><a href="#all_process_processrelease"><code>process.release</code></a></li>
<li><a href="#all_process_processreport"><code>process.report</code></a>
<ul>
<li><a href="#all_process_processreportcompact"><code>process.report.compact</code></a></li>
<li><a href="#all_process_processreportdirectory"><code>process.report.directory</code></a></li>
<li><a href="#all_process_processreportfilename"><code>process.report.filename</code></a></li>
<li><a href="#all_process_processreportgetreporterr"><code>process.report.getReport([err])</code></a></li>
<li><a href="#all_process_processreportreportonfatalerror"><code>process.report.reportOnFatalError</code></a></li>
<li><a href="#all_process_processreportreportonsignal"><code>process.report.reportOnSignal</code></a></li>
<li><a href="#all_process_processreportreportonuncaughtexception"><code>process.report.reportOnUncaughtException</code></a></li>
<li><a href="#all_process_processreportsignal"><code>process.report.signal</code></a></li>
<li><a href="#all_process_processreportwritereportfilename-err"><code>process.report.writeReport([filename][, err])</code></a></li>
</ul>
</li>
<li><a href="#all_process_processresourceusage"><code>process.resourceUsage()</code></a></li>
<li><a href="#all_process_processsendmessage-sendhandle-options-callback"><code>process.send(message[, sendHandle[, options]][, callback])</code></a></li>
<li><a href="#all_process_processsetegidid"><code>process.setegid(id)</code></a></li>
<li><a href="#all_process_processseteuidid"><code>process.seteuid(id)</code></a></li>
<li><a href="#all_process_processsetgidid"><code>process.setgid(id)</code></a></li>
<li><a href="#all_process_processsetgroupsgroups"><code>process.setgroups(groups)</code></a></li>
<li><a href="#all_process_processsetuidid"><code>process.setuid(id)</code></a></li>
<li><span class="stability_1"><a href="#all_process_processsetsourcemapsenabledval"><code>process.setSourceMapsEnabled(val)</code></a></span></li>
<li><a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback(fn)</code></a></li>
<li><span class="stability_1"><a href="#all_process_processsourcemapsenabled"><code>process.sourceMapsEnabled</code></a></span></li>
<li><a href="#all_process_processstderr"><code>process.stderr</code></a>
<ul>
<li><a href="#all_process_processstderrfd"><code>process.stderr.fd</code></a></li>
</ul>
</li>
<li><a href="#all_process_processstdin"><code>process.stdin</code></a>
<ul>
<li><a href="#all_process_processstdinfd"><code>process.stdin.fd</code></a></li>
</ul>
</li>
<li><a href="#all_process_processstdout"><code>process.stdout</code></a>
<ul>
<li><a href="#all_process_processstdoutfd"><code>process.stdout.fd</code></a></li>
<li><a href="#all_process_a-note-on-process-io">A note on process I/O</a></li>
</ul>
</li>
<li><a href="#all_process_processthrowdeprecation"><code>process.throwDeprecation</code></a></li>
<li><a href="#all_process_processtitle"><code>process.title</code></a></li>
<li><a href="#all_process_processtracedeprecation"><code>process.traceDeprecation</code></a></li>
<li><span class="stability_0"><a href="#all_process_processumask"><code>process.umask()</code></a></span></li>
<li><a href="#all_process_processumaskmask"><code>process.umask(mask)</code></a></li>
<li><a href="#all_process_processuptime"><code>process.uptime()</code></a></li>
<li><a href="#all_process_processversion"><code>process.version</code></a></li>
<li><a href="#all_process_processversions"><code>process.versions</code></a></li>
<li><a href="#all_process_exit-codes">Exit codes</a></li>
</ul>
</li>
<li><span class="stability_0"><a href="#all_punycode_punycode">Punycode</a></span>
<ul>
<li><a href="#all_punycode_punycodedecodestring"><code>punycode.decode(string)</code></a></li>
<li><a href="#all_punycode_punycodeencodestring"><code>punycode.encode(string)</code></a></li>
<li><a href="#all_punycode_punycodetoasciidomain"><code>punycode.toASCII(domain)</code></a></li>
<li><a href="#all_punycode_punycodetounicodedomain"><code>punycode.toUnicode(domain)</code></a></li>
<li><a href="#all_punycode_punycodeucs2"><code>punycode.ucs2</code></a>
<ul>
<li><a href="#all_punycode_punycodeucs2decodestring"><code>punycode.ucs2.decode(string)</code></a></li>
<li><a href="#all_punycode_punycodeucs2encodecodepoints"><code>punycode.ucs2.encode(codePoints)</code></a></li>
</ul>
</li>
<li><a href="#all_punycode_punycodeversion"><code>punycode.version</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_querystring_query-string">Query string</a></span>
<ul>
<li><a href="#all_querystring_querystringdecode"><code>querystring.decode()</code></a></li>
<li><a href="#all_querystring_querystringencode"><code>querystring.encode()</code></a></li>
<li><a href="#all_querystring_querystringescapestr"><code>querystring.escape(str)</code></a></li>
<li><a href="#all_querystring_querystringparsestr-sep-eq-options"><code>querystring.parse(str[, sep[, eq[, options]]])</code></a></li>
<li><a href="#all_querystring_querystringstringifyobj-sep-eq-options"><code>querystring.stringify(obj[, sep[, eq[, options]]])</code></a></li>
<li><a href="#all_querystring_querystringunescapestr"><code>querystring.unescape(str)</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_readline_readline">Readline</a></span>
<ul>
<li><a href="#all_readline_class-interfaceconstructor">Class: <code>InterfaceConstructor</code></a>
<ul>
<li><a href="#all_readline_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_readline_event-line">Event: <code>'line'</code></a></li>
<li><a href="#all_readline_event-history">Event: <code>'history'</code></a></li>
<li><a href="#all_readline_event-pause">Event: <code>'pause'</code></a></li>
<li><a href="#all_readline_event-resume">Event: <code>'resume'</code></a></li>
<li><a href="#all_readline_event-sigcont">Event: <code>'SIGCONT'</code></a></li>
<li><a href="#all_readline_event-sigint">Event: <code>'SIGINT'</code></a></li>
<li><a href="#all_readline_event-sigtstp">Event: <code>'SIGTSTP'</code></a></li>
<li><a href="#all_readline_rlclose"><code>rl.close()</code></a></li>
<li><a href="#all_readline_rlpause"><code>rl.pause()</code></a></li>
<li><a href="#all_readline_rlpromptpreservecursor"><code>rl.prompt([preserveCursor])</code></a></li>
<li><a href="#all_readline_rlresume"><code>rl.resume()</code></a></li>
<li><a href="#all_readline_rlsetpromptprompt"><code>rl.setPrompt(prompt)</code></a></li>
<li><a href="#all_readline_rlgetprompt"><code>rl.getPrompt()</code></a></li>
<li><a href="#all_readline_rlwritedata-key"><code>rl.write(data[, key])</code></a></li>
<li><a href="#all_readline_rlsymbolasynciterator"><code>rl[Symbol.asyncIterator]()</code></a></li>
<li><a href="#all_readline_rlline"><code>rl.line</code></a></li>
<li><a href="#all_readline_rlcursor"><code>rl.cursor</code></a></li>
<li><a href="#all_readline_rlgetcursorpos"><code>rl.getCursorPos()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_readline_promises-api">Promises API</a></span>
<ul>
<li><a href="#all_readline_class-readlinepromisesinterface">Class: <code>readlinePromises.Interface</code></a>
<ul>
<li><a href="#all_readline_rlquestionquery-options"><code>rl.question(query[, options])</code></a></li>
</ul>
</li>
<li><a href="#all_readline_class-readlinepromisesreadline">Class: <code>readlinePromises.Readline</code></a>
<ul>
<li><a href="#all_readline_new-readlinepromisesreadlinestream-options"><code>new readlinePromises.Readline(stream[, options])</code></a></li>
<li><a href="#all_readline_rlclearlinedir"><code>rl.clearLine(dir)</code></a></li>
<li><a href="#all_readline_rlclearscreendown"><code>rl.clearScreenDown()</code></a></li>
<li><a href="#all_readline_rlcommit"><code>rl.commit()</code></a></li>
<li><a href="#all_readline_rlcursortox-y"><code>rl.cursorTo(x[, y])</code></a></li>
<li><a href="#all_readline_rlmovecursordx-dy"><code>rl.moveCursor(dx, dy)</code></a></li>
<li><a href="#all_readline_rlrollback"><code>rl.rollback()</code></a></li>
</ul>
</li>
<li><a href="#all_readline_readlinepromisescreateinterfaceoptions"><code>readlinePromises.createInterface(options)</code></a>
<ul>
<li><a href="#all_readline_use-of-the-completer-function">Use of the <code>completer</code> function</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_readline_callback-api">Callback API</a>
<ul>
<li><a href="#all_readline_class-readlineinterface">Class: <code>readline.Interface</code></a>
<ul>
<li><a href="#all_readline_rlquestionquery-options-callback"><code>rl.question(query[, options], callback)</code></a></li>
</ul>
</li>
<li><a href="#all_readline_readlineclearlinestream-dir-callback"><code>readline.clearLine(stream, dir[, callback])</code></a></li>
<li><a href="#all_readline_readlineclearscreendownstream-callback"><code>readline.clearScreenDown(stream[, callback])</code></a></li>
<li><a href="#all_readline_readlinecreateinterfaceoptions"><code>readline.createInterface(options)</code></a>
<ul>
<li><a href="#all_readline_use-of-the-completer-function_1">Use of the <code>completer</code> function</a></li>
</ul>
</li>
<li><a href="#all_readline_readlinecursortostream-x-y-callback"><code>readline.cursorTo(stream, x[, y][, callback])</code></a></li>
<li><a href="#all_readline_readlinemovecursorstream-dx-dy-callback"><code>readline.moveCursor(stream, dx, dy[, callback])</code></a></li>
</ul>
</li>
<li><a href="#all_readline_readlineemitkeypresseventsstream-interface"><code>readline.emitKeypressEvents(stream[, interface])</code></a></li>
<li><a href="#all_readline_example-tiny-cli">Example: Tiny CLI</a></li>
<li><a href="#all_readline_example-read-file-stream-line-by-line">Example: Read file stream line-by-Line</a></li>
<li><a href="#all_readline_tty-keybindings">TTY keybindings</a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_repl_repl">REPL</a></span>
<ul>
<li><a href="#all_repl_design-and-features">Design and features</a>
<ul>
<li><a href="#all_repl_commands-and-special-keys">Commands and special keys</a></li>
<li><a href="#all_repl_default-evaluation">Default evaluation</a>
<ul>
<li><a href="#all_repl_javascript-expressions">JavaScript expressions</a></li>
<li><a href="#all_repl_global-and-local-scope">Global and local scope</a></li>
<li><a href="#all_repl_accessing-core-nodejs-modules">Accessing core Node.js modules</a></li>
<li><a href="#all_repl_global-uncaught-exceptions">Global uncaught exceptions</a></li>
<li><a href="#all_repl_assignment-of-the-_-underscore-variable">Assignment of the <code>_</code> (underscore) variable</a></li>
<li><a href="#all_repl_await-keyword"><code>await</code> keyword</a></li>
</ul>
</li>
<li><a href="#all_repl_reverse-i-search">Reverse-i-search</a></li>
<li><a href="#all_repl_custom-evaluation-functions">Custom evaluation functions</a>
<ul>
<li><a href="#all_repl_recoverable-errors">Recoverable errors</a></li>
</ul>
</li>
<li><a href="#all_repl_customizing-repl-output">Customizing REPL output</a></li>
</ul>
</li>
<li><a href="#all_repl_class-replserver">Class: <code>REPLServer</code></a>
<ul>
<li><a href="#all_repl_event-exit">Event: <code>'exit'</code></a></li>
<li><a href="#all_repl_event-reset">Event: <code>'reset'</code></a></li>
<li><a href="#all_repl_replserverdefinecommandkeyword-cmd"><code>replServer.defineCommand(keyword, cmd)</code></a></li>
<li><a href="#all_repl_replserverdisplaypromptpreservecursor"><code>replServer.displayPrompt([preserveCursor])</code></a></li>
<li><a href="#all_repl_replserverclearbufferedcommand"><code>replServer.clearBufferedCommand()</code></a></li>
<li><a href="#all_repl_replserversetuphistoryhistorypath-callback"><code>replServer.setupHistory(historyPath, callback)</code></a></li>
</ul>
</li>
<li><a href="#all_repl_replbuiltinmodules"><code>repl.builtinModules</code></a></li>
<li><a href="#all_repl_replstartoptions"><code>repl.start([options])</code></a></li>
<li><a href="#all_repl_the-nodejs-repl">The Node.js REPL</a>
<ul>
<li><a href="#all_repl_environment-variable-options">Environment variable options</a></li>
<li><a href="#all_repl_persistent-history">Persistent history</a></li>
<li><a href="#all_repl_using-the-nodejs-repl-with-advanced-line-editors">Using the Node.js REPL with advanced line-editors</a></li>
<li><a href="#all_repl_starting-multiple-repl-instances-against-a-single-running-instance">Starting multiple REPL instances against a single running instance</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_report_diagnostic-report">Diagnostic report</a></span>
<ul>
<li><a href="#all_report_usage">Usage</a></li>
<li><a href="#all_report_configuration">Configuration</a></li>
<li><a href="#all_report_interaction-with-workers">Interaction with workers</a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_single-executable-applications_single-executable-applications">Single executable applications</a></span>
<ul>
<li><a href="#all_single-executable-applications_generating-single-executable-preparation-blobs">Generating single executable preparation blobs</a>
<ul>
<li><a href="#all_single-executable-applications_assets">Assets</a></li>
<li><a href="#all_single-executable-applications_startup-snapshot-support">Startup snapshot support</a></li>
<li><a href="#all_single-executable-applications_v8-code-cache-support">V8 code cache support</a></li>
</ul>
</li>
<li><a href="#all_single-executable-applications_in-the-injected-main-script">In the injected main script</a>
<ul>
<li><a href="#all_single-executable-applications_single-executable-application-api">Single-executable application API</a>
<ul>
<li><a href="#all_single-executable-applications_seaissea"><code>sea.isSea()</code></a></li>
</ul>
</li>
<li><a href="#all_single-executable-applications_seagetassetkey-encoding"><code>sea.getAsset(key[, encoding])</code></a></li>
<li><a href="#all_single-executable-applications_seagetassetasblobkey-options"><code>sea.getAssetAsBlob(key[, options])</code></a></li>
<li><a href="#all_single-executable-applications_seagetrawassetkey"><code>sea.getRawAsset(key)</code></a></li>
<li><a href="#all_single-executable-applications_requireid-in-the-injected-main-script-is-not-file-based"><code>require(id)</code> in the injected main script is not file based</a></li>
<li><a href="#all_single-executable-applications___filename-and-modulefilename-in-the-injected-main-script"><code>__filename</code> and <code>module.filename</code> in the injected main script</a></li>
<li><a href="#all_single-executable-applications___dirname-in-the-injected-main-script"><code>__dirname</code> in the injected main script</a></li>
</ul>
</li>
<li><a href="#all_single-executable-applications_notes">Notes</a>
<ul>
<li><a href="#all_single-executable-applications_single-executable-application-creation-process">Single executable application creation process</a></li>
<li><a href="#all_single-executable-applications_platform-support">Platform support</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_stream_stream">Stream</a></span>
<ul>
<li><a href="#all_stream_organization-of-this-document">Organization of this document</a></li>
<li><a href="#all_stream_types-of-streams">Types of streams</a>
<ul>
<li><a href="#all_stream_streams-promises-api">Streams Promises API</a></li>
<li><a href="#all_stream_streampipelinesource-transforms-destination-options"><code>stream.pipeline(source[, ...transforms], destination[, options])</code></a></li>
<li><a href="#all_stream_streampipelinestreams-options"><code>stream.pipeline(streams[, options])</code></a></li>
<li><a href="#all_stream_streamfinishedstream-options"><code>stream.finished(stream[, options])</code></a></li>
<li><a href="#all_stream_object-mode">Object mode</a></li>
<li><a href="#all_stream_buffering">Buffering</a></li>
</ul>
</li>
<li><a href="#all_stream_api-for-stream-consumers">API for stream consumers</a>
<ul>
<li><a href="#all_stream_writable-streams">Writable streams</a>
<ul>
<li><a href="#all_stream_class-streamwritable">Class: <code>stream.Writable</code></a>
<ul>
<li><a href="#all_stream_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_stream_event-drain">Event: <code>'drain'</code></a></li>
<li><a href="#all_stream_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_stream_event-finish">Event: <code>'finish'</code></a></li>
<li><a href="#all_stream_event-pipe">Event: <code>'pipe'</code></a></li>
<li><a href="#all_stream_event-unpipe">Event: <code>'unpipe'</code></a></li>
<li><a href="#all_stream_writablecork"><code>writable.cork()</code></a></li>
<li><a href="#all_stream_writabledestroyerror"><code>writable.destroy([error])</code></a></li>
<li><a href="#all_stream_writableclosed"><code>writable.closed</code></a></li>
<li><a href="#all_stream_writabledestroyed"><code>writable.destroyed</code></a></li>
<li><a href="#all_stream_writableendchunk-encoding-callback"><code>writable.end([chunk[, encoding]][, callback])</code></a></li>
<li><a href="#all_stream_writablesetdefaultencodingencoding"><code>writable.setDefaultEncoding(encoding)</code></a></li>
<li><a href="#all_stream_writableuncork"><code>writable.uncork()</code></a></li>
<li><a href="#all_stream_writablewritable"><code>writable.writable</code></a></li>
<li><span class="stability_1"><a href="#all_stream_writablewritableaborted"><code>writable.writableAborted</code></a></span></li>
<li><a href="#all_stream_writablewritableended"><code>writable.writableEnded</code></a></li>
<li><a href="#all_stream_writablewritablecorked"><code>writable.writableCorked</code></a></li>
<li><a href="#all_stream_writableerrored"><code>writable.errored</code></a></li>
<li><a href="#all_stream_writablewritablefinished"><code>writable.writableFinished</code></a></li>
<li><a href="#all_stream_writablewritablehighwatermark"><code>writable.writableHighWaterMark</code></a></li>
<li><a href="#all_stream_writablewritablelength"><code>writable.writableLength</code></a></li>
<li><a href="#all_stream_writablewritableneeddrain"><code>writable.writableNeedDrain</code></a></li>
<li><a href="#all_stream_writablewritableobjectmode"><code>writable.writableObjectMode</code></a></li>
<li><span class="stability_1"><a href="#all_stream_writablesymbolasyncdispose"><code>writable[Symbol.asyncDispose]()</code></a></span></li>
<li><a href="#all_stream_writablewritechunk-encoding-callback"><code>writable.write(chunk[, encoding][, callback])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_stream_readable-streams">Readable streams</a>
<ul>
<li><a href="#all_stream_two-reading-modes">Two reading modes</a></li>
<li><a href="#all_stream_three-states">Three states</a></li>
<li><a href="#all_stream_choose-one-api-style">Choose one API style</a></li>
<li><a href="#all_stream_class-streamreadable">Class: <code>stream.Readable</code></a>
<ul>
<li><a href="#all_stream_event-close_1">Event: <code>'close'</code></a></li>
<li><a href="#all_stream_event-data">Event: <code>'data'</code></a></li>
<li><a href="#all_stream_event-end">Event: <code>'end'</code></a></li>
<li><a href="#all_stream_event-error_1">Event: <code>'error'</code></a></li>
<li><a href="#all_stream_event-pause">Event: <code>'pause'</code></a></li>
<li><a href="#all_stream_event-readable">Event: <code>'readable'</code></a></li>
<li><a href="#all_stream_event-resume">Event: <code>'resume'</code></a></li>
<li><a href="#all_stream_readabledestroyerror"><code>readable.destroy([error])</code></a></li>
<li><a href="#all_stream_readableclosed"><code>readable.closed</code></a></li>
<li><a href="#all_stream_readabledestroyed"><code>readable.destroyed</code></a></li>
<li><a href="#all_stream_readableispaused"><code>readable.isPaused()</code></a></li>
<li><a href="#all_stream_readablepause"><code>readable.pause()</code></a></li>
<li><a href="#all_stream_readablepipedestination-options"><code>readable.pipe(destination[, options])</code></a></li>
<li><a href="#all_stream_readablereadsize"><code>readable.read([size])</code></a></li>
<li><a href="#all_stream_readablereadable"><code>readable.readable</code></a></li>
<li><span class="stability_1"><a href="#all_stream_readablereadableaborted"><code>readable.readableAborted</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablereadabledidread"><code>readable.readableDidRead</code></a></span></li>
<li><a href="#all_stream_readablereadableencoding"><code>readable.readableEncoding</code></a></li>
<li><a href="#all_stream_readablereadableended"><code>readable.readableEnded</code></a></li>
<li><a href="#all_stream_readableerrored"><code>readable.errored</code></a></li>
<li><a href="#all_stream_readablereadableflowing"><code>readable.readableFlowing</code></a></li>
<li><a href="#all_stream_readablereadablehighwatermark"><code>readable.readableHighWaterMark</code></a></li>
<li><a href="#all_stream_readablereadablelength"><code>readable.readableLength</code></a></li>
<li><a href="#all_stream_readablereadableobjectmode"><code>readable.readableObjectMode</code></a></li>
<li><a href="#all_stream_readableresume"><code>readable.resume()</code></a></li>
<li><a href="#all_stream_readablesetencodingencoding"><code>readable.setEncoding(encoding)</code></a></li>
<li><a href="#all_stream_readableunpipedestination"><code>readable.unpipe([destination])</code></a></li>
<li><a href="#all_stream_readableunshiftchunk-encoding"><code>readable.unshift(chunk[, encoding])</code></a></li>
<li><a href="#all_stream_readablewrapstream"><code>readable.wrap(stream)</code></a></li>
<li><a href="#all_stream_readablesymbolasynciterator"><code>readable[Symbol.asyncIterator]()</code></a></li>
<li><span class="stability_1"><a href="#all_stream_readablesymbolasyncdispose"><code>readable[Symbol.asyncDispose]()</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablecomposestream-options"><code>readable.compose(stream[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readableiteratoroptions"><code>readable.iterator([options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablemapfn-options"><code>readable.map(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablefilterfn-options"><code>readable.filter(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readableforeachfn-options"><code>readable.forEach(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readabletoarrayoptions"><code>readable.toArray([options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablesomefn-options"><code>readable.some(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablefindfn-options"><code>readable.find(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readableeveryfn-options"><code>readable.every(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readableflatmapfn-options"><code>readable.flatMap(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readabledroplimit-options"><code>readable.drop(limit[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readabletakelimit-options"><code>readable.take(limit[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readableasindexedpairsoptions"><code>readable.asIndexedPairs([options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablereducefn-initial-options"><code>readable.reduce(fn[, initial[, options]])</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_stream_duplex-and-transform-streams">Duplex and transform streams</a>
<ul>
<li><a href="#all_stream_class-streamduplex">Class: <code>stream.Duplex</code></a>
<ul>
<li><a href="#all_stream_duplexallowhalfopen"><code>duplex.allowHalfOpen</code></a></li>
</ul>
</li>
<li><a href="#all_stream_class-streamtransform">Class: <code>stream.Transform</code></a>
<ul>
<li><a href="#all_stream_transformdestroyerror"><code>transform.destroy([error])</code></a></li>
</ul>
</li>
<li><a href="#all_stream_streamduplexpairoptions"><code>stream.duplexPair([options])</code></a></li>
</ul>
</li>
<li><a href="#all_stream_streamfinishedstream-options-callback"><code>stream.finished(stream[, options], callback)</code></a></li>
<li><a href="#all_stream_streampipelinesource-transforms-destination-callback"><code>stream.pipeline(source[, ...transforms], destination, callback)</code></a></li>
<li><a href="#all_stream_streampipelinestreams-callback"><code>stream.pipeline(streams, callback)</code></a></li>
<li><span class="stability_1"><a href="#all_stream_streamcomposestreams"><code>stream.compose(...streams)</code></a></span></li>
<li><a href="#all_stream_streamreadablefromiterable-options"><code>stream.Readable.from(iterable[, options])</code></a></li>
<li><span class="stability_1"><a href="#all_stream_streamreadablefromwebreadablestream-options"><code>stream.Readable.fromWeb(readableStream[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamreadableisdisturbedstream"><code>stream.Readable.isDisturbed(stream)</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamiserroredstream"><code>stream.isErrored(stream)</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamisreadablestream"><code>stream.isReadable(stream)</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamreadabletowebstreamreadable-options"><code>stream.Readable.toWeb(streamReadable[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamwritablefromwebwritablestream-options"><code>stream.Writable.fromWeb(writableStream[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamwritabletowebstreamwritable"><code>stream.Writable.toWeb(streamWritable)</code></a></span></li>
<li><a href="#all_stream_streamduplexfromsrc"><code>stream.Duplex.from(src)</code></a></li>
<li><span class="stability_1"><a href="#all_stream_streamduplexfromwebpair-options"><code>stream.Duplex.fromWeb(pair[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamduplextowebstreamduplex"><code>stream.Duplex.toWeb(streamDuplex)</code></a></span></li>
<li><a href="#all_stream_streamaddabortsignalsignal-stream"><code>stream.addAbortSignal(signal, stream)</code></a></li>
<li><a href="#all_stream_streamgetdefaulthighwatermarkobjectmode"><code>stream.getDefaultHighWaterMark(objectMode)</code></a></li>
<li><a href="#all_stream_streamsetdefaulthighwatermarkobjectmode-value"><code>stream.setDefaultHighWaterMark(objectMode, value)</code></a></li>
</ul>
</li>
<li><a href="#all_stream_api-for-stream-implementers">API for stream implementers</a>
<ul>
<li><a href="#all_stream_simplified-construction">Simplified construction</a></li>
<li><a href="#all_stream_implementing-a-writable-stream">Implementing a writable stream</a>
<ul>
<li><a href="#all_stream_new-streamwritableoptions"><code>new stream.Writable([options])</code></a></li>
<li><a href="#all_stream_writable_constructcallback"><code>writable._construct(callback)</code></a></li>
<li><a href="#all_stream_writable_writechunk-encoding-callback"><code>writable._write(chunk, encoding, callback)</code></a></li>
<li><a href="#all_stream_writable_writevchunks-callback"><code>writable._writev(chunks, callback)</code></a></li>
<li><a href="#all_stream_writable_destroyerr-callback"><code>writable._destroy(err, callback)</code></a></li>
<li><a href="#all_stream_writable_finalcallback"><code>writable._final(callback)</code></a></li>
<li><a href="#all_stream_errors-while-writing">Errors while writing</a></li>
<li><a href="#all_stream_an-example-writable-stream">An example writable stream</a></li>
<li><a href="#all_stream_decoding-buffers-in-a-writable-stream">Decoding buffers in a writable stream</a></li>
</ul>
</li>
<li><a href="#all_stream_implementing-a-readable-stream">Implementing a readable stream</a>
<ul>
<li><a href="#all_stream_new-streamreadableoptions"><code>new stream.Readable([options])</code></a></li>
<li><a href="#all_stream_readable_constructcallback"><code>readable._construct(callback)</code></a></li>
<li><a href="#all_stream_readable_readsize"><code>readable._read(size)</code></a></li>
<li><a href="#all_stream_readable_destroyerr-callback"><code>readable._destroy(err, callback)</code></a></li>
<li><a href="#all_stream_readablepushchunk-encoding"><code>readable.push(chunk[, encoding])</code></a></li>
<li><a href="#all_stream_errors-while-reading">Errors while reading</a></li>
<li><a href="#all_stream_an-example-counting-stream">An example counting stream</a></li>
</ul>
</li>
<li><a href="#all_stream_implementing-a-duplex-stream">Implementing a duplex stream</a>
<ul>
<li><a href="#all_stream_new-streamduplexoptions"><code>new stream.Duplex(options)</code></a></li>
<li><a href="#all_stream_an-example-duplex-stream">An example duplex stream</a></li>
<li><a href="#all_stream_object-mode-duplex-streams">Object mode duplex streams</a></li>
</ul>
</li>
<li><a href="#all_stream_implementing-a-transform-stream">Implementing a transform stream</a>
<ul>
<li><a href="#all_stream_new-streamtransformoptions"><code>new stream.Transform([options])</code></a></li>
<li><a href="#all_stream_event-end_1">Event: <code>'end'</code></a></li>
<li><a href="#all_stream_event-finish_1">Event: <code>'finish'</code></a></li>
<li><a href="#all_stream_transform_flushcallback"><code>transform._flush(callback)</code></a></li>
<li><a href="#all_stream_transform_transformchunk-encoding-callback"><code>transform._transform(chunk, encoding, callback)</code></a></li>
<li><a href="#all_stream_class-streampassthrough">Class: <code>stream.PassThrough</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_stream_additional-notes">Additional notes</a>
<ul>
<li><a href="#all_stream_streams-compatibility-with-async-generators-and-async-iterators">Streams compatibility with async generators and async iterators</a>
<ul>
<li><a href="#all_stream_consuming-readable-streams-with-async-iterators">Consuming readable streams with async iterators</a></li>
<li><a href="#all_stream_creating-readable-streams-with-async-generators">Creating readable streams with async generators</a></li>
<li><a href="#all_stream_piping-to-writable-streams-from-async-iterators">Piping to writable streams from async iterators</a></li>
</ul>
</li>
<li><a href="#all_stream_compatibility-with-older-nodejs-versions">Compatibility with older Node.js versions</a></li>
<li><a href="#all_stream_readableread0"><code>readable.read(0)</code></a></li>
<li><a href="#all_stream_readablepush"><code>readable.push('')</code></a></li>
<li><a href="#all_stream_highwatermark-discrepancy-after-calling-readablesetencoding"><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_string_decoder_string-decoder">String decoder</a></span>
<ul>
<li><a href="#all_string_decoder_class-stringdecoder">Class: <code>StringDecoder</code></a>
<ul>
<li><a href="#all_string_decoder_new-stringdecoderencoding"><code>new StringDecoder([encoding])</code></a></li>
<li><a href="#all_string_decoder_stringdecoderendbuffer"><code>stringDecoder.end([buffer])</code></a></li>
<li><a href="#all_string_decoder_stringdecoderwritebuffer"><code>stringDecoder.write(buffer)</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_test_test-runner">Test runner</a></span>
<ul>
<li><a href="#all_test_subtests">Subtests</a></li>
<li><a href="#all_test_skipping-tests">Skipping tests</a></li>
<li><a href="#all_test_todo-tests">TODO tests</a></li>
<li><a href="#all_test_describe-and-it-aliases"><code>describe()</code> and <code>it()</code> aliases</a></li>
<li><a href="#all_test_only-tests"><code>only</code> tests</a></li>
<li><a href="#all_test_filtering-tests-by-name">Filtering tests by name</a></li>
<li><a href="#all_test_extraneous-asynchronous-activity">Extraneous asynchronous activity</a></li>
<li><span class="stability_1"><a href="#all_test_watch-mode">Watch mode</a></span></li>
<li><a href="#all_test_running-tests-from-the-command-line">Running tests from the command line</a>
<ul>
<li><a href="#all_test_test-runner-execution-model">Test runner execution model</a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_test_collecting-code-coverage">Collecting code coverage</a></span>
<ul>
<li><a href="#all_test_coverage-reporters">Coverage reporters</a></li>
<li><a href="#all_test_limitations">Limitations</a></li>
</ul>
</li>
<li><a href="#all_test_mocking">Mocking</a>
<ul>
<li><a href="#all_test_timers">Timers</a></li>
<li><a href="#all_test_dates">Dates</a></li>
</ul>
</li>
<li><a href="#all_test_test-reporters">Test reporters</a>
<ul>
<li><a href="#all_test_custom-reporters">Custom reporters</a></li>
<li><a href="#all_test_multiple-reporters">Multiple reporters</a></li>
</ul>
</li>
<li><a href="#all_test_runoptions"><code>run([options])</code></a></li>
<li><a href="#all_test_suitename-options-fn"><code>suite([name][, options][, fn])</code></a></li>
<li><a href="#all_test_suiteskipname-options-fn"><code>suite.skip([name][, options][, fn])</code></a></li>
<li><a href="#all_test_suitetodoname-options-fn"><code>suite.todo([name][, options][, fn])</code></a></li>
<li><a href="#all_test_suiteonlyname-options-fn"><code>suite.only([name][, options][, fn])</code></a></li>
<li><a href="#all_test_testname-options-fn"><code>test([name][, options][, fn])</code></a></li>
<li><a href="#all_test_testskipname-options-fn"><code>test.skip([name][, options][, fn])</code></a></li>
<li><a href="#all_test_testtodoname-options-fn"><code>test.todo([name][, options][, fn])</code></a></li>
<li><a href="#all_test_testonlyname-options-fn"><code>test.only([name][, options][, fn])</code></a></li>
<li><a href="#all_test_describename-options-fn"><code>describe([name][, options][, fn])</code></a></li>
<li><a href="#all_test_describeskipname-options-fn"><code>describe.skip([name][, options][, fn])</code></a></li>
<li><a href="#all_test_describetodoname-options-fn"><code>describe.todo([name][, options][, fn])</code></a></li>
<li><a href="#all_test_describeonlyname-options-fn"><code>describe.only([name][, options][, fn])</code></a></li>
<li><a href="#all_test_itname-options-fn"><code>it([name][, options][, fn])</code></a></li>
<li><a href="#all_test_itskipname-options-fn"><code>it.skip([name][, options][, fn])</code></a></li>
<li><a href="#all_test_ittodoname-options-fn"><code>it.todo([name][, options][, fn])</code></a></li>
<li><a href="#all_test_itonlyname-options-fn"><code>it.only([name][, options][, fn])</code></a></li>
<li><a href="#all_test_beforefn-options"><code>before([fn][, options])</code></a></li>
<li><a href="#all_test_afterfn-options"><code>after([fn][, options])</code></a></li>
<li><a href="#all_test_beforeeachfn-options"><code>beforeEach([fn][, options])</code></a></li>
<li><a href="#all_test_aftereachfn-options"><code>afterEach([fn][, options])</code></a></li>
<li><a href="#all_test_class-mockfunctioncontext">Class: <code>MockFunctionContext</code></a>
<ul>
<li><a href="#all_test_ctxcalls"><code>ctx.calls</code></a></li>
<li><a href="#all_test_ctxcallcount"><code>ctx.callCount()</code></a></li>
<li><a href="#all_test_ctxmockimplementationimplementation"><code>ctx.mockImplementation(implementation)</code></a></li>
<li><a href="#all_test_ctxmockimplementationonceimplementation-oncall"><code>ctx.mockImplementationOnce(implementation[, onCall])</code></a></li>
<li><a href="#all_test_ctxresetcalls"><code>ctx.resetCalls()</code></a></li>
<li><a href="#all_test_ctxrestore"><code>ctx.restore()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_test_class-mockmodulecontext">Class: <code>MockModuleContext</code></a></span>
<ul>
<li><a href="#all_test_ctxrestore_1"><code>ctx.restore()</code></a></li>
</ul>
</li>
<li><a href="#all_test_class-mocktracker">Class: <code>MockTracker</code></a>
<ul>
<li><a href="#all_test_mockfnoriginal-implementation-options"><code>mock.fn([original[, implementation]][, options])</code></a></li>
<li><a href="#all_test_mockgetterobject-methodname-implementation-options"><code>mock.getter(object, methodName[, implementation][, options])</code></a></li>
<li><a href="#all_test_mockmethodobject-methodname-implementation-options"><code>mock.method(object, methodName[, implementation][, options])</code></a></li>
<li><span class="stability_1"><a href="#all_test_mockmodulespecifier-options"><code>mock.module(specifier[, options])</code></a></span></li>
<li><a href="#all_test_mockreset"><code>mock.reset()</code></a></li>
<li><a href="#all_test_mockrestoreall"><code>mock.restoreAll()</code></a></li>
<li><a href="#all_test_mocksetterobject-methodname-implementation-options"><code>mock.setter(object, methodName[, implementation][, options])</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_test_class-mocktimers">Class: <code>MockTimers</code></a></span>
<ul>
<li><a href="#all_test_timersenableenableoptions"><code>timers.enable([enableOptions])</code></a></li>
<li><a href="#all_test_timersreset"><code>timers.reset()</code></a></li>
<li><a href="#all_test_timerssymboldispose"><code>timers[Symbol.dispose]()</code></a></li>
<li><a href="#all_test_timerstickmilliseconds"><code>timers.tick([milliseconds])</code></a>
<ul>
<li><a href="#all_test_using-clear-functions">Using clear functions</a></li>
<li><a href="#all_test_working-with-nodejs-timers-modules">Working with Node.js timers modules</a></li>
</ul>
</li>
<li><a href="#all_test_timersrunall"><code>timers.runAll()</code></a></li>
<li><a href="#all_test_timerssettimemilliseconds"><code>timers.setTime(milliseconds)</code></a>
<ul>
<li><a href="#all_test_dates-and-timers-working-together">Dates and Timers working together</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_test_class-testsstream">Class: <code>TestsStream</code></a>
<ul>
<li><a href="#all_test_event-testcoverage">Event: <code>'test:coverage'</code></a></li>
<li><a href="#all_test_event-testcomplete">Event: <code>'test:complete'</code></a></li>
<li><a href="#all_test_event-testdequeue">Event: <code>'test:dequeue'</code></a></li>
<li><a href="#all_test_event-testdiagnostic">Event: <code>'test:diagnostic'</code></a></li>
<li><a href="#all_test_event-testenqueue">Event: <code>'test:enqueue'</code></a></li>
<li><a href="#all_test_event-testfail">Event: <code>'test:fail'</code></a></li>
<li><a href="#all_test_event-testpass">Event: <code>'test:pass'</code></a></li>
<li><a href="#all_test_event-testplan">Event: <code>'test:plan'</code></a></li>
<li><a href="#all_test_event-teststart">Event: <code>'test:start'</code></a></li>
<li><a href="#all_test_event-teststderr">Event: <code>'test:stderr'</code></a></li>
<li><a href="#all_test_event-teststdout">Event: <code>'test:stdout'</code></a></li>
<li><a href="#all_test_event-testwatchdrained">Event: <code>'test:watch:drained'</code></a></li>
</ul>
</li>
<li><a href="#all_test_class-testcontext">Class: <code>TestContext</code></a>
<ul>
<li><a href="#all_test_contextbeforefn-options"><code>context.before([fn][, options])</code></a></li>
<li><a href="#all_test_contextbeforeeachfn-options"><code>context.beforeEach([fn][, options])</code></a></li>
<li><a href="#all_test_contextafterfn-options"><code>context.after([fn][, options])</code></a></li>
<li><a href="#all_test_contextaftereachfn-options"><code>context.afterEach([fn][, options])</code></a></li>
<li><a href="#all_test_contextassert"><code>context.assert</code></a></li>
<li><a href="#all_test_contextdiagnosticmessage"><code>context.diagnostic(message)</code></a></li>
<li><a href="#all_test_contextfullname"><code>context.fullName</code></a></li>
<li><a href="#all_test_contextname"><code>context.name</code></a></li>
<li><span class="stability_1"><a href="#all_test_contextplancount"><code>context.plan(count)</code></a></span></li>
<li><a href="#all_test_contextrunonlyshouldrunonlytests"><code>context.runOnly(shouldRunOnlyTests)</code></a></li>
<li><a href="#all_test_contextsignal"><code>context.signal</code></a></li>
<li><a href="#all_test_contextskipmessage"><code>context.skip([message])</code></a></li>
<li><a href="#all_test_contexttodomessage"><code>context.todo([message])</code></a></li>
<li><a href="#all_test_contexttestname-options-fn"><code>context.test([name][, options][, fn])</code></a></li>
</ul>
</li>
<li><a href="#all_test_class-suitecontext">Class: <code>SuiteContext</code></a>
<ul>
<li><a href="#all_test_contextname_1"><code>context.name</code></a></li>
<li><a href="#all_test_contextsignal_1"><code>context.signal</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_timers_timers">Timers</a></span>
<ul>
<li><a href="#all_timers_class-immediate">Class: <code>Immediate</code></a>
<ul>
<li><a href="#all_timers_immediatehasref"><code>immediate.hasRef()</code></a></li>
<li><a href="#all_timers_immediateref"><code>immediate.ref()</code></a></li>
<li><a href="#all_timers_immediateunref"><code>immediate.unref()</code></a></li>
<li><span class="stability_1"><a href="#all_timers_immediatesymboldispose"><code>immediate[Symbol.dispose]()</code></a></span></li>
</ul>
</li>
<li><a href="#all_timers_class-timeout">Class: <code>Timeout</code></a>
<ul>
<li><span class="stability_3"><a href="#all_timers_timeoutclose"><code>timeout.close()</code></a></span></li>
<li><a href="#all_timers_timeouthasref"><code>timeout.hasRef()</code></a></li>
<li><a href="#all_timers_timeoutref"><code>timeout.ref()</code></a></li>
<li><a href="#all_timers_timeoutrefresh"><code>timeout.refresh()</code></a></li>
<li><a href="#all_timers_timeoutunref"><code>timeout.unref()</code></a></li>
<li><a href="#all_timers_timeoutsymboltoprimitive"><code>timeout[Symbol.toPrimitive]()</code></a></li>
<li><span class="stability_1"><a href="#all_timers_timeoutsymboldispose"><code>timeout[Symbol.dispose]()</code></a></span></li>
</ul>
</li>
<li><a href="#all_timers_scheduling-timers">Scheduling timers</a>
<ul>
<li><a href="#all_timers_setimmediatecallback-args"><code>setImmediate(callback[, ...args])</code></a></li>
<li><a href="#all_timers_setintervalcallback-delay-args"><code>setInterval(callback[, delay[, ...args]])</code></a></li>
<li><a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout(callback[, delay[, ...args]])</code></a></li>
</ul>
</li>
<li><a href="#all_timers_cancelling-timers">Cancelling timers</a>
<ul>
<li><a href="#all_timers_clearimmediateimmediate"><code>clearImmediate(immediate)</code></a></li>
<li><a href="#all_timers_clearintervaltimeout"><code>clearInterval(timeout)</code></a></li>
<li><a href="#all_timers_cleartimeouttimeout"><code>clearTimeout(timeout)</code></a></li>
</ul>
</li>
<li><a href="#all_timers_timers-promises-api">Timers Promises API</a>
<ul>
<li><a href="#all_timers_timerspromisessettimeoutdelay-value-options"><code>timersPromises.setTimeout([delay[, value[, options]]])</code></a></li>
<li><a href="#all_timers_timerspromisessetimmediatevalue-options"><code>timersPromises.setImmediate([value[, options]])</code></a></li>
<li><a href="#all_timers_timerspromisessetintervaldelay-value-options"><code>timersPromises.setInterval([delay[, value[, options]]])</code></a></li>
<li><span class="stability_1"><a href="#all_timers_timerspromisesschedulerwaitdelay-options"><code>timersPromises.scheduler.wait(delay[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_timers_timerspromisesscheduleryield"><code>timersPromises.scheduler.yield()</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_tls_tls-ssl">TLS (SSL)</a></span>
<ul>
<li><a href="#all_tls_determining-if-crypto-support-is-unavailable">Determining if crypto support is unavailable</a></li>
<li><a href="#all_tls_tlsssl-concepts">TLS/SSL concepts</a>
<ul>
<li><a href="#all_tls_perfect-forward-secrecy">Perfect forward secrecy</a></li>
<li><a href="#all_tls_alpn-and-sni">ALPN and SNI</a></li>
<li><a href="#all_tls_pre-shared-keys">Pre-shared keys</a></li>
<li><a href="#all_tls_client-initiated-renegotiation-attack-mitigation">Client-initiated renegotiation attack mitigation</a></li>
<li><a href="#all_tls_session-resumption">Session resumption</a>
<ul>
<li><a href="#all_tls_session-identifiers">Session identifiers</a></li>
<li><a href="#all_tls_session-tickets">Session tickets</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_tls_modifying-the-default-tls-cipher-suite">Modifying the default TLS cipher suite</a></li>
<li><a href="#all_tls_x509-certificate-error-codes">X509 certificate error codes</a></li>
<li><span class="stability_0"><a href="#all_tls_class-tlscryptostream">Class: <code>tls.CryptoStream</code></a></span>
<ul>
<li><a href="#all_tls_cryptostreambyteswritten"><code>cryptoStream.bytesWritten</code></a></li>
</ul>
</li>
<li><span class="stability_0"><a href="#all_tls_class-tlssecurepair">Class: <code>tls.SecurePair</code></a></span>
<ul>
<li><a href="#all_tls_event-secure">Event: <code>'secure'</code></a></li>
</ul>
</li>
<li><a href="#all_tls_class-tlsserver">Class: <code>tls.Server</code></a>
<ul>
<li><a href="#all_tls_event-connection">Event: <code>'connection'</code></a></li>
<li><a href="#all_tls_event-keylog">Event: <code>'keylog'</code></a></li>
<li><a href="#all_tls_event-newsession">Event: <code>'newSession'</code></a></li>
<li><a href="#all_tls_event-ocsprequest">Event: <code>'OCSPRequest'</code></a></li>
<li><a href="#all_tls_event-resumesession">Event: <code>'resumeSession'</code></a></li>
<li><a href="#all_tls_event-secureconnection">Event: <code>'secureConnection'</code></a></li>
<li><a href="#all_tls_event-tlsclienterror">Event: <code>'tlsClientError'</code></a></li>
<li><a href="#all_tls_serveraddcontexthostname-context"><code>server.addContext(hostname, context)</code></a></li>
<li><a href="#all_tls_serveraddress"><code>server.address()</code></a></li>
<li><a href="#all_tls_serverclosecallback"><code>server.close([callback])</code></a></li>
<li><a href="#all_tls_servergetticketkeys"><code>server.getTicketKeys()</code></a></li>
<li><a href="#all_tls_serverlisten"><code>server.listen()</code></a></li>
<li><a href="#all_tls_serversetsecurecontextoptions"><code>server.setSecureContext(options)</code></a></li>
<li><a href="#all_tls_serversetticketkeyskeys"><code>server.setTicketKeys(keys)</code></a></li>
</ul>
</li>
<li><a href="#all_tls_class-tlstlssocket">Class: <code>tls.TLSSocket</code></a>
<ul>
<li><a href="#all_tls_new-tlstlssocketsocket-options"><code>new tls.TLSSocket(socket[, options])</code></a></li>
<li><a href="#all_tls_event-keylog_1">Event: <code>'keylog'</code></a></li>
<li><a href="#all_tls_event-ocspresponse">Event: <code>'OCSPResponse'</code></a></li>
<li><a href="#all_tls_event-secureconnect">Event: <code>'secureConnect'</code></a></li>
<li><a href="#all_tls_event-session">Event: <code>'session'</code></a></li>
<li><a href="#all_tls_tlssocketaddress"><code>tlsSocket.address()</code></a></li>
<li><a href="#all_tls_tlssocketauthorizationerror"><code>tlsSocket.authorizationError</code></a></li>
<li><a href="#all_tls_tlssocketauthorized"><code>tlsSocket.authorized</code></a></li>
<li><a href="#all_tls_tlssocketdisablerenegotiation"><code>tlsSocket.disableRenegotiation()</code></a></li>
<li><a href="#all_tls_tlssocketenabletrace"><code>tlsSocket.enableTrace()</code></a></li>
<li><a href="#all_tls_tlssocketencrypted"><code>tlsSocket.encrypted</code></a></li>
<li><a href="#all_tls_tlssocketexportkeyingmateriallength-label-context"><code>tlsSocket.exportKeyingMaterial(length, label[, context])</code></a></li>
<li><a href="#all_tls_tlssocketgetcertificate"><code>tlsSocket.getCertificate()</code></a></li>
<li><a href="#all_tls_tlssocketgetcipher"><code>tlsSocket.getCipher()</code></a></li>
<li><a href="#all_tls_tlssocketgetephemeralkeyinfo"><code>tlsSocket.getEphemeralKeyInfo()</code></a></li>
<li><a href="#all_tls_tlssocketgetfinished"><code>tlsSocket.getFinished()</code></a></li>
<li><a href="#all_tls_tlssocketgetpeercertificatedetailed"><code>tlsSocket.getPeerCertificate([detailed])</code></a>
<ul>
<li><a href="#all_tls_certificate-object">Certificate object</a></li>
</ul>
</li>
<li><a href="#all_tls_tlssocketgetpeerfinished"><code>tlsSocket.getPeerFinished()</code></a></li>
<li><a href="#all_tls_tlssocketgetpeerx509certificate"><code>tlsSocket.getPeerX509Certificate()</code></a></li>
<li><a href="#all_tls_tlssocketgetprotocol"><code>tlsSocket.getProtocol()</code></a></li>
<li><a href="#all_tls_tlssocketgetsession"><code>tlsSocket.getSession()</code></a></li>
<li><a href="#all_tls_tlssocketgetsharedsigalgs"><code>tlsSocket.getSharedSigalgs()</code></a></li>
<li><a href="#all_tls_tlssocketgettlsticket"><code>tlsSocket.getTLSTicket()</code></a></li>
<li><a href="#all_tls_tlssocketgetx509certificate"><code>tlsSocket.getX509Certificate()</code></a></li>
<li><a href="#all_tls_tlssocketissessionreused"><code>tlsSocket.isSessionReused()</code></a></li>
<li><a href="#all_tls_tlssocketlocaladdress"><code>tlsSocket.localAddress</code></a></li>
<li><a href="#all_tls_tlssocketlocalport"><code>tlsSocket.localPort</code></a></li>
<li><a href="#all_tls_tlssocketremoteaddress"><code>tlsSocket.remoteAddress</code></a></li>
<li><a href="#all_tls_tlssocketremotefamily"><code>tlsSocket.remoteFamily</code></a></li>
<li><a href="#all_tls_tlssocketremoteport"><code>tlsSocket.remotePort</code></a></li>
<li><a href="#all_tls_tlssocketrenegotiateoptions-callback"><code>tlsSocket.renegotiate(options, callback)</code></a></li>
<li><a href="#all_tls_tlssocketsetkeycertcontext"><code>tlsSocket.setKeyCert(context)</code></a></li>
<li><a href="#all_tls_tlssocketsetmaxsendfragmentsize"><code>tlsSocket.setMaxSendFragment(size)</code></a></li>
</ul>
</li>
<li><a href="#all_tls_tlscheckserveridentityhostname-cert"><code>tls.checkServerIdentity(hostname, cert)</code></a></li>
<li><a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect(options[, callback])</code></a></li>
<li><a href="#all_tls_tlsconnectpath-options-callback"><code>tls.connect(path[, options][, callback])</code></a></li>
<li><a href="#all_tls_tlsconnectport-host-options-callback"><code>tls.connect(port[, host][, options][, callback])</code></a></li>
<li><a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext([options])</code></a></li>
<li><span class="stability_0"><a href="#all_tls_tlscreatesecurepaircontext-isserver-requestcert-rejectunauthorized-options"><code>tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])</code></a></span></li>
<li><a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer([options][, secureConnectionListener])</code></a></li>
<li><a href="#all_tls_tlsgetciphers"><code>tls.getCiphers()</code></a></li>
<li><a href="#all_tls_tlsrootcertificates"><code>tls.rootCertificates</code></a></li>
<li><a href="#all_tls_tlsdefault_ecdh_curve"><code>tls.DEFAULT_ECDH_CURVE</code></a></li>
<li><a href="#all_tls_tlsdefault_max_version"><code>tls.DEFAULT_MAX_VERSION</code></a></li>
<li><a href="#all_tls_tlsdefault_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a></li>
<li><a href="#all_tls_tlsdefault_ciphers"><code>tls.DEFAULT_CIPHERS</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_tracing_trace-events">Trace events</a></span>
<ul>
<li><a href="#all_tracing_the-nodetrace_events-module">The <code>node:trace_events</code> module</a>
<ul>
<li><a href="#all_tracing_tracing-object"><code>Tracing</code> object</a>
<ul>
<li><a href="#all_tracing_tracingcategories"><code>tracing.categories</code></a></li>
<li><a href="#all_tracing_tracingdisable"><code>tracing.disable()</code></a></li>
<li><a href="#all_tracing_tracingenable"><code>tracing.enable()</code></a></li>
<li><a href="#all_tracing_tracingenabled"><code>tracing.enabled</code></a></li>
</ul>
</li>
<li><a href="#all_tracing_trace_eventscreatetracingoptions"><code>trace_events.createTracing(options)</code></a></li>
<li><a href="#all_tracing_trace_eventsgetenabledcategories"><code>trace_events.getEnabledCategories()</code></a></li>
</ul>
</li>
<li><a href="#all_tracing_examples">Examples</a>
<ul>
<li><a href="#all_tracing_collect-trace-events-data-by-inspector">Collect trace events data by inspector</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_tty_tty">TTY</a></span>
<ul>
<li><a href="#all_tty_class-ttyreadstream">Class: <code>tty.ReadStream</code></a>
<ul>
<li><a href="#all_tty_readstreamisraw"><code>readStream.isRaw</code></a></li>
<li><a href="#all_tty_readstreamistty"><code>readStream.isTTY</code></a></li>
<li><a href="#all_tty_readstreamsetrawmodemode"><code>readStream.setRawMode(mode)</code></a></li>
</ul>
</li>
<li><a href="#all_tty_class-ttywritestream">Class: <code>tty.WriteStream</code></a>
<ul>
<li><a href="#all_tty_new-ttyreadstreamfd-options"><code>new tty.ReadStream(fd[, options])</code></a></li>
<li><a href="#all_tty_new-ttywritestreamfd"><code>new tty.WriteStream(fd)</code></a></li>
<li><a href="#all_tty_event-resize">Event: <code>'resize'</code></a></li>
<li><a href="#all_tty_writestreamclearlinedir-callback"><code>writeStream.clearLine(dir[, callback])</code></a></li>
<li><a href="#all_tty_writestreamclearscreendowncallback"><code>writeStream.clearScreenDown([callback])</code></a></li>
<li><a href="#all_tty_writestreamcolumns"><code>writeStream.columns</code></a></li>
<li><a href="#all_tty_writestreamcursortox-y-callback"><code>writeStream.cursorTo(x[, y][, callback])</code></a></li>
<li><a href="#all_tty_writestreamgetcolordepthenv"><code>writeStream.getColorDepth([env])</code></a></li>
<li><a href="#all_tty_writestreamgetwindowsize"><code>writeStream.getWindowSize()</code></a></li>
<li><a href="#all_tty_writestreamhascolorscount-env"><code>writeStream.hasColors([count][, env])</code></a></li>
<li><a href="#all_tty_writestreamistty"><code>writeStream.isTTY</code></a></li>
<li><a href="#all_tty_writestreammovecursordx-dy-callback"><code>writeStream.moveCursor(dx, dy[, callback])</code></a></li>
<li><a href="#all_tty_writestreamrows"><code>writeStream.rows</code></a></li>
</ul>
</li>
<li><a href="#all_tty_ttyisattyfd"><code>tty.isatty(fd)</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_dgram_udpdatagram-sockets">UDP/datagram sockets</a></span>
<ul>
<li><a href="#all_dgram_class-dgramsocket">Class: <code>dgram.Socket</code></a>
<ul>
<li><a href="#all_dgram_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_dgram_event-connect">Event: <code>'connect'</code></a></li>
<li><a href="#all_dgram_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_dgram_event-listening">Event: <code>'listening'</code></a></li>
<li><a href="#all_dgram_event-message">Event: <code>'message'</code></a></li>
<li><a href="#all_dgram_socketaddmembershipmulticastaddress-multicastinterface"><code>socket.addMembership(multicastAddress[, multicastInterface])</code></a></li>
<li><a href="#all_dgram_socketaddsourcespecificmembershipsourceaddress-groupaddress-multicastinterface"><code>socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code></a></li>
<li><a href="#all_dgram_socketaddress"><code>socket.address()</code></a></li>
<li><a href="#all_dgram_socketbindport-address-callback"><code>socket.bind([port][, address][, callback])</code></a></li>
<li><a href="#all_dgram_socketbindoptions-callback"><code>socket.bind(options[, callback])</code></a></li>
<li><a href="#all_dgram_socketclosecallback"><code>socket.close([callback])</code></a></li>
<li><span class="stability_1"><a href="#all_dgram_socketsymbolasyncdispose"><code>socket[Symbol.asyncDispose]()</code></a></span></li>
<li><a href="#all_dgram_socketconnectport-address-callback"><code>socket.connect(port[, address][, callback])</code></a></li>
<li><a href="#all_dgram_socketdisconnect"><code>socket.disconnect()</code></a></li>
<li><a href="#all_dgram_socketdropmembershipmulticastaddress-multicastinterface"><code>socket.dropMembership(multicastAddress[, multicastInterface])</code></a></li>
<li><a href="#all_dgram_socketdropsourcespecificmembershipsourceaddress-groupaddress-multicastinterface"><code>socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code></a></li>
<li><a href="#all_dgram_socketgetrecvbuffersize"><code>socket.getRecvBufferSize()</code></a></li>
<li><a href="#all_dgram_socketgetsendbuffersize"><code>socket.getSendBufferSize()</code></a></li>
<li><a href="#all_dgram_socketgetsendqueuesize"><code>socket.getSendQueueSize()</code></a></li>
<li><a href="#all_dgram_socketgetsendqueuecount"><code>socket.getSendQueueCount()</code></a></li>
<li><a href="#all_dgram_socketref"><code>socket.ref()</code></a></li>
<li><a href="#all_dgram_socketremoteaddress"><code>socket.remoteAddress()</code></a></li>
<li><a href="#all_dgram_socketsendmsg-offset-length-port-address-callback"><code>socket.send(msg[, offset, length][, port][, address][, callback])</code></a>
<ul>
<li><a href="#all_dgram_note-about-udp-datagram-size">Note about UDP datagram size</a></li>
</ul>
</li>
<li><a href="#all_dgram_socketsetbroadcastflag"><code>socket.setBroadcast(flag)</code></a></li>
<li><a href="#all_dgram_socketsetmulticastinterfacemulticastinterface"><code>socket.setMulticastInterface(multicastInterface)</code></a>
<ul>
<li><a href="#all_dgram_example-ipv6-outgoing-multicast-interface">Example: IPv6 outgoing multicast interface</a></li>
<li><a href="#all_dgram_example-ipv4-outgoing-multicast-interface">Example: IPv4 outgoing multicast interface</a></li>
<li><a href="#all_dgram_call-results">Call results</a></li>
</ul>
</li>
<li><a href="#all_dgram_socketsetmulticastloopbackflag"><code>socket.setMulticastLoopback(flag)</code></a></li>
<li><a href="#all_dgram_socketsetmulticastttlttl"><code>socket.setMulticastTTL(ttl)</code></a></li>
<li><a href="#all_dgram_socketsetrecvbuffersizesize"><code>socket.setRecvBufferSize(size)</code></a></li>
<li><a href="#all_dgram_socketsetsendbuffersizesize"><code>socket.setSendBufferSize(size)</code></a></li>
<li><a href="#all_dgram_socketsetttlttl"><code>socket.setTTL(ttl)</code></a></li>
<li><a href="#all_dgram_socketunref"><code>socket.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_dgram_nodedgram-module-functions"><code>node:dgram</code> module functions</a>
<ul>
<li><a href="#all_dgram_dgramcreatesocketoptions-callback"><code>dgram.createSocket(options[, callback])</code></a></li>
<li><a href="#all_dgram_dgramcreatesockettype-callback"><code>dgram.createSocket(type[, callback])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_url_url">URL</a></span>
<ul>
<li><a href="#all_url_url-strings-and-url-objects">URL strings and URL objects</a>
<ul>
<li><a href="#all_url_constructing-a-url-from-component-parts-and-getting-the-constructed-string">Constructing a URL from component parts and getting the constructed string</a></li>
</ul>
</li>
<li><a href="#all_url_the-whatwg-url-api">The WHATWG URL API</a>
<ul>
<li><a href="#all_url_class-url">Class: <code>URL</code></a>
<ul>
<li><a href="#all_url_new-urlinput-base"><code>new URL(input[, base])</code></a></li>
<li><a href="#all_url_urlhash"><code>url.hash</code></a></li>
<li><a href="#all_url_urlhost"><code>url.host</code></a></li>
<li><a href="#all_url_urlhostname"><code>url.hostname</code></a></li>
<li><a href="#all_url_urlhref"><code>url.href</code></a></li>
<li><a href="#all_url_urlorigin"><code>url.origin</code></a></li>
<li><a href="#all_url_urlpassword"><code>url.password</code></a></li>
<li><a href="#all_url_urlpathname"><code>url.pathname</code></a></li>
<li><a href="#all_url_urlport"><code>url.port</code></a></li>
<li><a href="#all_url_urlprotocol"><code>url.protocol</code></a>
<ul>
<li><a href="#all_url_special-schemes">Special schemes</a></li>
</ul>
</li>
<li><a href="#all_url_urlsearch"><code>url.search</code></a></li>
<li><a href="#all_url_urlsearchparams"><code>url.searchParams</code></a></li>
<li><a href="#all_url_urlusername"><code>url.username</code></a></li>
<li><a href="#all_url_urltostring"><code>url.toString()</code></a></li>
<li><a href="#all_url_urltojson"><code>url.toJSON()</code></a></li>
<li><span class="stability_1"><a href="#all_url_urlcreateobjecturlblob"><code>URL.createObjectURL(blob)</code></a></span></li>
<li><span class="stability_1"><a href="#all_url_urlrevokeobjecturlid"><code>URL.revokeObjectURL(id)</code></a></span></li>
<li><a href="#all_url_urlcanparseinput-base"><code>URL.canParse(input[, base])</code></a></li>
<li><a href="#all_url_urlparseinput-base"><code>URL.parse(input[, base])</code></a></li>
</ul>
</li>
<li><a href="#all_url_class-urlsearchparams">Class: <code>URLSearchParams</code></a>
<ul>
<li><a href="#all_url_new-urlsearchparams"><code>new URLSearchParams()</code></a></li>
<li><a href="#all_url_new-urlsearchparamsstring"><code>new URLSearchParams(string)</code></a></li>
<li><a href="#all_url_new-urlsearchparamsobj"><code>new URLSearchParams(obj)</code></a></li>
<li><a href="#all_url_new-urlsearchparamsiterable"><code>new URLSearchParams(iterable)</code></a></li>
<li><a href="#all_url_urlsearchparamsappendname-value"><code>urlSearchParams.append(name, value)</code></a></li>
<li><a href="#all_url_urlsearchparamsdeletename-value"><code>urlSearchParams.delete(name[, value])</code></a></li>
<li><a href="#all_url_urlsearchparamsentries"><code>urlSearchParams.entries()</code></a></li>
<li><a href="#all_url_urlsearchparamsforeachfn-thisarg"><code>urlSearchParams.forEach(fn[, thisArg])</code></a></li>
<li><a href="#all_url_urlsearchparamsgetname"><code>urlSearchParams.get(name)</code></a></li>
<li><a href="#all_url_urlsearchparamsgetallname"><code>urlSearchParams.getAll(name)</code></a></li>
<li><a href="#all_url_urlsearchparamshasname-value"><code>urlSearchParams.has(name[, value])</code></a></li>
<li><a href="#all_url_urlsearchparamskeys"><code>urlSearchParams.keys()</code></a></li>
<li><a href="#all_url_urlsearchparamssetname-value"><code>urlSearchParams.set(name, value)</code></a></li>
<li><a href="#all_url_urlsearchparamssize"><code>urlSearchParams.size</code></a></li>
<li><a href="#all_url_urlsearchparamssort"><code>urlSearchParams.sort()</code></a></li>
<li><a href="#all_url_urlsearchparamstostring"><code>urlSearchParams.toString()</code></a></li>
<li><a href="#all_url_urlsearchparamsvalues"><code>urlSearchParams.values()</code></a></li>
<li><a href="#all_url_urlsearchparamssymboliterator"><code>urlSearchParams[Symbol.iterator]()</code></a></li>
</ul>
</li>
<li><a href="#all_url_urldomaintoasciidomain"><code>url.domainToASCII(domain)</code></a></li>
<li><a href="#all_url_urldomaintounicodedomain"><code>url.domainToUnicode(domain)</code></a></li>
<li><a href="#all_url_urlfileurltopathurl-options"><code>url.fileURLToPath(url[, options])</code></a></li>
<li><a href="#all_url_urlformaturl-options"><code>url.format(URL[, options])</code></a></li>
<li><a href="#all_url_urlpathtofileurlpath-options"><code>url.pathToFileURL(path[, options])</code></a></li>
<li><a href="#all_url_urlurltohttpoptionsurl"><code>url.urlToHttpOptions(url)</code></a></li>
</ul>
</li>
<li><span class="stability_3"><a href="#all_url_legacy-url-api">Legacy URL API</a></span>
<ul>
<li><span class="stability_3"><a href="#all_url_legacy-urlobject">Legacy <code>urlObject</code></a></span>
<ul>
<li><a href="#all_url_urlobjectauth"><code>urlObject.auth</code></a></li>
<li><a href="#all_url_urlobjecthash"><code>urlObject.hash</code></a></li>
<li><a href="#all_url_urlobjecthost"><code>urlObject.host</code></a></li>
<li><a href="#all_url_urlobjecthostname"><code>urlObject.hostname</code></a></li>
<li><a href="#all_url_urlobjecthref"><code>urlObject.href</code></a></li>
<li><a href="#all_url_urlobjectpath"><code>urlObject.path</code></a></li>
<li><a href="#all_url_urlobjectpathname"><code>urlObject.pathname</code></a></li>
<li><a href="#all_url_urlobjectport"><code>urlObject.port</code></a></li>
<li><a href="#all_url_urlobjectprotocol"><code>urlObject.protocol</code></a></li>
<li><a href="#all_url_urlobjectquery"><code>urlObject.query</code></a></li>
<li><a href="#all_url_urlobjectsearch"><code>urlObject.search</code></a></li>
<li><a href="#all_url_urlobjectslashes"><code>urlObject.slashes</code></a></li>
</ul>
</li>
<li><span class="stability_3"><a href="#all_url_urlformaturlobject"><code>url.format(urlObject)</code></a></span></li>
<li><span class="stability_0"><a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse(urlString[, parseQueryString[, slashesDenoteHost]])</code></a></span></li>
<li><span class="stability_3"><a href="#all_url_urlresolvefrom-to"><code>url.resolve(from, to)</code></a></span></li>
</ul>
</li>
<li><a href="#all_url_percent-encoding-in-urls">Percent-encoding in URLs</a>
<ul>
<li><a href="#all_url_legacy-api">Legacy API</a></li>
<li><a href="#all_url_whatwg-api">WHATWG API</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_util_util">Util</a></span>
<ul>
<li><a href="#all_util_utilcallbackifyoriginal"><code>util.callbackify(original)</code></a></li>
<li><a href="#all_util_utildebuglogsection-callback"><code>util.debuglog(section[, callback])</code></a>
<ul>
<li><a href="#all_util_debuglogenabled"><code>debuglog().enabled</code></a></li>
</ul>
</li>
<li><a href="#all_util_utildebugsection"><code>util.debug(section)</code></a></li>
<li><a href="#all_util_utildeprecatefn-msg-code"><code>util.deprecate(fn, msg[, code])</code></a></li>
<li><a href="#all_util_utilformatformat-args"><code>util.format(format[, ...args])</code></a></li>
<li><a href="#all_util_utilformatwithoptionsinspectoptions-format-args"><code>util.formatWithOptions(inspectOptions, format[, ...args])</code></a></li>
<li><a href="#all_util_utilgetsystemerrornameerr"><code>util.getSystemErrorName(err)</code></a></li>
<li><a href="#all_util_utilgetsystemerrormap"><code>util.getSystemErrorMap()</code></a></li>
<li><span class="stability_3"><a href="#all_util_utilinheritsconstructor-superconstructor"><code>util.inherits(constructor, superConstructor)</code></a></span></li>
<li><a href="#all_util_utilinspectobject-options"><code>util.inspect(object[, options])</code></a></li>
<li><a href="#all_util_utilinspectobject-showhidden-depth-colors"><code>util.inspect(object[, showHidden[, depth[, colors]]])</code></a>
<ul>
<li><a href="#all_util_customizing-utilinspect-colors">Customizing <code>util.inspect</code> colors</a>
<ul>
<li><a href="#all_util_modifiers">Modifiers</a></li>
<li><a href="#all_util_foreground-colors">Foreground colors</a></li>
<li><a href="#all_util_background-colors">Background colors</a></li>
</ul>
</li>
<li><a href="#all_util_custom-inspection-functions-on-objects">Custom inspection functions on objects</a></li>
<li><a href="#all_util_utilinspectcustom"><code>util.inspect.custom</code></a></li>
<li><a href="#all_util_utilinspectdefaultoptions"><code>util.inspect.defaultOptions</code></a></li>
</ul>
</li>
<li><a href="#all_util_utilisdeepstrictequalval1-val2"><code>util.isDeepStrictEqual(val1, val2)</code></a></li>
<li><span class="stability_1"><a href="#all_util_class-utilmimetype">Class: <code>util.MIMEType</code></a></span>
<ul>
<li><a href="#all_util_constructor-new-mimetypeinput">Constructor: <code>new MIMEType(input)</code></a></li>
<li><a href="#all_util_mimetype"><code>mime.type</code></a></li>
<li><a href="#all_util_mimesubtype"><code>mime.subtype</code></a></li>
<li><a href="#all_util_mimeessence"><code>mime.essence</code></a></li>
<li><a href="#all_util_mimeparams"><code>mime.params</code></a></li>
<li><a href="#all_util_mimetostring"><code>mime.toString()</code></a></li>
<li><a href="#all_util_mimetojson"><code>mime.toJSON()</code></a></li>
</ul>
</li>
<li><a href="#all_util_class-utilmimeparams">Class: <code>util.MIMEParams</code></a>
<ul>
<li><a href="#all_util_constructor-new-mimeparams">Constructor: <code>new MIMEParams()</code></a></li>
<li><a href="#all_util_mimeparamsdeletename"><code>mimeParams.delete(name)</code></a></li>
<li><a href="#all_util_mimeparamsentries"><code>mimeParams.entries()</code></a></li>
<li><a href="#all_util_mimeparamsgetname"><code>mimeParams.get(name)</code></a></li>
<li><a href="#all_util_mimeparamshasname"><code>mimeParams.has(name)</code></a></li>
<li><a href="#all_util_mimeparamskeys"><code>mimeParams.keys()</code></a></li>
<li><a href="#all_util_mimeparamssetname-value"><code>mimeParams.set(name, value)</code></a></li>
<li><a href="#all_util_mimeparamsvalues"><code>mimeParams.values()</code></a></li>
<li><a href="#all_util_mimeparamsiterator"><code>mimeParams[@@iterator]()</code></a></li>
</ul>
</li>
<li><a href="#all_util_utilparseargsconfig"><code>util.parseArgs([config])</code></a>
<ul>
<li><a href="#all_util_parseargs-tokens"><code>parseArgs</code> <code>tokens</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_util_utilparseenvcontent"><code>util.parseEnv(content)</code></a></span></li>
<li><a href="#all_util_utilpromisifyoriginal"><code>util.promisify(original)</code></a>
<ul>
<li><a href="#all_util_custom-promisified-functions">Custom promisified functions</a></li>
<li><a href="#all_util_utilpromisifycustom"><code>util.promisify.custom</code></a></li>
</ul>
</li>
<li><a href="#all_util_utilstripvtcontrolcharactersstr"><code>util.stripVTControlCharacters(str)</code></a></li>
<li><span class="stability_1"><a href="#all_util_utilstyletextformat-text-options"><code>util.styleText(format, text[, options])</code></a></span></li>
<li><a href="#all_util_class-utiltextdecoder">Class: <code>util.TextDecoder</code></a>
<ul>
<li><a href="#all_util_whatwg-supported-encodings">WHATWG supported encodings</a>
<ul>
<li><a href="#all_util_encodings-supported-by-default-with-full-icu-data">Encodings supported by default (with full ICU data)</a></li>
<li><a href="#all_util_encodings-supported-when-nodejs-is-built-with-the-small-icu-option">Encodings supported when Node.js is built with the <code>small-icu</code> option</a></li>
<li><a href="#all_util_encodings-supported-when-icu-is-disabled">Encodings supported when ICU is disabled</a></li>
</ul>
</li>
<li><a href="#all_util_new-textdecoderencoding-options"><code>new TextDecoder([encoding[, options]])</code></a></li>
<li><a href="#all_util_textdecoderdecodeinput-options"><code>textDecoder.decode([input[, options]])</code></a></li>
<li><a href="#all_util_textdecoderencoding"><code>textDecoder.encoding</code></a></li>
<li><a href="#all_util_textdecoderfatal"><code>textDecoder.fatal</code></a></li>
<li><a href="#all_util_textdecoderignorebom"><code>textDecoder.ignoreBOM</code></a></li>
</ul>
</li>
<li><a href="#all_util_class-utiltextencoder">Class: <code>util.TextEncoder</code></a>
<ul>
<li><a href="#all_util_textencoderencodeinput"><code>textEncoder.encode([input])</code></a></li>
<li><a href="#all_util_textencoderencodeintosrc-dest"><code>textEncoder.encodeInto(src, dest)</code></a></li>
<li><a href="#all_util_textencoderencoding"><code>textEncoder.encoding</code></a></li>
</ul>
</li>
<li><a href="#all_util_utiltousvstringstring"><code>util.toUSVString(string)</code></a></li>
<li><span class="stability_1"><a href="#all_util_utiltransferableabortcontroller"><code>util.transferableAbortController()</code></a></span></li>
<li><span class="stability_1"><a href="#all_util_utiltransferableabortsignalsignal"><code>util.transferableAbortSignal(signal)</code></a></span></li>
<li><span class="stability_1"><a href="#all_util_utilabortedsignal-resource"><code>util.aborted(signal, resource)</code></a></span></li>
<li><a href="#all_util_utiltypes"><code>util.types</code></a>
<ul>
<li><a href="#all_util_utiltypesisanyarraybuffervalue"><code>util.types.isAnyArrayBuffer(value)</code></a></li>
<li><a href="#all_util_utiltypesisarraybufferviewvalue"><code>util.types.isArrayBufferView(value)</code></a></li>
<li><a href="#all_util_utiltypesisargumentsobjectvalue"><code>util.types.isArgumentsObject(value)</code></a></li>
<li><a href="#all_util_utiltypesisarraybuffervalue"><code>util.types.isArrayBuffer(value)</code></a></li>
<li><a href="#all_util_utiltypesisasyncfunctionvalue"><code>util.types.isAsyncFunction(value)</code></a></li>
<li><a href="#all_util_utiltypesisbigint64arrayvalue"><code>util.types.isBigInt64Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisbigintobjectvalue"><code>util.types.isBigIntObject(value)</code></a></li>
<li><a href="#all_util_utiltypesisbiguint64arrayvalue"><code>util.types.isBigUint64Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisbooleanobjectvalue"><code>util.types.isBooleanObject(value)</code></a></li>
<li><a href="#all_util_utiltypesisboxedprimitivevalue"><code>util.types.isBoxedPrimitive(value)</code></a></li>
<li><a href="#all_util_utiltypesiscryptokeyvalue"><code>util.types.isCryptoKey(value)</code></a></li>
<li><a href="#all_util_utiltypesisdataviewvalue"><code>util.types.isDataView(value)</code></a></li>
<li><a href="#all_util_utiltypesisdatevalue"><code>util.types.isDate(value)</code></a></li>
<li><a href="#all_util_utiltypesisexternalvalue"><code>util.types.isExternal(value)</code></a></li>
<li><a href="#all_util_utiltypesisfloat32arrayvalue"><code>util.types.isFloat32Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisfloat64arrayvalue"><code>util.types.isFloat64Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisgeneratorfunctionvalue"><code>util.types.isGeneratorFunction(value)</code></a></li>
<li><a href="#all_util_utiltypesisgeneratorobjectvalue"><code>util.types.isGeneratorObject(value)</code></a></li>
<li><a href="#all_util_utiltypesisint8arrayvalue"><code>util.types.isInt8Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisint16arrayvalue"><code>util.types.isInt16Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisint32arrayvalue"><code>util.types.isInt32Array(value)</code></a></li>
<li><a href="#all_util_utiltypesiskeyobjectvalue"><code>util.types.isKeyObject(value)</code></a></li>
<li><a href="#all_util_utiltypesismapvalue"><code>util.types.isMap(value)</code></a></li>
<li><a href="#all_util_utiltypesismapiteratorvalue"><code>util.types.isMapIterator(value)</code></a></li>
<li><a href="#all_util_utiltypesismodulenamespaceobjectvalue"><code>util.types.isModuleNamespaceObject(value)</code></a></li>
<li><a href="#all_util_utiltypesisnativeerrorvalue"><code>util.types.isNativeError(value)</code></a></li>
<li><a href="#all_util_utiltypesisnumberobjectvalue"><code>util.types.isNumberObject(value)</code></a></li>
<li><a href="#all_util_utiltypesispromisevalue"><code>util.types.isPromise(value)</code></a></li>
<li><a href="#all_util_utiltypesisproxyvalue"><code>util.types.isProxy(value)</code></a></li>
<li><a href="#all_util_utiltypesisregexpvalue"><code>util.types.isRegExp(value)</code></a></li>
<li><a href="#all_util_utiltypesissetvalue"><code>util.types.isSet(value)</code></a></li>
<li><a href="#all_util_utiltypesissetiteratorvalue"><code>util.types.isSetIterator(value)</code></a></li>
<li><a href="#all_util_utiltypesissharedarraybuffervalue"><code>util.types.isSharedArrayBuffer(value)</code></a></li>
<li><a href="#all_util_utiltypesisstringobjectvalue"><code>util.types.isStringObject(value)</code></a></li>
<li><a href="#all_util_utiltypesissymbolobjectvalue"><code>util.types.isSymbolObject(value)</code></a></li>
<li><a href="#all_util_utiltypesistypedarrayvalue"><code>util.types.isTypedArray(value)</code></a></li>
<li><a href="#all_util_utiltypesisuint8arrayvalue"><code>util.types.isUint8Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisuint8clampedarrayvalue"><code>util.types.isUint8ClampedArray(value)</code></a></li>
<li><a href="#all_util_utiltypesisuint16arrayvalue"><code>util.types.isUint16Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisuint32arrayvalue"><code>util.types.isUint32Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisweakmapvalue"><code>util.types.isWeakMap(value)</code></a></li>
<li><a href="#all_util_utiltypesisweaksetvalue"><code>util.types.isWeakSet(value)</code></a></li>
</ul>
</li>
<li><a href="#all_util_deprecated-apis">Deprecated APIs</a>
<ul>
<li><span class="stability_0"><a href="#all_util_util_extendtarget-source"><code>util._extend(target, source)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisarrayobject"><code>util.isArray(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisbooleanobject"><code>util.isBoolean(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisbufferobject"><code>util.isBuffer(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisdateobject"><code>util.isDate(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utiliserrorobject"><code>util.isError(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisfunctionobject"><code>util.isFunction(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisnullobject"><code>util.isNull(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisnullorundefinedobject"><code>util.isNullOrUndefined(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisnumberobject"><code>util.isNumber(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisobjectobject"><code>util.isObject(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisprimitiveobject"><code>util.isPrimitive(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisregexpobject"><code>util.isRegExp(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisstringobject"><code>util.isString(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilissymbolobject"><code>util.isSymbol(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisundefinedobject"><code>util.isUndefined(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utillogstring"><code>util.log(string)</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_v8_v8">V8</a>
<ul>
<li><a href="#all_v8_v8cacheddataversiontag"><code>v8.cachedDataVersionTag()</code></a></li>
<li><a href="#all_v8_v8getheapcodestatistics"><code>v8.getHeapCodeStatistics()</code></a></li>
<li><a href="#all_v8_v8getheapsnapshotoptions"><code>v8.getHeapSnapshot([options])</code></a></li>
<li><a href="#all_v8_v8getheapspacestatistics"><code>v8.getHeapSpaceStatistics()</code></a></li>
<li><a href="#all_v8_v8getheapstatistics"><code>v8.getHeapStatistics()</code></a></li>
<li><span class="stability_1"><a href="#all_v8_v8queryobjectsctor-options"><code>v8.queryObjects(ctor[, options])</code></a></span></li>
<li><a href="#all_v8_v8setflagsfromstringflags"><code>v8.setFlagsFromString(flags)</code></a></li>
<li><a href="#all_v8_v8stopcoverage"><code>v8.stopCoverage()</code></a></li>
<li><a href="#all_v8_v8takecoverage"><code>v8.takeCoverage()</code></a></li>
<li><a href="#all_v8_v8writeheapsnapshotfilenameoptions"><code>v8.writeHeapSnapshot([filename[,options]])</code></a></li>
<li><span class="stability_1"><a href="#all_v8_v8setheapsnapshotnearheaplimitlimit"><code>v8.setHeapSnapshotNearHeapLimit(limit)</code></a></span></li>
<li><a href="#all_v8_serialization-api">Serialization API</a>
<ul>
<li><a href="#all_v8_v8serializevalue"><code>v8.serialize(value)</code></a></li>
<li><a href="#all_v8_v8deserializebuffer"><code>v8.deserialize(buffer)</code></a></li>
<li><a href="#all_v8_class-v8serializer">Class: <code>v8.Serializer</code></a>
<ul>
<li><a href="#all_v8_new-serializer"><code>new Serializer()</code></a></li>
<li><a href="#all_v8_serializerwriteheader"><code>serializer.writeHeader()</code></a></li>
<li><a href="#all_v8_serializerwritevaluevalue"><code>serializer.writeValue(value)</code></a></li>
<li><a href="#all_v8_serializerreleasebuffer"><code>serializer.releaseBuffer()</code></a></li>
<li><a href="#all_v8_serializertransferarraybufferid-arraybuffer"><code>serializer.transferArrayBuffer(id, arrayBuffer)</code></a></li>
<li><a href="#all_v8_serializerwriteuint32value"><code>serializer.writeUint32(value)</code></a></li>
<li><a href="#all_v8_serializerwriteuint64hi-lo"><code>serializer.writeUint64(hi, lo)</code></a></li>
<li><a href="#all_v8_serializerwritedoublevalue"><code>serializer.writeDouble(value)</code></a></li>
<li><a href="#all_v8_serializerwriterawbytesbuffer"><code>serializer.writeRawBytes(buffer)</code></a></li>
<li><a href="#all_v8_serializer_writehostobjectobject"><code>serializer._writeHostObject(object)</code></a></li>
<li><a href="#all_v8_serializer_getdatacloneerrormessage"><code>serializer._getDataCloneError(message)</code></a></li>
<li><a href="#all_v8_serializer_getsharedarraybufferidsharedarraybuffer"><code>serializer._getSharedArrayBufferId(sharedArrayBuffer)</code></a></li>
<li><a href="#all_v8_serializer_settreatarraybufferviewsashostobjectsflag"><code>serializer._setTreatArrayBufferViewsAsHostObjects(flag)</code></a></li>
</ul>
</li>
<li><a href="#all_v8_class-v8deserializer">Class: <code>v8.Deserializer</code></a>
<ul>
<li><a href="#all_v8_new-deserializerbuffer"><code>new Deserializer(buffer)</code></a></li>
<li><a href="#all_v8_deserializerreadheader"><code>deserializer.readHeader()</code></a></li>
<li><a href="#all_v8_deserializerreadvalue"><code>deserializer.readValue()</code></a></li>
<li><a href="#all_v8_deserializertransferarraybufferid-arraybuffer"><code>deserializer.transferArrayBuffer(id, arrayBuffer)</code></a></li>
<li><a href="#all_v8_deserializergetwireformatversion"><code>deserializer.getWireFormatVersion()</code></a></li>
<li><a href="#all_v8_deserializerreaduint32"><code>deserializer.readUint32()</code></a></li>
<li><a href="#all_v8_deserializerreaduint64"><code>deserializer.readUint64()</code></a></li>
<li><a href="#all_v8_deserializerreaddouble"><code>deserializer.readDouble()</code></a></li>
<li><a href="#all_v8_deserializerreadrawbyteslength"><code>deserializer.readRawBytes(length)</code></a></li>
<li><a href="#all_v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a></li>
</ul>
</li>
<li><a href="#all_v8_class-v8defaultserializer">Class: <code>v8.DefaultSerializer</code></a></li>
<li><a href="#all_v8_class-v8defaultdeserializer">Class: <code>v8.DefaultDeserializer</code></a></li>
</ul>
</li>
<li><a href="#all_v8_promise-hooks">Promise hooks</a>
<ul>
<li><a href="#all_v8_promisehooksoninitinit"><code>promiseHooks.onInit(init)</code></a></li>
<li><a href="#all_v8_promisehooksonsettledsettled"><code>promiseHooks.onSettled(settled)</code></a></li>
<li><a href="#all_v8_promisehooksonbeforebefore"><code>promiseHooks.onBefore(before)</code></a></li>
<li><a href="#all_v8_promisehooksonafterafter"><code>promiseHooks.onAfter(after)</code></a></li>
<li><a href="#all_v8_promisehookscreatehookcallbacks"><code>promiseHooks.createHook(callbacks)</code></a></li>
<li><a href="#all_v8_hook-callbacks">Hook callbacks</a>
<ul>
<li><a href="#all_v8_initpromise-parent"><code>init(promise, parent)</code></a></li>
<li><a href="#all_v8_beforepromise"><code>before(promise)</code></a></li>
<li><a href="#all_v8_afterpromise"><code>after(promise)</code></a></li>
<li><a href="#all_v8_settledpromise"><code>settled(promise)</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_v8_startup-snapshot-api">Startup Snapshot API</a></span>
<ul>
<li><a href="#all_v8_v8startupsnapshotaddserializecallbackcallback-data"><code>v8.startupSnapshot.addSerializeCallback(callback[, data])</code></a></li>
<li><a href="#all_v8_v8startupsnapshotadddeserializecallbackcallback-data"><code>v8.startupSnapshot.addDeserializeCallback(callback[, data])</code></a></li>
<li><a href="#all_v8_v8startupsnapshotsetdeserializemainfunctioncallback-data"><code>v8.startupSnapshot.setDeserializeMainFunction(callback[, data])</code></a></li>
<li><a href="#all_v8_v8startupsnapshotisbuildingsnapshot"><code>v8.startupSnapshot.isBuildingSnapshot()</code></a></li>
</ul>
</li>
<li><a href="#all_v8_class-v8gcprofiler">Class: <code>v8.GCProfiler</code></a>
<ul>
<li><a href="#all_v8_new-v8gcprofiler"><code>new v8.GCProfiler()</code></a></li>
<li><a href="#all_v8_profilerstart"><code>profiler.start()</code></a></li>
<li><a href="#all_v8_profilerstop"><code>profiler.stop()</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_vm_vm-executing-javascript">VM (executing JavaScript)</a></span>
<ul>
<li><a href="#all_vm_class-vmscript">Class: <code>vm.Script</code></a>
<ul>
<li><a href="#all_vm_new-vmscriptcode-options"><code>new vm.Script(code[, options])</code></a></li>
<li><a href="#all_vm_scriptcacheddatarejected"><code>script.cachedDataRejected</code></a></li>
<li><a href="#all_vm_scriptcreatecacheddata"><code>script.createCachedData()</code></a></li>
<li><a href="#all_vm_scriptrunincontextcontextifiedobject-options"><code>script.runInContext(contextifiedObject[, options])</code></a></li>
<li><a href="#all_vm_scriptruninnewcontextcontextobject-options"><code>script.runInNewContext([contextObject[, options]])</code></a></li>
<li><a href="#all_vm_scriptruninthiscontextoptions"><code>script.runInThisContext([options])</code></a></li>
<li><a href="#all_vm_scriptsourcemapurl"><code>script.sourceMapURL</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_vm_class-vmmodule">Class: <code>vm.Module</code></a></span>
<ul>
<li><a href="#all_vm_moduledependencyspecifiers"><code>module.dependencySpecifiers</code></a></li>
<li><a href="#all_vm_moduleerror"><code>module.error</code></a></li>
<li><a href="#all_vm_moduleevaluateoptions"><code>module.evaluate([options])</code></a></li>
<li><a href="#all_vm_moduleidentifier"><code>module.identifier</code></a></li>
<li><a href="#all_vm_modulelinklinker"><code>module.link(linker)</code></a></li>
<li><a href="#all_vm_modulenamespace"><code>module.namespace</code></a></li>
<li><a href="#all_vm_modulestatus"><code>module.status</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_vm_class-vmsourcetextmodule">Class: <code>vm.SourceTextModule</code></a></span>
<ul>
<li><a href="#all_vm_new-vmsourcetextmodulecode-options"><code>new vm.SourceTextModule(code[, options])</code></a></li>
<li><a href="#all_vm_sourcetextmodulecreatecacheddata"><code>sourceTextModule.createCachedData()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_vm_class-vmsyntheticmodule">Class: <code>vm.SyntheticModule</code></a></span>
<ul>
<li><a href="#all_vm_new-vmsyntheticmoduleexportnames-evaluatecallback-options"><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code></a></li>
<li><a href="#all_vm_syntheticmodulesetexportname-value"><code>syntheticModule.setExport(name, value)</code></a></li>
</ul>
</li>
<li><a href="#all_vm_vmcompilefunctioncode-params-options"><code>vm.compileFunction(code[, params[, options]])</code></a></li>
<li><a href="#all_vm_vmconstants"><code>vm.constants</code></a>
<ul>
<li><span class="stability_1"><a href="#all_vm_vmconstantsuse_main_context_default_loader"><code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code></a></span></li>
</ul>
</li>
<li><a href="#all_vm_vmcreatecontextcontextobject-options"><code>vm.createContext([contextObject[, options]])</code></a></li>
<li><a href="#all_vm_vmiscontextobject"><code>vm.isContext(object)</code></a></li>
<li><span class="stability_1"><a href="#all_vm_vmmeasurememoryoptions"><code>vm.measureMemory([options])</code></a></span></li>
<li><a href="#all_vm_vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext(code, contextifiedObject[, options])</code></a></li>
<li><a href="#all_vm_vmruninnewcontextcode-contextobject-options"><code>vm.runInNewContext(code[, contextObject[, options]])</code></a></li>
<li><a href="#all_vm_vmruninthiscontextcode-options"><code>vm.runInThisContext(code[, options])</code></a></li>
<li><a href="#all_vm_example-running-an-http-server-within-a-vm">Example: Running an HTTP server within a VM</a></li>
<li><a href="#all_vm_what-does-it-mean-to-contextify-an-object">What does it mean to "contextify" an object?</a>
<ul>
<li><a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a></li>
</ul>
</li>
<li><a href="#all_vm_timeout-interactions-with-asynchronous-tasks-and-promises">Timeout interactions with asynchronous tasks and Promises</a></li>
<li><a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>
<ul>
<li><a href="#all_vm_when-the-importmoduledynamically-option-is-not-specified-or-undefined">When the <code>importModuleDynamically</code> option is not specified or undefined</a></li>
<li><a href="#all_vm_when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader">When <code>importModuleDynamically</code> is <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code></a></li>
<li><a href="#all_vm_when-importmoduledynamically-is-a-function">When <code>importModuleDynamically</code> is a function</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_wasi_webassembly-system-interface-wasi">WebAssembly System Interface (WASI)</a></span>
<ul>
<li><a href="#all_wasi_security">Security</a></li>
<li><a href="#all_wasi_class-wasi">Class: <code>WASI</code></a>
<ul>
<li><a href="#all_wasi_new-wasioptions"><code>new WASI([options])</code></a></li>
<li><a href="#all_wasi_wasigetimportobject"><code>wasi.getImportObject()</code></a></li>
<li><a href="#all_wasi_wasistartinstance"><code>wasi.start(instance)</code></a></li>
<li><a href="#all_wasi_wasiinitializeinstance"><code>wasi.initialize(instance)</code></a></li>
<li><a href="#all_wasi_wasiwasiimport"><code>wasi.wasiImport</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_webcrypto_web-crypto-api">Web Crypto API</a></span>
<ul>
<li><a href="#all_webcrypto_examples">Examples</a>
<ul>
<li><a href="#all_webcrypto_generating-keys">Generating keys</a>
<ul>
<li><a href="#all_webcrypto_aes-keys">AES keys</a></li>
<li><a href="#all_webcrypto_ecdsa-key-pairs">ECDSA key pairs</a></li>
<li><span class="stability_1"><a href="#all_webcrypto_ed25519ed448x25519x448-key-pairs">Ed25519/Ed448/X25519/X448 key pairs</a></span></li>
<li><a href="#all_webcrypto_hmac-keys">HMAC keys</a></li>
<li><a href="#all_webcrypto_rsa-key-pairs">RSA key pairs</a></li>
</ul>
</li>
<li><a href="#all_webcrypto_encryption-and-decryption">Encryption and decryption</a></li>
<li><a href="#all_webcrypto_exporting-and-importing-keys">Exporting and importing keys</a></li>
<li><a href="#all_webcrypto_wrapping-and-unwrapping-keys">Wrapping and unwrapping keys</a></li>
<li><a href="#all_webcrypto_sign-and-verify">Sign and verify</a></li>
<li><a href="#all_webcrypto_deriving-bits-and-keys">Deriving bits and keys</a></li>
<li><a href="#all_webcrypto_digest">Digest</a></li>
</ul>
</li>
<li><a href="#all_webcrypto_algorithm-matrix">Algorithm matrix</a></li>
<li><a href="#all_webcrypto_class-crypto">Class: <code>Crypto</code></a>
<ul>
<li><a href="#all_webcrypto_cryptosubtle"><code>crypto.subtle</code></a></li>
<li><a href="#all_webcrypto_cryptogetrandomvaluestypedarray"><code>crypto.getRandomValues(typedArray)</code></a></li>
<li><a href="#all_webcrypto_cryptorandomuuid"><code>crypto.randomUUID()</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-cryptokey">Class: <code>CryptoKey</code></a>
<ul>
<li><a href="#all_webcrypto_cryptokeyalgorithm"><code>cryptoKey.algorithm</code></a></li>
<li><a href="#all_webcrypto_cryptokeyextractable"><code>cryptoKey.extractable</code></a></li>
<li><a href="#all_webcrypto_cryptokeytype"><code>cryptoKey.type</code></a></li>
<li><a href="#all_webcrypto_cryptokeyusages"><code>cryptoKey.usages</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-cryptokeypair">Class: <code>CryptoKeyPair</code></a>
<ul>
<li><a href="#all_webcrypto_cryptokeypairprivatekey"><code>cryptoKeyPair.privateKey</code></a></li>
<li><a href="#all_webcrypto_cryptokeypairpublickey"><code>cryptoKeyPair.publicKey</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-subtlecrypto">Class: <code>SubtleCrypto</code></a>
<ul>
<li><a href="#all_webcrypto_subtledecryptalgorithm-key-data"><code>subtle.decrypt(algorithm, key, data)</code></a></li>
<li><a href="#all_webcrypto_subtlederivebitsalgorithm-basekey-length"><code>subtle.deriveBits(algorithm, baseKey[, length])</code></a></li>
<li><a href="#all_webcrypto_subtlederivekeyalgorithm-basekey-derivedkeyalgorithm-extractable-keyusages"><code>subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)</code></a></li>
<li><a href="#all_webcrypto_subtledigestalgorithm-data"><code>subtle.digest(algorithm, data)</code></a></li>
<li><a href="#all_webcrypto_subtleencryptalgorithm-key-data"><code>subtle.encrypt(algorithm, key, data)</code></a></li>
<li><a href="#all_webcrypto_subtleexportkeyformat-key"><code>subtle.exportKey(format, key)</code></a></li>
<li><a href="#all_webcrypto_subtlegeneratekeyalgorithm-extractable-keyusages"><code>subtle.generateKey(algorithm, extractable, keyUsages)</code></a></li>
<li><a href="#all_webcrypto_subtleimportkeyformat-keydata-algorithm-extractable-keyusages"><code>subtle.importKey(format, keyData, algorithm, extractable, keyUsages)</code></a></li>
<li><a href="#all_webcrypto_subtlesignalgorithm-key-data"><code>subtle.sign(algorithm, key, data)</code></a></li>
<li><a href="#all_webcrypto_subtleunwrapkeyformat-wrappedkey-unwrappingkey-unwrapalgo-unwrappedkeyalgo-extractable-keyusages"><code>subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)</code></a></li>
<li><a href="#all_webcrypto_subtleverifyalgorithm-key-signature-data"><code>subtle.verify(algorithm, key, signature, data)</code></a></li>
<li><a href="#all_webcrypto_subtlewrapkeyformat-key-wrappingkey-wrapalgo"><code>subtle.wrapKey(format, key, wrappingKey, wrapAlgo)</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_algorithm-parameters">Algorithm parameters</a>
<ul>
<li><a href="#all_webcrypto_class-algorithmidentifier">Class: <code>AlgorithmIdentifier</code></a>
<ul>
<li><a href="#all_webcrypto_algorithmidentifiername"><code>algorithmIdentifier.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-aescbcparams">Class: <code>AesCbcParams</code></a>
<ul>
<li><a href="#all_webcrypto_aescbcparamsiv"><code>aesCbcParams.iv</code></a></li>
<li><a href="#all_webcrypto_aescbcparamsname"><code>aesCbcParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-aesctrparams">Class: <code>AesCtrParams</code></a>
<ul>
<li><a href="#all_webcrypto_aesctrparamscounter"><code>aesCtrParams.counter</code></a></li>
<li><a href="#all_webcrypto_aesctrparamslength"><code>aesCtrParams.length</code></a></li>
<li><a href="#all_webcrypto_aesctrparamsname"><code>aesCtrParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-aesgcmparams">Class: <code>AesGcmParams</code></a>
<ul>
<li><a href="#all_webcrypto_aesgcmparamsadditionaldata"><code>aesGcmParams.additionalData</code></a></li>
<li><a href="#all_webcrypto_aesgcmparamsiv"><code>aesGcmParams.iv</code></a></li>
<li><a href="#all_webcrypto_aesgcmparamsname"><code>aesGcmParams.name</code></a></li>
<li><a href="#all_webcrypto_aesgcmparamstaglength"><code>aesGcmParams.tagLength</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-aeskeygenparams">Class: <code>AesKeyGenParams</code></a>
<ul>
<li><a href="#all_webcrypto_aeskeygenparamslength"><code>aesKeyGenParams.length</code></a></li>
<li><a href="#all_webcrypto_aeskeygenparamsname"><code>aesKeyGenParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-ecdhkeyderiveparams">Class: <code>EcdhKeyDeriveParams</code></a>
<ul>
<li><a href="#all_webcrypto_ecdhkeyderiveparamsname"><code>ecdhKeyDeriveParams.name</code></a></li>
<li><a href="#all_webcrypto_ecdhkeyderiveparamspublic"><code>ecdhKeyDeriveParams.public</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-ecdsaparams">Class: <code>EcdsaParams</code></a>
<ul>
<li><a href="#all_webcrypto_ecdsaparamshash"><code>ecdsaParams.hash</code></a></li>
<li><a href="#all_webcrypto_ecdsaparamsname"><code>ecdsaParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-eckeygenparams">Class: <code>EcKeyGenParams</code></a>
<ul>
<li><a href="#all_webcrypto_eckeygenparamsname"><code>ecKeyGenParams.name</code></a></li>
<li><a href="#all_webcrypto_eckeygenparamsnamedcurve"><code>ecKeyGenParams.namedCurve</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-eckeyimportparams">Class: <code>EcKeyImportParams</code></a>
<ul>
<li><a href="#all_webcrypto_eckeyimportparamsname"><code>ecKeyImportParams.name</code></a></li>
<li><a href="#all_webcrypto_eckeyimportparamsnamedcurve"><code>ecKeyImportParams.namedCurve</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-ed448params">Class: <code>Ed448Params</code></a>
<ul>
<li><a href="#all_webcrypto_ed448paramsname"><code>ed448Params.name</code></a></li>
<li><a href="#all_webcrypto_ed448paramscontext"><code>ed448Params.context</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-hkdfparams">Class: <code>HkdfParams</code></a>
<ul>
<li><a href="#all_webcrypto_hkdfparamshash"><code>hkdfParams.hash</code></a></li>
<li><a href="#all_webcrypto_hkdfparamsinfo"><code>hkdfParams.info</code></a></li>
<li><a href="#all_webcrypto_hkdfparamsname"><code>hkdfParams.name</code></a></li>
<li><a href="#all_webcrypto_hkdfparamssalt"><code>hkdfParams.salt</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-hmacimportparams">Class: <code>HmacImportParams</code></a>
<ul>
<li><a href="#all_webcrypto_hmacimportparamshash"><code>hmacImportParams.hash</code></a></li>
<li><a href="#all_webcrypto_hmacimportparamslength"><code>hmacImportParams.length</code></a></li>
<li><a href="#all_webcrypto_hmacimportparamsname"><code>hmacImportParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-hmackeygenparams">Class: <code>HmacKeyGenParams</code></a>
<ul>
<li><a href="#all_webcrypto_hmackeygenparamshash"><code>hmacKeyGenParams.hash</code></a></li>
<li><a href="#all_webcrypto_hmackeygenparamslength"><code>hmacKeyGenParams.length</code></a></li>
<li><a href="#all_webcrypto_hmackeygenparamsname"><code>hmacKeyGenParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-pbkdf2params">Class: <code>Pbkdf2Params</code></a>
<ul>
<li><a href="#all_webcrypto_pbkdb2paramshash"><code>pbkdb2Params.hash</code></a></li>
<li><a href="#all_webcrypto_pbkdf2paramsiterations"><code>pbkdf2Params.iterations</code></a></li>
<li><a href="#all_webcrypto_pbkdf2paramsname"><code>pbkdf2Params.name</code></a></li>
<li><a href="#all_webcrypto_pbkdf2paramssalt"><code>pbkdf2Params.salt</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-rsahashedimportparams">Class: <code>RsaHashedImportParams</code></a>
<ul>
<li><a href="#all_webcrypto_rsahashedimportparamshash"><code>rsaHashedImportParams.hash</code></a></li>
<li><a href="#all_webcrypto_rsahashedimportparamsname"><code>rsaHashedImportParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-rsahashedkeygenparams">Class: <code>RsaHashedKeyGenParams</code></a>
<ul>
<li><a href="#all_webcrypto_rsahashedkeygenparamshash"><code>rsaHashedKeyGenParams.hash</code></a></li>
<li><a href="#all_webcrypto_rsahashedkeygenparamsmoduluslength"><code>rsaHashedKeyGenParams.modulusLength</code></a></li>
<li><a href="#all_webcrypto_rsahashedkeygenparamsname"><code>rsaHashedKeyGenParams.name</code></a></li>
<li><a href="#all_webcrypto_rsahashedkeygenparamspublicexponent"><code>rsaHashedKeyGenParams.publicExponent</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-rsaoaepparams">Class: <code>RsaOaepParams</code></a>
<ul>
<li><a href="#all_webcrypto_rsaoaepparamslabel"><code>rsaOaepParams.label</code></a></li>
<li><a href="#all_webcrypto_rsaoaepparamsname"><code>rsaOaepParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-rsapssparams">Class: <code>RsaPssParams</code></a>
<ul>
<li><a href="#all_webcrypto_rsapssparamsname"><code>rsaPssParams.name</code></a></li>
<li><a href="#all_webcrypto_rsapssparamssaltlength"><code>rsaPssParams.saltLength</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_webstreams_web-streams-api">Web Streams API</a></span>
<ul>
<li><a href="#all_webstreams_overview">Overview</a>
<ul>
<li><a href="#all_webstreams_example-readablestream">Example <code>ReadableStream</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_api">API</a>
<ul>
<li><a href="#all_webstreams_class-readablestream">Class: <code>ReadableStream</code></a>
<ul>
<li><a href="#all_webstreams_new-readablestreamunderlyingsource--strategy"><code>new ReadableStream([underlyingSource [, strategy]])</code></a></li>
<li><a href="#all_webstreams_readablestreamlocked"><code>readableStream.locked</code></a></li>
<li><a href="#all_webstreams_readablestreamcancelreason"><code>readableStream.cancel([reason])</code></a></li>
<li><a href="#all_webstreams_readablestreamgetreaderoptions"><code>readableStream.getReader([options])</code></a></li>
<li><a href="#all_webstreams_readablestreampipethroughtransform-options"><code>readableStream.pipeThrough(transform[, options])</code></a></li>
<li><a href="#all_webstreams_readablestreampipetodestination-options"><code>readableStream.pipeTo(destination[, options])</code></a></li>
<li><a href="#all_webstreams_readablestreamtee"><code>readableStream.tee()</code></a></li>
<li><a href="#all_webstreams_readablestreamvaluesoptions"><code>readableStream.values([options])</code></a></li>
<li><a href="#all_webstreams_async-iteration">Async Iteration</a></li>
<li><a href="#all_webstreams_transferring-with-postmessage">Transferring with <code>postMessage()</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_readablestreamfromiterable"><code>ReadableStream.from(iterable)</code></a></li>
<li><a href="#all_webstreams_class-readablestreamdefaultreader">Class: <code>ReadableStreamDefaultReader</code></a>
<ul>
<li><a href="#all_webstreams_new-readablestreamdefaultreaderstream"><code>new ReadableStreamDefaultReader(stream)</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultreadercancelreason"><code>readableStreamDefaultReader.cancel([reason])</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultreaderclosed"><code>readableStreamDefaultReader.closed</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultreaderread"><code>readableStreamDefaultReader.read()</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultreaderreleaselock"><code>readableStreamDefaultReader.releaseLock()</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-readablestreambyobreader">Class: <code>ReadableStreamBYOBReader</code></a>
<ul>
<li><a href="#all_webstreams_new-readablestreambyobreaderstream"><code>new ReadableStreamBYOBReader(stream)</code></a></li>
<li><a href="#all_webstreams_readablestreambyobreadercancelreason"><code>readableStreamBYOBReader.cancel([reason])</code></a></li>
<li><a href="#all_webstreams_readablestreambyobreaderclosed"><code>readableStreamBYOBReader.closed</code></a></li>
<li><a href="#all_webstreams_readablestreambyobreaderreadview-options"><code>readableStreamBYOBReader.read(view[, options])</code></a></li>
<li><a href="#all_webstreams_readablestreambyobreaderreleaselock"><code>readableStreamBYOBReader.releaseLock()</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-readablestreamdefaultcontroller">Class: <code>ReadableStreamDefaultController</code></a>
<ul>
<li><a href="#all_webstreams_readablestreamdefaultcontrollerclose"><code>readableStreamDefaultController.close()</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultcontrollerdesiredsize"><code>readableStreamDefaultController.desiredSize</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultcontrollerenqueuechunk"><code>readableStreamDefaultController.enqueue([chunk])</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultcontrollererrorerror"><code>readableStreamDefaultController.error([error])</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-readablebytestreamcontroller">Class: <code>ReadableByteStreamController</code></a>
<ul>
<li><a href="#all_webstreams_readablebytestreamcontrollerbyobrequest"><code>readableByteStreamController.byobRequest</code></a></li>
<li><a href="#all_webstreams_readablebytestreamcontrollerclose"><code>readableByteStreamController.close()</code></a></li>
<li><a href="#all_webstreams_readablebytestreamcontrollerdesiredsize"><code>readableByteStreamController.desiredSize</code></a></li>
<li><a href="#all_webstreams_readablebytestreamcontrollerenqueuechunk"><code>readableByteStreamController.enqueue(chunk)</code></a></li>
<li><a href="#all_webstreams_readablebytestreamcontrollererrorerror"><code>readableByteStreamController.error([error])</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-readablestreambyobrequest">Class: <code>ReadableStreamBYOBRequest</code></a>
<ul>
<li><a href="#all_webstreams_readablestreambyobrequestrespondbyteswritten"><code>readableStreamBYOBRequest.respond(bytesWritten)</code></a></li>
<li><a href="#all_webstreams_readablestreambyobrequestrespondwithnewviewview"><code>readableStreamBYOBRequest.respondWithNewView(view)</code></a></li>
<li><a href="#all_webstreams_readablestreambyobrequestview"><code>readableStreamBYOBRequest.view</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-writablestream">Class: <code>WritableStream</code></a>
<ul>
<li><a href="#all_webstreams_new-writablestreamunderlyingsink-strategy"><code>new WritableStream([underlyingSink[, strategy]])</code></a></li>
<li><a href="#all_webstreams_writablestreamabortreason"><code>writableStream.abort([reason])</code></a></li>
<li><a href="#all_webstreams_writablestreamclose"><code>writableStream.close()</code></a></li>
<li><a href="#all_webstreams_writablestreamgetwriter"><code>writableStream.getWriter()</code></a></li>
<li><a href="#all_webstreams_writablestreamlocked"><code>writableStream.locked</code></a></li>
<li><a href="#all_webstreams_transferring-with-postmessage_1">Transferring with postMessage()</a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-writablestreamdefaultwriter">Class: <code>WritableStreamDefaultWriter</code></a>
<ul>
<li><a href="#all_webstreams_new-writablestreamdefaultwriterstream"><code>new WritableStreamDefaultWriter(stream)</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterabortreason"><code>writableStreamDefaultWriter.abort([reason])</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterclose"><code>writableStreamDefaultWriter.close()</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterclosed"><code>writableStreamDefaultWriter.closed</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterdesiredsize"><code>writableStreamDefaultWriter.desiredSize</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterready"><code>writableStreamDefaultWriter.ready</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterreleaselock"><code>writableStreamDefaultWriter.releaseLock()</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterwritechunk"><code>writableStreamDefaultWriter.write([chunk])</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-writablestreamdefaultcontroller">Class: <code>WritableStreamDefaultController</code></a>
<ul>
<li><a href="#all_webstreams_writablestreamdefaultcontrollererrorerror"><code>writableStreamDefaultController.error([error])</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultcontrollersignal"><code>writableStreamDefaultController.signal</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-transformstream">Class: <code>TransformStream</code></a>
<ul>
<li><a href="#all_webstreams_new-transformstreamtransformer-writablestrategy-readablestrategy"><code>new TransformStream([transformer[, writableStrategy[, readableStrategy]]])</code></a></li>
<li><a href="#all_webstreams_transformstreamreadable"><code>transformStream.readable</code></a></li>
<li><a href="#all_webstreams_transformstreamwritable"><code>transformStream.writable</code></a></li>
<li><a href="#all_webstreams_transferring-with-postmessage_2">Transferring with postMessage()</a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-transformstreamdefaultcontroller">Class: <code>TransformStreamDefaultController</code></a>
<ul>
<li><a href="#all_webstreams_transformstreamdefaultcontrollerdesiredsize"><code>transformStreamDefaultController.desiredSize</code></a></li>
<li><a href="#all_webstreams_transformstreamdefaultcontrollerenqueuechunk"><code>transformStreamDefaultController.enqueue([chunk])</code></a></li>
<li><a href="#all_webstreams_transformstreamdefaultcontrollererrorreason"><code>transformStreamDefaultController.error([reason])</code></a></li>
<li><a href="#all_webstreams_transformstreamdefaultcontrollerterminate"><code>transformStreamDefaultController.terminate()</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-bytelengthqueuingstrategy">Class: <code>ByteLengthQueuingStrategy</code></a>
<ul>
<li><a href="#all_webstreams_new-bytelengthqueuingstrategyinit"><code>new ByteLengthQueuingStrategy(init)</code></a></li>
<li><a href="#all_webstreams_bytelengthqueuingstrategyhighwatermark"><code>byteLengthQueuingStrategy.highWaterMark</code></a></li>
<li><a href="#all_webstreams_bytelengthqueuingstrategysize"><code>byteLengthQueuingStrategy.size</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-countqueuingstrategy">Class: <code>CountQueuingStrategy</code></a>
<ul>
<li><a href="#all_webstreams_new-countqueuingstrategyinit"><code>new CountQueuingStrategy(init)</code></a></li>
<li><a href="#all_webstreams_countqueuingstrategyhighwatermark"><code>countQueuingStrategy.highWaterMark</code></a></li>
<li><a href="#all_webstreams_countqueuingstrategysize"><code>countQueuingStrategy.size</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-textencoderstream">Class: <code>TextEncoderStream</code></a>
<ul>
<li><a href="#all_webstreams_new-textencoderstream"><code>new TextEncoderStream()</code></a></li>
<li><a href="#all_webstreams_textencoderstreamencoding"><code>textEncoderStream.encoding</code></a></li>
<li><a href="#all_webstreams_textencoderstreamreadable"><code>textEncoderStream.readable</code></a></li>
<li><a href="#all_webstreams_textencoderstreamwritable"><code>textEncoderStream.writable</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-textdecoderstream">Class: <code>TextDecoderStream</code></a>
<ul>
<li><a href="#all_webstreams_new-textdecoderstreamencoding-options"><code>new TextDecoderStream([encoding[, options]])</code></a></li>
<li><a href="#all_webstreams_textdecoderstreamencoding"><code>textDecoderStream.encoding</code></a></li>
<li><a href="#all_webstreams_textdecoderstreamfatal"><code>textDecoderStream.fatal</code></a></li>
<li><a href="#all_webstreams_textdecoderstreamignorebom"><code>textDecoderStream.ignoreBOM</code></a></li>
<li><a href="#all_webstreams_textdecoderstreamreadable"><code>textDecoderStream.readable</code></a></li>
<li><a href="#all_webstreams_textdecoderstreamwritable"><code>textDecoderStream.writable</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-compressionstream">Class: <code>CompressionStream</code></a>
<ul>
<li><a href="#all_webstreams_new-compressionstreamformat"><code>new CompressionStream(format)</code></a></li>
<li><a href="#all_webstreams_compressionstreamreadable"><code>compressionStream.readable</code></a></li>
<li><a href="#all_webstreams_compressionstreamwritable"><code>compressionStream.writable</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-decompressionstream">Class: <code>DecompressionStream</code></a>
<ul>
<li><a href="#all_webstreams_new-decompressionstreamformat"><code>new DecompressionStream(format)</code></a></li>
<li><a href="#all_webstreams_decompressionstreamreadable"><code>decompressionStream.readable</code></a></li>
<li><a href="#all_webstreams_decompressionstreamwritable"><code>decompressionStream.writable</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_utility-consumers">Utility Consumers</a>
<ul>
<li><a href="#all_webstreams_streamconsumersarraybufferstream"><code>streamConsumers.arrayBuffer(stream)</code></a></li>
<li><a href="#all_webstreams_streamconsumersblobstream"><code>streamConsumers.blob(stream)</code></a></li>
<li><a href="#all_webstreams_streamconsumersbufferstream"><code>streamConsumers.buffer(stream)</code></a></li>
<li><a href="#all_webstreams_streamconsumersjsonstream"><code>streamConsumers.json(stream)</code></a></li>
<li><a href="#all_webstreams_streamconsumerstextstream"><code>streamConsumers.text(stream)</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_worker_threads_worker-threads">Worker threads</a></span>
<ul>
<li><a href="#all_worker_threads_workergetenvironmentdatakey"><code>worker.getEnvironmentData(key)</code></a></li>
<li><a href="#all_worker_threads_workerismainthread"><code>worker.isMainThread</code></a></li>
<li><a href="#all_worker_threads_workermarkasuntransferableobject"><code>worker.markAsUntransferable(object)</code></a></li>
<li><a href="#all_worker_threads_workermovemessageporttocontextport-contextifiedsandbox"><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code></a></li>
<li><a href="#all_worker_threads_workerparentport"><code>worker.parentPort</code></a></li>
<li><span class="stability_1"><a href="#all_worker_threads_workerpostmessagetothreadthreadid-value-transferlist-timeout"><code>worker.postMessageToThread(threadId, value[, transferList][, timeout])</code></a></span></li>
<li><a href="#all_worker_threads_workerreceivemessageonportport"><code>worker.receiveMessageOnPort(port)</code></a></li>
<li><a href="#all_worker_threads_workerresourcelimits"><code>worker.resourceLimits</code></a></li>
<li><a href="#all_worker_threads_workershare_env"><code>worker.SHARE_ENV</code></a></li>
<li><a href="#all_worker_threads_workersetenvironmentdatakey-value"><code>worker.setEnvironmentData(key[, value])</code></a></li>
<li><a href="#all_worker_threads_workerthreadid"><code>worker.threadId</code></a></li>
<li><a href="#all_worker_threads_workerworkerdata"><code>worker.workerData</code></a></li>
<li><a href="#all_worker_threads_class-broadcastchannel-extends-eventtarget">Class: <code>BroadcastChannel extends EventTarget</code></a>
<ul>
<li><a href="#all_worker_threads_new-broadcastchannelname"><code>new BroadcastChannel(name)</code></a></li>
<li><a href="#all_worker_threads_broadcastchannelclose"><code>broadcastChannel.close()</code></a></li>
<li><a href="#all_worker_threads_broadcastchannelonmessage"><code>broadcastChannel.onmessage</code></a></li>
<li><a href="#all_worker_threads_broadcastchannelonmessageerror"><code>broadcastChannel.onmessageerror</code></a></li>
<li><a href="#all_worker_threads_broadcastchannelpostmessagemessage"><code>broadcastChannel.postMessage(message)</code></a></li>
<li><a href="#all_worker_threads_broadcastchannelref"><code>broadcastChannel.ref()</code></a></li>
<li><a href="#all_worker_threads_broadcastchannelunref"><code>broadcastChannel.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_worker_threads_class-messagechannel">Class: <code>MessageChannel</code></a></li>
<li><a href="#all_worker_threads_class-messageport">Class: <code>MessagePort</code></a>
<ul>
<li><a href="#all_worker_threads_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_worker_threads_event-message">Event: <code>'message'</code></a></li>
<li><a href="#all_worker_threads_event-messageerror">Event: <code>'messageerror'</code></a></li>
<li><a href="#all_worker_threads_portclose"><code>port.close()</code></a></li>
<li><a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>port.postMessage(value[, transferList])</code></a>
<ul>
<li><a href="#all_worker_threads_considerations-when-transferring-typedarrays-and-buffers">Considerations when transferring TypedArrays and Buffers</a></li>
<li><a href="#all_worker_threads_considerations-when-cloning-objects-with-prototypes-classes-and-accessors">Considerations when cloning objects with prototypes, classes, and accessors</a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_worker_threads_porthasref"><code>port.hasRef()</code></a></span></li>
<li><a href="#all_worker_threads_portref"><code>port.ref()</code></a></li>
<li><a href="#all_worker_threads_portstart"><code>port.start()</code></a></li>
<li><a href="#all_worker_threads_portunref"><code>port.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_worker_threads_class-worker">Class: <code>Worker</code></a>
<ul>
<li><a href="#all_worker_threads_new-workerfilename-options"><code>new Worker(filename[, options])</code></a></li>
<li><a href="#all_worker_threads_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_worker_threads_event-exit">Event: <code>'exit'</code></a></li>
<li><a href="#all_worker_threads_event-message_1">Event: <code>'message'</code></a></li>
<li><a href="#all_worker_threads_event-messageerror_1">Event: <code>'messageerror'</code></a></li>
<li><a href="#all_worker_threads_event-online">Event: <code>'online'</code></a></li>
<li><a href="#all_worker_threads_workergetheapsnapshotoptions"><code>worker.getHeapSnapshot([options])</code></a></li>
<li><a href="#all_worker_threads_workerperformance"><code>worker.performance</code></a>
<ul>
<li><a href="#all_worker_threads_performanceeventlooputilizationutilization1-utilization2"><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code></a></li>
</ul>
</li>
<li><a href="#all_worker_threads_workerpostmessagevalue-transferlist"><code>worker.postMessage(value[, transferList])</code></a></li>
<li><a href="#all_worker_threads_workerref"><code>worker.ref()</code></a></li>
<li><a href="#all_worker_threads_workerresourcelimits_1"><code>worker.resourceLimits</code></a></li>
<li><a href="#all_worker_threads_workerstderr"><code>worker.stderr</code></a></li>
<li><a href="#all_worker_threads_workerstdin"><code>worker.stdin</code></a></li>
<li><a href="#all_worker_threads_workerstdout"><code>worker.stdout</code></a></li>
<li><a href="#all_worker_threads_workerterminate"><code>worker.terminate()</code></a></li>
<li><a href="#all_worker_threads_workerthreadid_1"><code>worker.threadId</code></a></li>
<li><a href="#all_worker_threads_workerunref"><code>worker.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_worker_threads_notes">Notes</a>
<ul>
<li><a href="#all_worker_threads_synchronous-blocking-of-stdio">Synchronous blocking of stdio</a></li>
<li><a href="#all_worker_threads_launching-worker-threads-from-preload-scripts">Launching worker threads from preload scripts</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_zlib_zlib">Zlib</a></span>
<ul>
<li><a href="#all_zlib_threadpool-usage-and-performance-considerations">Threadpool usage and performance considerations</a></li>
<li><a href="#all_zlib_compressing-http-requests-and-responses">Compressing HTTP requests and responses</a></li>
<li><a href="#all_zlib_memory-usage-tuning">Memory usage tuning</a>
<ul>
<li><a href="#all_zlib_for-zlib-based-streams">For zlib-based streams</a></li>
<li><a href="#all_zlib_for-brotli-based-streams">For Brotli-based streams</a></li>
</ul>
</li>
<li><a href="#all_zlib_flushing">Flushing</a></li>
<li><a href="#all_zlib_constants">Constants</a>
<ul>
<li><a href="#all_zlib_zlib-constants">zlib constants</a></li>
<li><a href="#all_zlib_brotli-constants">Brotli constants</a>
<ul>
<li><a href="#all_zlib_flush-operations">Flush operations</a></li>
<li><a href="#all_zlib_compressor-options">Compressor options</a></li>
<li><a href="#all_zlib_decompressor-options">Decompressor options</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_zlib_class-options">Class: <code>Options</code></a></li>
<li><a href="#all_zlib_class-brotlioptions">Class: <code>BrotliOptions</code></a></li>
<li><a href="#all_zlib_class-zlibbrotlicompress">Class: <code>zlib.BrotliCompress</code></a></li>
<li><a href="#all_zlib_class-zlibbrotlidecompress">Class: <code>zlib.BrotliDecompress</code></a></li>
<li><a href="#all_zlib_class-zlibdeflate">Class: <code>zlib.Deflate</code></a></li>
<li><a href="#all_zlib_class-zlibdeflateraw">Class: <code>zlib.DeflateRaw</code></a></li>
<li><a href="#all_zlib_class-zlibgunzip">Class: <code>zlib.Gunzip</code></a></li>
<li><a href="#all_zlib_class-zlibgzip">Class: <code>zlib.Gzip</code></a></li>
<li><a href="#all_zlib_class-zlibinflate">Class: <code>zlib.Inflate</code></a></li>
<li><a href="#all_zlib_class-zlibinflateraw">Class: <code>zlib.InflateRaw</code></a></li>
<li><a href="#all_zlib_class-zlibunzip">Class: <code>zlib.Unzip</code></a></li>
<li><a href="#all_zlib_class-zlibzlibbase">Class: <code>zlib.ZlibBase</code></a>
<ul>
<li><span class="stability_0"><a href="#all_zlib_zlibbytesread"><code>zlib.bytesRead</code></a></span></li>
<li><a href="#all_zlib_zlibbyteswritten"><code>zlib.bytesWritten</code></a></li>
<li><a href="#all_zlib_zlibcrc32data-value"><code>zlib.crc32(data[, value])</code></a></li>
<li><a href="#all_zlib_zlibclosecallback"><code>zlib.close([callback])</code></a></li>
<li><a href="#all_zlib_zlibflushkind-callback"><code>zlib.flush([kind, ]callback)</code></a></li>
<li><a href="#all_zlib_zlibparamslevel-strategy-callback"><code>zlib.params(level, strategy, callback)</code></a></li>
<li><a href="#all_zlib_zlibreset"><code>zlib.reset()</code></a></li>
</ul>
</li>
<li><a href="#all_zlib_zlibconstants"><code>zlib.constants</code></a></li>
<li><a href="#all_zlib_zlibcreatebrotlicompressoptions"><code>zlib.createBrotliCompress([options])</code></a></li>
<li><a href="#all_zlib_zlibcreatebrotlidecompressoptions"><code>zlib.createBrotliDecompress([options])</code></a></li>
<li><a href="#all_zlib_zlibcreatedeflateoptions"><code>zlib.createDeflate([options])</code></a></li>
<li><a href="#all_zlib_zlibcreatedeflaterawoptions"><code>zlib.createDeflateRaw([options])</code></a></li>
<li><a href="#all_zlib_zlibcreategunzipoptions"><code>zlib.createGunzip([options])</code></a></li>
<li><a href="#all_zlib_zlibcreategzipoptions"><code>zlib.createGzip([options])</code></a></li>
<li><a href="#all_zlib_zlibcreateinflateoptions"><code>zlib.createInflate([options])</code></a></li>
<li><a href="#all_zlib_zlibcreateinflaterawoptions"><code>zlib.createInflateRaw([options])</code></a></li>
<li><a href="#all_zlib_zlibcreateunzipoptions"><code>zlib.createUnzip([options])</code></a></li>
<li><a href="#all_zlib_convenience-methods">Convenience methods</a>
<ul>
<li><a href="#all_zlib_zlibbrotlicompressbuffer-options-callback"><code>zlib.brotliCompress(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibbrotlicompresssyncbuffer-options"><code>zlib.brotliCompressSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibbrotlidecompressbuffer-options-callback"><code>zlib.brotliDecompress(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibbrotlidecompresssyncbuffer-options"><code>zlib.brotliDecompressSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibdeflatebuffer-options-callback"><code>zlib.deflate(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibdeflatesyncbuffer-options"><code>zlib.deflateSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibdeflaterawbuffer-options-callback"><code>zlib.deflateRaw(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibdeflaterawsyncbuffer-options"><code>zlib.deflateRawSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibgunzipbuffer-options-callback"><code>zlib.gunzip(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibgunzipsyncbuffer-options"><code>zlib.gunzipSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibgzipbuffer-options-callback"><code>zlib.gzip(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibgzipsyncbuffer-options"><code>zlib.gzipSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibinflatebuffer-options-callback"><code>zlib.inflate(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibinflatesyncbuffer-options"><code>zlib.inflateSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibinflaterawbuffer-options-callback"><code>zlib.inflateRaw(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibinflaterawsyncbuffer-options"><code>zlib.inflateRawSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibunzipbuffer-options-callback"><code>zlib.unzip(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibunzipsyncbuffer-options"><code>zlib.unzipSync(buffer[, options])</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</details>
<div role="main" id="apicontent">
<section><h2>About this documentation<span><a class="mark" href="#all_documentation_about-this-documentation" id="all_documentation_about-this-documentation">#</a></span><a aria-hidden="true" class="legacy" id="documentation_about_this_documentation"></a></h2>
<p>Welcome to the official API reference documentation for Node.js!</p>
<p>Node.js is a JavaScript runtime built on the <a href="https://v8.dev/">V8 JavaScript engine</a>.</p>
<section><h3>Contributing<span><a class="mark" href="#all_documentation_contributing" id="all_documentation_contributing">#</a></span><a aria-hidden="true" class="legacy" id="documentation_contributing"></a></h3>
<p>Report errors in this documentation in <a href="https://github.com/nodejs/node/issues/new">the issue tracker</a>. See
<a href="https://github.com/nodejs/node/blob/HEAD/CONTRIBUTING.md">the contributing guide</a> for directions on how to submit pull requests.</p>
</section><section><h3>Stability index<span><a class="mark" href="#all_documentation_stability-index" id="all_documentation_stability-index">#</a></span><a aria-hidden="true" class="legacy" id="documentation_stability_index"></a></h3>
<p>Throughout the documentation are indications of a section's stability. Some APIs
are so proven and so relied upon that they are unlikely to ever change at all.
Others are brand new and experimental, or known to be hazardous.</p>
<p>The stability indexes are as follows:</p>
<p></p><div class="api_stability api_stability_0">Stability: 0 - Deprecated. The feature may emit warnings. Backward
compatibility is not guaranteed.</div><p></p>
<!-- separator -->
<p></p><div class="api_stability api_stability_1">Stability: 1 - Experimental. The feature is not subject to
<a href="https://semver.org/">semantic versioning</a> rules. Non-backward compatible changes or removal may
occur in any future release. Use of the feature is not recommended in
production environments.<p>Experimental features are subdivided into stages:</p><ul>
<li>1.0 - Early development. Experimental features at this stage are unfinished
and subject to substantial change.</li>
<li>1.1 - Active development. Experimental features at this stage are nearing
minimum viability.</li>
<li>1.2 - Release candidate. Experimental features at this stage are hopefully
ready to become stable. No further breaking changes are anticipated but may
still occur in response to user feedback. We encourage user testing and
feedback so that we can know that this feature is ready to be marked as
stable.</li>
</ul><p>Experimental features leave the experimental status typically either by
graduating to stable, or are removed without a deprecation cycle.</p></div><p></p>
<!-- separator -->
<p></p><div class="api_stability api_stability_2">Stability: 2 - Stable. Compatibility with the npm ecosystem is a high
priority.</div><p></p>
<!-- separator -->
<p></p><div class="api_stability api_stability_3">Stability: 3 - Legacy. Although this feature is unlikely to be removed and is
still covered by semantic versioning guarantees, it is no longer actively
maintained, and other alternatives are available.</div><p></p>
<p>Features are marked as legacy rather than being deprecated if their use does no
harm, and they are widely relied upon within the npm ecosystem. Bugs found in
legacy features are unlikely to be fixed.</p>
<p>Use caution when making use of Experimental features, particularly when
authoring libraries. Users may not be aware that experimental features are being
used. Bugs or behavior changes may surprise users when Experimental API
modifications occur. To avoid surprises, use of an Experimental feature may need
a command-line flag. Experimental features may also emit a <a href="#all_process_event-warning">warning</a>.</p>
</section><section><h3>Stability overview<span><a class="mark" href="#all_documentation_stability-overview" id="all_documentation_stability-overview">#</a></span><a aria-hidden="true" class="legacy" id="documentation_stability_overview"></a></h3>
<!-- STABILITY_OVERVIEW_SLOT_BEGIN -->
<!-- STABILITY_OVERVIEW_SLOT_END -->
</section><section><h3>JSON output<span><a class="mark" href="#all_documentation_json-output" id="all_documentation_json-output">#</a></span><a aria-hidden="true" class="legacy" id="documentation_json_output"></a></h3>
<div class="api_metadata">
<span>Added in: v0.6.12</span>
</div>
<p>Every <code>.html</code> document has a corresponding <code>.json</code> document. This is for IDEs
and other utilities that consume the documentation.</p>
</section><section><h3>System calls and man pages<span><a class="mark" href="#all_documentation_system-calls-and-man-pages" id="all_documentation_system-calls-and-man-pages">#</a></span><a aria-hidden="true" class="legacy" id="documentation_system_calls_and_man_pages"></a></h3>
<p>Node.js functions which wrap a system call will document that. The docs link
to the corresponding man pages which describe how the system call works.</p>
<p>Most Unix system calls have Windows analogues. Still, behavior differences may
be unavoidable.</p></section>
</section>
<section><h2>Usage and example<span><a class="mark" href="#all_synopsis_usage-and-example" id="all_synopsis_usage-and-example">#</a></span><a aria-hidden="true" class="legacy" id="synopsis_usage_and_example"></a></h2>
<section><h3>Usage<span><a class="mark" href="#all_synopsis_usage" id="all_synopsis_usage">#</a></span><a aria-hidden="true" class="legacy" id="synopsis_usage"></a></h3>
<p><code>node [options] [V8 options] [script.js | -e "script" | - ] [arguments]</code></p>
<p>Please see the <a href="#all_cli_options">Command-line options</a> document for more information.</p>
</section><section><h3>Example<span><a class="mark" href="#all_synopsis_example" id="all_synopsis_example">#</a></span><a aria-hidden="true" class="legacy" id="synopsis_example"></a></h3>
<p>An example of a <a href="http.html">web server</a> written with Node.js which responds with
<code>'Hello, World!'</code>:</p>
<p>Commands in this document start with <code>$</code> or <code>></code> to replicate how they would
appear in a user's terminal. Do not include the <code>$</code> and <code>></code> characters. They are
there to show the start of each command.</p>
<p>Lines that don't start with <code>$</code> or <code>></code> character show the output of the previous
command.</p>
<p>First, make sure to have downloaded and installed Node.js. See
<a href="https://nodejs.org/en/download/package-manager/">Installing Node.js via package manager</a> for further install information.</p>
<p>Now, create an empty project folder called <code>projects</code>, then navigate into it.</p>
<p>Linux and Mac:</p>
<pre><code class="language-bash"><span class="hljs-built_in">mkdir</span> ~/projects
<span class="hljs-built_in">cd</span> ~/projects</code> <button class="copy-button">copy</button></pre>
<p>Windows CMD:</p>
<pre><code class="language-powershell">mkdir %USERPROFILE%\projects
<span class="hljs-built_in">cd</span> %USERPROFILE%\projects</code> <button class="copy-button">copy</button></pre>
<p>Windows PowerShell:</p>
<pre><code class="language-powershell">mkdir <span class="hljs-variable">$env:USERPROFILE</span>\projects
<span class="hljs-built_in">cd</span> <span class="hljs-variable">$env:USERPROFILE</span>\projects</code> <button class="copy-button">copy</button></pre>
<p>Next, create a new source file in the <code>projects</code>
folder and call it <code>hello-world.js</code>.</p>
<p>Open <code>hello-world.js</code> in any preferred text editor and
paste in the following content:</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> hostname = <span class="hljs-string">'127.0.0.1'</span>;
<span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</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> {
res.<span class="hljs-property">statusCode</span> = <span class="hljs-number">200</span>;
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/plain'</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Hello, World!\n'</span>);
});
server.<span class="hljs-title function_">listen</span>(port, hostname, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Server running at http://<span class="hljs-subst">${hostname}</span>:<span class="hljs-subst">${port}</span>/`</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Save the file. Then, in the terminal window, to run the <code>hello-world.js</code> file,
enter:</p>
<pre><code class="language-bash">node hello-world.js</code> <button class="copy-button">copy</button></pre>
<p>Output like this should appear in the terminal:</p>
<pre><code class="language-console">Server running at http://127.0.0.1:3000/</code> <button class="copy-button">copy</button></pre>
<p>Now, open any preferred web browser and visit <code>http://127.0.0.1:3000</code>.</p>
<p>If the browser displays the string <code>Hello, World!</code>, that indicates
the server is working.</p></section>
</section>
<section><h2>Assert<span><a class="mark" href="#all_assert_assert" id="all_assert_assert">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/assert.js">lib/assert.js</a></p>
<p>The <code>node:assert</code> module provides a set of assertion functions for verifying
invariants.</p>
<section><h3>Strict assertion mode<span><a class="mark" href="#all_assert_strict-assertion-mode" id="all_assert_strict-assertion-mode">#</a></span><a aria-hidden="true" class="legacy" id="assert_strict_assertion_mode"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Exposed as <code>require('node:assert/strict')</code>.</p></td></tr>
<tr><td>v13.9.0, v12.16.2</td>
<td><p>Changed "strict mode" to "strict assertion mode" and "legacy mode" to "legacy assertion mode" to avoid confusion with the more usual meaning of "strict mode".</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>Added error diffs to the strict assertion mode.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>Added strict assertion mode to the assert module.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p><span>Added in: v9.9.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>In strict assertion mode, non-strict methods behave like their corresponding
strict methods. For example, <a href="#all_assert_assertdeepequalactual-expected-message"><code>assert.deepEqual()</code></a> will behave like
<a href="#all_assert_assertdeepstrictequalactual-expected-message"><code>assert.deepStrictEqual()</code></a>.</p>
<p>In strict assertion mode, error messages for objects display a diff. In legacy
assertion mode, error messages for objects display the objects, often truncated.</p>
<p>To use strict assertion mode:</p>
<pre class="with-47-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> { strict <span class="hljs-keyword">as</span> assert } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>).<span class="hljs-property">strict</span>;</code><button class="copy-button">copy</button></pre>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);</code><button class="copy-button">copy</button></pre>
<p>Example error diff:</p>
<pre class="with-47-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> { strict <span class="hljs-keyword">as</span> assert } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
assert.<span class="hljs-title function_">deepEqual</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-number">5</span>], [[[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'3'</span>]], <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected ... Lines skipped</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// ...</span>
<span class="hljs-comment">// 2,</span>
<span class="hljs-comment">// + 3</span>
<span class="hljs-comment">// - '3'</span>
<span class="hljs-comment">// ],</span>
<span class="hljs-comment">// ...</span>
<span class="hljs-comment">// 5</span>
<span class="hljs-comment">// ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">deepEqual</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-number">5</span>], [[[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'3'</span>]], <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected ... Lines skipped</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// ...</span>
<span class="hljs-comment">// 2,</span>
<span class="hljs-comment">// + 3</span>
<span class="hljs-comment">// - '3'</span>
<span class="hljs-comment">// ],</span>
<span class="hljs-comment">// ...</span>
<span class="hljs-comment">// 5</span>
<span class="hljs-comment">// ]</span></code><button class="copy-button">copy</button></pre>
<p>To deactivate the colors, use the <code>NO_COLOR</code> or <code>NODE_DISABLE_COLORS</code>
environment variables. This will also deactivate the colors in the REPL. For
more on color support in terminal environments, read the tty
<a href="#all_tty_writestreamgetcolordepthenv"><code>getColorDepth()</code></a> documentation.</p>
</section><section><h3>Legacy assertion mode<span><a class="mark" href="#all_assert_legacy-assertion-mode" id="all_assert_legacy-assertion-mode">#</a></span><a aria-hidden="true" class="legacy" id="assert_legacy_assertion_mode"></a></h3>
<p>Legacy assertion mode uses the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"><code>==</code> operator</a> in:</p>
<ul>
<li><a href="#all_assert_assertdeepequalactual-expected-message"><code>assert.deepEqual()</code></a></li>
<li><a href="#all_assert_assertequalactual-expected-message"><code>assert.equal()</code></a></li>
<li><a href="#all_assert_assertnotdeepequalactual-expected-message"><code>assert.notDeepEqual()</code></a></li>
<li><a href="#all_assert_assertnotequalactual-expected-message"><code>assert.notEqual()</code></a></li>
</ul>
<p>To use legacy assertion mode:</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);</code><button class="copy-button">copy</button></pre>
<p>Legacy assertion mode may have surprising results, especially when using
<a href="#all_assert_assertdeepequalactual-expected-message"><code>assert.deepEqual()</code></a>:</p>
<pre><code class="language-js cjs"><span class="hljs-comment">// WARNING: This does not throw an AssertionError in legacy assertion mode!</span>
assert.<span class="hljs-title function_">deepEqual</span>(<span class="hljs-regexp">/a/gi</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>());</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: assert.AssertionError<a class="srclink" href="https://github.com/nodejs/node/blob/10eb2fb02ca31ee6ba14961921aae404ca57a1b5/lib/assert.js#L143">[src]</a><span><a class="mark" href="#all_assert_class-assertassertionerror" id="all_assert_class-assertassertionerror">#</a></span><a aria-hidden="true" class="legacy" id="assert_class_assert_assertionerror"></a></h3>
<ul>
<li>Extends: <a href="#all_errors_class-error" class="type"><errors.Error></a></li>
</ul>
<p>Indicates the failure of an assertion. All errors thrown by the <code>node:assert</code>
module will be instances of the <code>AssertionError</code> class.</p>
<h4><code>new assert.AssertionError(options)</code><span><a class="mark" href="#all_assert_new-assertassertionerroroptions" id="all_assert_new-assertassertionerroroptions">#</a></span><a aria-hidden="true" class="legacy" id="assert_new_assert_assertionerror_options"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.21</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>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If provided, the error message is set to this value.</li>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The <code>actual</code> property on the error instance.</li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The <code>expected</code> property on the error instance.</li>
<li><code>operator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <code>operator</code> property on the error instance.</li>
<li><code>stackStartFn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> If provided, the generated stack trace omits
frames before this function.</li>
</ul>
</li>
</ul>
<p>A subclass of <code>Error</code> that indicates the failure of an assertion.</p>
<p>All instances contain the built-in <code>Error</code> properties (<code>message</code> and <code>name</code>)
and:</p>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Set to the <code>actual</code> argument for methods such as
<a href="#all_assert_assertstrictequalactual-expected-message"><code>assert.strictEqual()</code></a>.</li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Set to the <code>expected</code> value for methods such as
<a href="#all_assert_assertstrictequalactual-expected-message"><code>assert.strictEqual()</code></a>.</li>
<li><code>generatedMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates if the message was auto-generated
(<code>true</code>) or not.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Value is always <code>ERR_ASSERTION</code> to show that the error is an
assertion error.</li>
<li><code>operator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Set to the passed in operator value.</li>
</ul>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-comment">// Generate an AssertionError to compare the error message later:</span>
<span class="hljs-keyword">const</span> { message } = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">AssertionError</span>({
<span class="hljs-attr">actual</span>: <span class="hljs-number">1</span>,
<span class="hljs-attr">expected</span>: <span class="hljs-number">2</span>,
<span class="hljs-attr">operator</span>: <span class="hljs-string">'strictEqual'</span>,
});
<span class="hljs-comment">// Verify error output:</span>
<span class="hljs-keyword">try</span> {
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-title function_">assert</span>(err <span class="hljs-keyword">instanceof</span> assert.<span class="hljs-property">AssertionError</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">message</span>, message);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">name</span>, <span class="hljs-string">'AssertionError'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">actual</span>, <span class="hljs-number">1</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">expected</span>, <span class="hljs-number">2</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">code</span>, <span class="hljs-string">'ERR_ASSERTION'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">operator</span>, <span class="hljs-string">'strictEqual'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">generatedMessage</span>, <span class="hljs-literal">true</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-comment">// Generate an AssertionError to compare the error message later:</span>
<span class="hljs-keyword">const</span> { message } = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">AssertionError</span>({
<span class="hljs-attr">actual</span>: <span class="hljs-number">1</span>,
<span class="hljs-attr">expected</span>: <span class="hljs-number">2</span>,
<span class="hljs-attr">operator</span>: <span class="hljs-string">'strictEqual'</span>,
});
<span class="hljs-comment">// Verify error output:</span>
<span class="hljs-keyword">try</span> {
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-title function_">assert</span>(err <span class="hljs-keyword">instanceof</span> assert.<span class="hljs-property">AssertionError</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">message</span>, message);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">name</span>, <span class="hljs-string">'AssertionError'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">actual</span>, <span class="hljs-number">1</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">expected</span>, <span class="hljs-number">2</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">code</span>, <span class="hljs-string">'ERR_ASSERTION'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">operator</span>, <span class="hljs-string">'strictEqual'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">generatedMessage</span>, <span class="hljs-literal">true</span>);
}</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>assert.CallTracker</code><span><a class="mark" href="#all_assert_class-assertcalltracker" id="all_assert_class-assertcalltracker">#</a></span><a aria-hidden="true" class="legacy" id="assert_class_assert_calltracker"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>the <code>assert.CallTracker</code> class has been deprecated and will be removed in a future version.</p></td></tr>
<tr><td>v14.2.0, v12.19.0</td>
<td><p><span>Added in: v14.2.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p>This feature is deprecated and will be removed in a future version.
Please consider using alternatives such as the
<a href="#all_test_mocking"><code>mock</code></a> helper function.</p>
<h4><code>new assert.CallTracker()</code><span><a class="mark" href="#all_assert_new-assertcalltracker" id="all_assert_new-assertcalltracker">#</a></span><a aria-hidden="true" class="legacy" id="assert_new_assert_calltracker"></a></h4>
<div class="api_metadata">
<span>Added in: v14.2.0, v12.19.0</span>
</div>
<p>Creates a new <a href="#all_assert_class-assertcalltracker"><code>CallTracker</code></a> object which can be used to track if functions
were called a specific number of times. The <code>tracker.verify()</code> must be called
for the verification to take place. The usual pattern would be to call it in a
<a href="#all_process_event-exit"><code>process.on('exit')</code></a> handler.</p>
<pre class="with-40-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-comment">// callsfunc() must be called exactly 1 time before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func, <span class="hljs-number">1</span>);
<span class="hljs-title function_">callsfunc</span>();
<span class="hljs-comment">// Calls tracker.verify() and verifies if all tracker.calls() functions have</span>
<span class="hljs-comment">// been called exact times.</span>
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
tracker.<span class="hljs-title function_">verify</span>();
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-comment">// callsfunc() must be called exactly 1 time before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func, <span class="hljs-number">1</span>);
<span class="hljs-title function_">callsfunc</span>();
<span class="hljs-comment">// Calls tracker.verify() and verifies if all tracker.calls() functions have</span>
<span class="hljs-comment">// been called exact times.</span>
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
tracker.<span class="hljs-title function_">verify</span>();
});</code><button class="copy-button">copy</button></pre>
<h4><code>tracker.calls([fn][, exact])</code><span><a class="mark" href="#all_assert_trackercallsfn-exact" id="all_assert_trackercallsfn-exact">#</a></span><a aria-hidden="true" class="legacy" id="assert_tracker_calls_fn_exact"></a></h4>
<div class="api_metadata">
<span>Added in: v14.2.0, v12.19.0</span>
</div>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> <strong>Default:</strong> A no-op function.</li>
<li><code>exact</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>1</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A function that wraps <code>fn</code>.</li>
</ul>
<p>The wrapper function is expected to be called exactly <code>exact</code> times. If the
function has not been called exactly <code>exact</code> times when
<a href="#all_assert_trackerverify"><code>tracker.verify()</code></a> is called, then <a href="#all_assert_trackerverify"><code>tracker.verify()</code></a> will throw an
error.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-comment">// Returns a function that wraps func() that must be called exact times</span>
<span class="hljs-comment">// before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-comment">// Returns a function that wraps func() that must be called exact times</span>
<span class="hljs-comment">// before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func);</code><button class="copy-button">copy</button></pre>
<h4><code>tracker.getCalls(fn)</code><span><a class="mark" href="#all_assert_trackergetcallsfn" id="all_assert_trackergetcallsfn">#</a></span><a aria-hidden="true" class="legacy" id="assert_tracker_getcalls_fn"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<ul>
<li>
<p><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array with all the calls to a tracked function.</p>
</li>
<li>
<p>Object <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p>
<ul>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>arguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> the arguments passed to the tracked function</li>
</ul>
</li>
</ul>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func);
<span class="hljs-title function_">callsfunc</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
assert.<span class="hljs-title function_">deepStrictEqual</span>(tracker.<span class="hljs-title function_">getCalls</span>(callsfunc),
[{ <span class="hljs-attr">thisArg</span>: <span class="hljs-literal">undefined</span>, <span class="hljs-attr">arguments</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>] }]);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func);
<span class="hljs-title function_">callsfunc</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
assert.<span class="hljs-title function_">deepStrictEqual</span>(tracker.<span class="hljs-title function_">getCalls</span>(callsfunc),
[{ <span class="hljs-attr">thisArg</span>: <span class="hljs-literal">undefined</span>, <span class="hljs-attr">arguments</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>] }]);</code><button class="copy-button">copy</button></pre>
<h4><code>tracker.report()</code><span><a class="mark" href="#all_assert_trackerreport" id="all_assert_trackerreport">#</a></span><a aria-hidden="true" class="legacy" id="assert_tracker_report"></a></h4>
<div class="api_metadata">
<span>Added in: v14.2.0, v12.19.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array of objects containing information about the wrapper
functions returned by <a href="#all_assert_trackercallsfn-exact"><code>tracker.calls()</code></a>.</li>
<li>Object <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The actual number of times the function was called.</li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of times the function was expected to be
called.</li>
<li><code>operator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the function that is wrapped.</li>
<li><code>stack</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A stack trace of the function.</li>
</ul>
</li>
</ul>
<p>The arrays contains information about the expected and actual number of calls of
the functions that have not been called the expected number of times.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-comment">// Returns a function that wraps func() that must be called exact times</span>
<span class="hljs-comment">// before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func, <span class="hljs-number">2</span>);
<span class="hljs-comment">// Returns an array containing information on callsfunc()</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(tracker.<span class="hljs-title function_">report</span>());
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">// message: 'Expected the func function to be executed 2 time(s) but was</span>
<span class="hljs-comment">// executed 0 time(s).',</span>
<span class="hljs-comment">// actual: 0,</span>
<span class="hljs-comment">// expected: 2,</span>
<span class="hljs-comment">// operator: 'func',</span>
<span class="hljs-comment">// stack: stack trace</span>
<span class="hljs-comment">// }</span>
<span class="hljs-comment">// ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-comment">// Returns a function that wraps func() that must be called exact times</span>
<span class="hljs-comment">// before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func, <span class="hljs-number">2</span>);
<span class="hljs-comment">// Returns an array containing information on callsfunc()</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(tracker.<span class="hljs-title function_">report</span>());
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">// message: 'Expected the func function to be executed 2 time(s) but was</span>
<span class="hljs-comment">// executed 0 time(s).',</span>
<span class="hljs-comment">// actual: 0,</span>
<span class="hljs-comment">// expected: 2,</span>
<span class="hljs-comment">// operator: 'func',</span>
<span class="hljs-comment">// stack: stack trace</span>
<span class="hljs-comment">// }</span>
<span class="hljs-comment">// ]</span></code><button class="copy-button">copy</button></pre>
<h4><code>tracker.reset([fn])</code><span><a class="mark" href="#all_assert_trackerresetfn" id="all_assert_trackerresetfn">#</a></span><a aria-hidden="true" class="legacy" id="assert_tracker_reset_fn"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<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 tracked function to reset.</li>
</ul>
<p>Reset calls of the call tracker.
If a tracked function is passed as an argument, the calls will be reset for it.
If no arguments are passed, all tracked functions will be reset.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func);
<span class="hljs-title function_">callsfunc</span>();
<span class="hljs-comment">// Tracker was called once</span>
assert.<span class="hljs-title function_">strictEqual</span>(tracker.<span class="hljs-title function_">getCalls</span>(callsfunc).<span class="hljs-property">length</span>, <span class="hljs-number">1</span>);
tracker.<span class="hljs-title function_">reset</span>(callsfunc);
assert.<span class="hljs-title function_">strictEqual</span>(tracker.<span class="hljs-title function_">getCalls</span>(callsfunc).<span class="hljs-property">length</span>, <span class="hljs-number">0</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func);
<span class="hljs-title function_">callsfunc</span>();
<span class="hljs-comment">// Tracker was called once</span>
assert.<span class="hljs-title function_">strictEqual</span>(tracker.<span class="hljs-title function_">getCalls</span>(callsfunc).<span class="hljs-property">length</span>, <span class="hljs-number">1</span>);
tracker.<span class="hljs-title function_">reset</span>(callsfunc);
assert.<span class="hljs-title function_">strictEqual</span>(tracker.<span class="hljs-title function_">getCalls</span>(callsfunc).<span class="hljs-property">length</span>, <span class="hljs-number">0</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>tracker.verify()</code><span><a class="mark" href="#all_assert_trackerverify" id="all_assert_trackerverify">#</a></span><a aria-hidden="true" class="legacy" id="assert_tracker_verify"></a></h4>
<div class="api_metadata">
<span>Added in: v14.2.0, v12.19.0</span>
</div>
<p>Iterates through the list of functions passed to
<a href="#all_assert_trackercallsfn-exact"><code>tracker.calls()</code></a> and will throw an error for functions that
have not been called the expected number of times.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-comment">// Returns a function that wraps func() that must be called exact times</span>
<span class="hljs-comment">// before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func, <span class="hljs-number">2</span>);
<span class="hljs-title function_">callsfunc</span>();
<span class="hljs-comment">// Will throw an error since callsfunc() was only called once.</span>
tracker.<span class="hljs-title function_">verify</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-comment">// Returns a function that wraps func() that must be called exact times</span>
<span class="hljs-comment">// before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func, <span class="hljs-number">2</span>);
<span class="hljs-title function_">callsfunc</span>();
<span class="hljs-comment">// Will throw an error since callsfunc() was only called once.</span>
tracker.<span class="hljs-title function_">verify</span>();</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>assert(value[, message])</code><span><a class="mark" href="#all_assert_assertvalue-message" id="all_assert_assertvalue-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_value_message"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The input that is checked for being truthy.</li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>An alias of <a href="#all_assert_assertokvalue-message"><code>assert.ok()</code></a>.</p>
</section><section><h3><code>assert.deepEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertdeepequalactual-expected-message" id="all_assert_assertdeepequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_deepequal_actual_expected_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.15.0</td>
<td><p>Error cause and errors properties are now compared as well.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Regular expressions lastIndex property is now compared as well.</p></td></tr>
<tr><td>v16.0.0, v14.18.0</td>
<td><p>In Legacy assertion mode, changed status from Deprecated to Legacy.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>NaN is now treated as being identical if both sides are NaN.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>The type tags are now properly compared and there are a couple minor comparison adjustments to make the check less surprising.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>Error</code> names and messages are now properly compared.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>Set</code> and <code>Map</code> content is also compared.</p></td></tr>
<tr><td>v6.4.0, v4.7.1</td>
<td><p>Typed array slices are handled correctly now.</p></td></tr>
<tr><td>v6.1.0, v4.5.0</td>
<td><p>Objects with circular references can be used as inputs now.</p></td></tr>
<tr><td>v5.10.1, v4.4.3</td>
<td><p>Handle non-<code>Uint8Array</code> typed arrays correctly.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p><strong>Strict assertion mode</strong></p>
<p>An alias of <a href="#all_assert_assertdeepstrictequalactual-expected-message"><code>assert.deepStrictEqual()</code></a>.</p>
<p><strong>Legacy assertion mode</strong></p>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_assert_assertdeepstrictequalactual-expected-message"><code>assert.deepStrictEqual()</code></a> instead.</div><p></p>
<p>Tests for deep equality between the <code>actual</code> and <code>expected</code> parameters. Consider
using <a href="#all_assert_assertdeepstrictequalactual-expected-message"><code>assert.deepStrictEqual()</code></a> instead. <a href="#all_assert_assertdeepequalactual-expected-message"><code>assert.deepEqual()</code></a> can have
surprising results.</p>
<p><em>Deep equality</em> means that the enumerable "own" properties of child objects
are also recursively evaluated by the following rules.</p>
<h4>Comparison details<span><a class="mark" href="#all_assert_comparison-details" id="all_assert_comparison-details">#</a></span><a aria-hidden="true" class="legacy" id="assert_comparison_details"></a></h4>
<ul>
<li>Primitive values are compared with the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"><code>==</code> operator</a>,
with the exception of <code>NaN</code>. It is treated as being identical in case
both sides are <code>NaN</code>.</li>
<li><a href="https://tc39.github.io/ecma262/#sec-object.prototype.tostring">Type tags</a> of objects should be the same.</li>
<li>Only <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">enumerable "own" properties</a> are considered.</li>
<li><a href="#all_errors_class-error"><code>Error</code></a> names, messages, causes, and errors are always compared,
even if these are not enumerable properties.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript">Object wrappers</a> are compared both as objects and unwrapped values.</li>
<li><code>Object</code> properties are compared unordered.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a> keys and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a> items are compared unordered.</li>
<li>Recursion stops when both sides differ or both sides encounter a circular
reference.</li>
<li>Implementation does not test the <a href="https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots"><code>[[Prototype]]</code></a> of
objects.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol"><code>Symbol</code></a> properties are not compared.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> comparison does not rely on their values.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a> lastIndex, flags, and source are always compared, even if these
are not enumerable properties.</li>
</ul>
<p>The following example does not throw an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> because the
primitives are compared using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"><code>==</code> operator</a>.</p>
<pre class="with-50-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-comment">// WARNING: This does not throw an AssertionError!</span>
assert.<span class="hljs-title function_">deepEqual</span>(<span class="hljs-string">'+00000000'</span>, <span class="hljs-literal">false</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-comment">// WARNING: This does not throw an AssertionError!</span>
assert.<span class="hljs-title function_">deepEqual</span>(<span class="hljs-string">'+00000000'</span>, <span class="hljs-literal">false</span>);</code><button class="copy-button">copy</button></pre>
<p>"Deep" equality means that the enumerable "own" properties of child objects
are evaluated also:</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">const</span> obj1 = {
<span class="hljs-attr">a</span>: {
<span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
},
};
<span class="hljs-keyword">const</span> obj2 = {
<span class="hljs-attr">a</span>: {
<span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
},
};
<span class="hljs-keyword">const</span> obj3 = {
<span class="hljs-attr">a</span>: {
<span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
},
};
<span class="hljs-keyword">const</span> obj4 = { <span class="hljs-attr">__proto__</span>: obj1 };
assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj1);
<span class="hljs-comment">// OK</span>
<span class="hljs-comment">// Values of b are different:</span>
assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj2);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }</span>
assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj3);
<span class="hljs-comment">// OK</span>
<span class="hljs-comment">// Prototypes are ignored:</span>
assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj4);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } deepEqual {}</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> obj1 = {
<span class="hljs-attr">a</span>: {
<span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
},
};
<span class="hljs-keyword">const</span> obj2 = {
<span class="hljs-attr">a</span>: {
<span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
},
};
<span class="hljs-keyword">const</span> obj3 = {
<span class="hljs-attr">a</span>: {
<span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
},
};
<span class="hljs-keyword">const</span> obj4 = { <span class="hljs-attr">__proto__</span>: obj1 };
assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj1);
<span class="hljs-comment">// OK</span>
<span class="hljs-comment">// Values of b are different:</span>
assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj2);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }</span>
assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj3);
<span class="hljs-comment">// OK</span>
<span class="hljs-comment">// Prototypes are ignored:</span>
assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj4);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } deepEqual {}</span></code><button class="copy-button">copy</button></pre>
<p>If the values are not equal, an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code>
property set equal to the value of the <code>message</code> parameter. If the <code>message</code>
parameter is undefined, a default error message is assigned. If the <code>message</code>
parameter is an instance of an <a href="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>
</section><section><h3><code>assert.deepStrictEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertdeepstrictequalactual-expected-message" id="all_assert_assertdeepstrictequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_deepstrictequal_actual_expected_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.15.0</td>
<td><p>Error cause and errors properties are now compared as well.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Regular expressions lastIndex property is now compared as well.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>Enumerable symbol properties are now compared.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>NaN</code> is now compared using the <a href="https://tc39.github.io/ecma262/#sec-samevaluezero">SameValueZero</a> comparison.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p>The <code>Error</code> names and messages are now properly compared.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>Set</code> and <code>Map</code> content is also compared.</p></td></tr>
<tr><td>v6.1.0</td>
<td><p>Objects with circular references can be used as inputs now.</p></td></tr>
<tr><td>v6.4.0, v4.7.1</td>
<td><p>Typed array slices are handled correctly now.</p></td></tr>
<tr><td>v5.10.1, v4.4.3</td>
<td><p>Handle non-<code>Uint8Array</code> typed arrays correctly.</p></td></tr>
<tr><td>v1.2.0</td>
<td><p><span>Added in: v1.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>Tests for deep equality between the <code>actual</code> and <code>expected</code> parameters.
"Deep" equality means that the enumerable "own" properties of child objects
are recursively evaluated also by the following rules.</p>
<h4>Comparison details<span><a class="mark" href="#all_assert_comparison-details_1" id="all_assert_comparison-details_1">#</a></span><a aria-hidden="true" class="legacy" id="assert_comparison_details_1"></a></h4>
<ul>
<li>Primitive values are compared using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is"><code>Object.is()</code></a>.</li>
<li><a href="https://tc39.github.io/ecma262/#sec-object.prototype.tostring">Type tags</a> of objects should be the same.</li>
<li><a href="https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots"><code>[[Prototype]]</code></a> of objects are compared using
the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality"><code>===</code> operator</a>.</li>
<li>Only <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">enumerable "own" properties</a> are considered.</li>
<li><a href="#all_errors_class-error"><code>Error</code></a> names, messages, causes, and errors are always compared,
even if these are not enumerable properties.
<code>errors</code> is also compared.</li>
<li>Enumerable own <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol"><code>Symbol</code></a> properties are compared as well.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript">Object wrappers</a> are compared both as objects and unwrapped values.</li>
<li><code>Object</code> properties are compared unordered.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a> keys and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a> items are compared unordered.</li>
<li>Recursion stops when both sides differ or both sides encounter a circular
reference.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> instances are <strong>not</strong> compared structurally.
They are only equal if they reference the same object. Any comparison between
different <code>WeakMap</code> or <code>WeakSet</code> instances will result in inequality,
even if they contain the same entries.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a> lastIndex, flags, and source are always compared, even if these
are not enumerable properties.</li>
</ul>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
<span class="hljs-comment">// This fails because 1 !== '1'.</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-string">'1'</span> });
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">// + a: 1</span>
<span class="hljs-comment">// - a: '1'</span>
<span class="hljs-comment">// }</span>
<span class="hljs-comment">// The following objects don't have own properties</span>
<span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>();
<span class="hljs-keyword">const</span> object = {};
<span class="hljs-keyword">const</span> fakeDate = {};
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">setPrototypeOf</span>(fakeDate, <span class="hljs-title class_">Date</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>);
<span class="hljs-comment">// Different [[Prototype]]:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(object, fakeDate);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + {}</span>
<span class="hljs-comment">// - Date {}</span>
<span class="hljs-comment">// Different type tags:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(date, fakeDate);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + 2018-04-26T00:49:08.604Z</span>
<span class="hljs-comment">// - Date {}</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-title class_">NaN</span>, <span class="hljs-title class_">NaN</span>);
<span class="hljs-comment">// OK because Object.is(NaN, NaN) is true.</span>
<span class="hljs-comment">// Different unwrapped numbers:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Number</span>(<span class="hljs-number">1</span>), <span class="hljs-keyword">new</span> <span class="hljs-title class_">Number</span>(<span class="hljs-number">2</span>));
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + [Number: 1]</span>
<span class="hljs-comment">// - [Number: 2]</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">'foo'</span>), <span class="hljs-title class_">Object</span>(<span class="hljs-string">'foo'</span>));
<span class="hljs-comment">// OK because the object and the string are identical when unwrapped.</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(-<span class="hljs-number">0</span>, -<span class="hljs-number">0</span>);
<span class="hljs-comment">// OK</span>
<span class="hljs-comment">// Different zeros:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-number">0</span>, -<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + 0</span>
<span class="hljs-comment">// - -0</span>
<span class="hljs-keyword">const</span> symbol1 = <span class="hljs-title class_">Symbol</span>();
<span class="hljs-keyword">const</span> symbol2 = <span class="hljs-title class_">Symbol</span>();
assert.<span class="hljs-title function_">deepStrictEqual</span>({ [symbol1]: <span class="hljs-number">1</span> }, { [symbol1]: <span class="hljs-number">1</span> });
<span class="hljs-comment">// OK, because it is the same symbol on both objects.</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>({ [symbol1]: <span class="hljs-number">1</span> }, { [symbol2]: <span class="hljs-number">1</span> });
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">// [Symbol()]: 1</span>
<span class="hljs-comment">// }</span>
<span class="hljs-keyword">const</span> weakMap1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>();
<span class="hljs-keyword">const</span> weakMap2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>();
<span class="hljs-keyword">const</span> obj = {};
weakMap1.<span class="hljs-title function_">set</span>(obj, <span class="hljs-string">'value'</span>);
weakMap2.<span class="hljs-title function_">set</span>(obj, <span class="hljs-string">'value'</span>);
<span class="hljs-comment">// Comparing different instances fails, even with same contents</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(weakMap1, weakMap2);
<span class="hljs-comment">// AssertionError: Values have same structure but are not reference-equal:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// WeakMap {</span>
<span class="hljs-comment">// <items unknown></span>
<span class="hljs-comment">// }</span>
<span class="hljs-comment">// Comparing the same instance to itself succeeds</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(weakMap1, weakMap1);
<span class="hljs-comment">// OK</span>
<span class="hljs-keyword">const</span> weakSet1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakSet</span>();
<span class="hljs-keyword">const</span> weakSet2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakSet</span>();
weakSet1.<span class="hljs-title function_">add</span>(obj);
weakSet2.<span class="hljs-title function_">add</span>(obj);
<span class="hljs-comment">// Comparing different instances fails, even with same contents</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(weakSet1, weakSet2);
<span class="hljs-comment">// AssertionError: Values have same structure but are not reference-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// WeakSet {</span>
<span class="hljs-comment">// <items unknown></span>
<span class="hljs-comment">// }</span>
<span class="hljs-comment">// Comparing the same instance to itself succeeds</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(weakSet1, weakSet1);
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
<span class="hljs-comment">// This fails because 1 !== '1'.</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-string">'1'</span> });
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">// + a: 1</span>
<span class="hljs-comment">// - a: '1'</span>
<span class="hljs-comment">// }</span>
<span class="hljs-comment">// The following objects don't have own properties</span>
<span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>();
<span class="hljs-keyword">const</span> object = {};
<span class="hljs-keyword">const</span> fakeDate = {};
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">setPrototypeOf</span>(fakeDate, <span class="hljs-title class_">Date</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>);
<span class="hljs-comment">// Different [[Prototype]]:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(object, fakeDate);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + {}</span>
<span class="hljs-comment">// - Date {}</span>
<span class="hljs-comment">// Different type tags:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(date, fakeDate);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + 2018-04-26T00:49:08.604Z</span>
<span class="hljs-comment">// - Date {}</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-title class_">NaN</span>, <span class="hljs-title class_">NaN</span>);
<span class="hljs-comment">// OK because Object.is(NaN, NaN) is true.</span>
<span class="hljs-comment">// Different unwrapped numbers:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Number</span>(<span class="hljs-number">1</span>), <span class="hljs-keyword">new</span> <span class="hljs-title class_">Number</span>(<span class="hljs-number">2</span>));
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + [Number: 1]</span>
<span class="hljs-comment">// - [Number: 2]</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">'foo'</span>), <span class="hljs-title class_">Object</span>(<span class="hljs-string">'foo'</span>));
<span class="hljs-comment">// OK because the object and the string are identical when unwrapped.</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(-<span class="hljs-number">0</span>, -<span class="hljs-number">0</span>);
<span class="hljs-comment">// OK</span>
<span class="hljs-comment">// Different zeros:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-number">0</span>, -<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + 0</span>
<span class="hljs-comment">// - -0</span>
<span class="hljs-keyword">const</span> symbol1 = <span class="hljs-title class_">Symbol</span>();
<span class="hljs-keyword">const</span> symbol2 = <span class="hljs-title class_">Symbol</span>();
assert.<span class="hljs-title function_">deepStrictEqual</span>({ [symbol1]: <span class="hljs-number">1</span> }, { [symbol1]: <span class="hljs-number">1</span> });
<span class="hljs-comment">// OK, because it is the same symbol on both objects.</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>({ [symbol1]: <span class="hljs-number">1</span> }, { [symbol2]: <span class="hljs-number">1</span> });
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">// [Symbol()]: 1</span>
<span class="hljs-comment">// }</span>
<span class="hljs-keyword">const</span> weakMap1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>();
<span class="hljs-keyword">const</span> weakMap2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>();
<span class="hljs-keyword">const</span> obj = {};
weakMap1.<span class="hljs-title function_">set</span>(obj, <span class="hljs-string">'value'</span>);
weakMap2.<span class="hljs-title function_">set</span>(obj, <span class="hljs-string">'value'</span>);
<span class="hljs-comment">// Comparing different instances fails, even with same contents</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(weakMap1, weakMap2);
<span class="hljs-comment">// AssertionError: Values have same structure but are not reference-equal:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// WeakMap {</span>
<span class="hljs-comment">// <items unknown></span>
<span class="hljs-comment">// }</span>
<span class="hljs-comment">// Comparing the same instance to itself succeeds</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(weakMap1, weakMap1);
<span class="hljs-comment">// OK</span>
<span class="hljs-keyword">const</span> weakSet1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakSet</span>();
<span class="hljs-keyword">const</span> weakSet2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakSet</span>();
weakSet1.<span class="hljs-title function_">add</span>(obj);
weakSet2.<span class="hljs-title function_">add</span>(obj);
<span class="hljs-comment">// Comparing different instances fails, even with same contents</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(weakSet1, weakSet2);
<span class="hljs-comment">// AssertionError: Values have same structure but are not reference-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// WeakSet {</span>
<span class="hljs-comment">// <items unknown></span>
<span class="hljs-comment">// }</span>
<span class="hljs-comment">// Comparing the same instance to itself succeeds</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(weakSet1, weakSet1);
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></pre>
<p>If the values are not equal, an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code>
property set equal to the value of the <code>message</code> parameter. If the <code>message</code>
parameter is undefined, a default error message is assigned. If the <code>message</code>
parameter is an instance of an <a href="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
</section><section><h3><code>assert.doesNotMatch(string, regexp[, message])</code><span><a class="mark" href="#all_assert_assertdoesnotmatchstring-regexp-message" id="all_assert_assertdoesnotmatchstring-regexp-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_doesnotmatch_string_regexp_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p><span>Added in: v13.6.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>regexp</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type"><RegExp></a></li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>Expects the <code>string</code> input not to match the regular expression.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">doesNotMatch</span>(<span class="hljs-string">'I will fail'</span>, <span class="hljs-regexp">/fail/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...</span>
assert.<span class="hljs-title function_">doesNotMatch</span>(<span class="hljs-number">123</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.</span>
assert.<span class="hljs-title function_">doesNotMatch</span>(<span class="hljs-string">'I will pass'</span>, <span class="hljs-regexp">/different/</span>);
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">doesNotMatch</span>(<span class="hljs-string">'I will fail'</span>, <span class="hljs-regexp">/fail/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...</span>
assert.<span class="hljs-title function_">doesNotMatch</span>(<span class="hljs-number">123</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.</span>
assert.<span class="hljs-title function_">doesNotMatch</span>(<span class="hljs-string">'I will pass'</span>, <span class="hljs-regexp">/different/</span>);
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></pre>
<p>If the values do match, or if the <code>string</code> argument is of another type than
<code>string</code>, an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code> property set equal
to the value of the <code>message</code> parameter. If the <code>message</code> parameter is
undefined, a default error message is assigned. If the <code>message</code> parameter is an
instance of an <a href="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>
</section><section><h3><code>assert.doesNotReject(asyncFn[, error][, message])</code><span><a class="mark" href="#all_assert_assertdoesnotrejectasyncfn-error-message" id="all_assert_assertdoesnotrejectasyncfn-error-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_doesnotreject_asyncfn_error_message"></a></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>asyncFn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type"><RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Awaits the <code>asyncFn</code> promise or, if <code>asyncFn</code> is a function, immediately
calls the function and awaits the returned promise to complete. It will then
check that the promise is not rejected.</p>
<p>If <code>asyncFn</code> is a function and it throws an error synchronously,
<code>assert.doesNotReject()</code> will return a rejected <code>Promise</code> with that error. If
the function does not return a promise, <code>assert.doesNotReject()</code> will return a
rejected <code>Promise</code> with an <a href="#all_errors_err_invalid_return_value"><code>ERR_INVALID_RETURN_VALUE</code></a> error. In both cases
the error handler is skipped.</p>
<p>Using <code>assert.doesNotReject()</code> is actually not useful because there is little
benefit in catching a rejection and then rejecting it again. Instead, consider
adding a comment next to the specific code path that should not reject and keep
error messages as expressive as possible.</p>
<p>If specified, <code>error</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><code>Class</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>, or a validation
function. See <a href="#all_assert_assertthrowsfn-error-message"><code>assert.throws()</code></a> for more details.</p>
<p>Besides the async nature to await the completion behaves identically to
<a href="#all_assert_assertdoesnotthrowfn-error-message"><code>assert.doesNotThrow()</code></a>.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
<span class="hljs-keyword">await</span> assert.<span class="hljs-title function_">doesNotReject</span>(
<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-title class_">SyntaxError</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">await</span> assert.<span class="hljs-title function_">doesNotReject</span>(
<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-title class_">SyntaxError</span>,
);
})();</code><button class="copy-button">copy</button></pre>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">doesNotReject</span>(<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>)))
.<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// ...</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">doesNotReject</span>(<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>)))
.<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// ...</span>
});</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>assert.doesNotThrow(fn[, error][, message])</code><span><a class="mark" href="#all_assert_assertdoesnotthrowfn-error-message" id="all_assert_assertdoesnotthrowfn-error-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_doesnotthrow_fn_error_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.11.0, v4.4.5</td>
<td><p>The <code>message</code> parameter is respected now.</p></td></tr>
<tr><td>v4.2.0</td>
<td><p>The <code>error</code> parameter can now be an arrow function.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type"><RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Asserts that the function <code>fn</code> does not throw an error.</p>
<p>Using <code>assert.doesNotThrow()</code> is actually not useful because there
is no benefit in catching an error and then rethrowing it. Instead, consider
adding a comment next to the specific code path that should not throw and keep
error messages as expressive as possible.</p>
<p>When <code>assert.doesNotThrow()</code> is called, it will immediately call the <code>fn</code>
function.</p>
<p>If an error is thrown and it is the same type as that specified by the <code>error</code>
parameter, then an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown. If the error is of a
different type, or if the <code>error</code> parameter is undefined, the error is
propagated back to the caller.</p>
<p>If specified, <code>error</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><code>Class</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>, or a validation
function. See <a href="#all_assert_assertthrowsfn-error-message"><code>assert.throws()</code></a> for more details.</p>
<p>The following, for instance, will throw the <a href="#all_errors_class-typeerror"><code>TypeError</code></a> because there is no
matching error type in the assertion:</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">doesNotThrow</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-title class_">SyntaxError</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">doesNotThrow</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-title class_">SyntaxError</span>,
);</code><button class="copy-button">copy</button></pre>
<p>However, the following will result in an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> with the message
'Got unwanted exception...':</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">doesNotThrow</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-title class_">TypeError</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">doesNotThrow</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-title class_">TypeError</span>,
);</code><button class="copy-button">copy</button></pre>
<p>If an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown and a value is provided for the <code>message</code>
parameter, the value of <code>message</code> will be appended to the <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>
message:</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">doesNotThrow</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-regexp">/Wrong value/</span>,
<span class="hljs-string">'Whoops'</span>,
);
<span class="hljs-comment">// Throws: AssertionError: Got unwanted exception: Whoops</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">doesNotThrow</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-regexp">/Wrong value/</span>,
<span class="hljs-string">'Whoops'</span>,
);
<span class="hljs-comment">// Throws: AssertionError: Got unwanted exception: Whoops</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>assert.equal(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertequalactual-expected-message" id="all_assert_assertequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_equal_actual_expected_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0, v14.18.0</td>
<td><p>In Legacy assertion mode, changed status from Deprecated to Legacy.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>NaN is now treated as being identical if both sides are NaN.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p><strong>Strict assertion mode</strong></p>
<p>An alias of <a href="#all_assert_assertstrictequalactual-expected-message"><code>assert.strictEqual()</code></a>.</p>
<p><strong>Legacy assertion mode</strong></p>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_assert_assertstrictequalactual-expected-message"><code>assert.strictEqual()</code></a> instead.</div><p></p>
<p>Tests shallow, coercive equality between the <code>actual</code> and <code>expected</code> parameters
using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"><code>==</code> operator</a>. <code>NaN</code> is specially handled
and treated as being identical if both sides are <code>NaN</code>.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// OK, 1 == 1</span>
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>);
<span class="hljs-comment">// OK, 1 == '1'</span>
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-title class_">NaN</span>, <span class="hljs-title class_">NaN</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// AssertionError: 1 == 2</span>
assert.<span class="hljs-title function_">equal</span>({ <span class="hljs-attr">a</span>: { <span class="hljs-attr">b</span>: <span class="hljs-number">1</span> } }, { <span class="hljs-attr">a</span>: { <span class="hljs-attr">b</span>: <span class="hljs-number">1</span> } });
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// OK, 1 == 1</span>
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>);
<span class="hljs-comment">// OK, 1 == '1'</span>
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-title class_">NaN</span>, <span class="hljs-title class_">NaN</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// AssertionError: 1 == 2</span>
assert.<span class="hljs-title function_">equal</span>({ <span class="hljs-attr">a</span>: { <span class="hljs-attr">b</span>: <span class="hljs-number">1</span> } }, { <span class="hljs-attr">a</span>: { <span class="hljs-attr">b</span>: <span class="hljs-number">1</span> } });
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }</span></code><button class="copy-button">copy</button></pre>
<p>If the values are not equal, an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code>
property set equal to the value of the <code>message</code> parameter. If the <code>message</code>
parameter is undefined, a default error message is assigned. If the <code>message</code>
parameter is an instance of an <a href="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
</section><section><h3><code>assert.fail([message])</code><span><a class="mark" href="#all_assert_assertfailmessage" id="all_assert_assertfailmessage">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_fail_message"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div>
<ul>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a> <strong>Default:</strong> <code>'Failed'</code></li>
</ul>
<p>Throws an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> with the provided error message or a default
error message. If the <code>message</code> parameter is an instance of an <a href="#all_errors_class-error"><code>Error</code></a> then
it will be thrown instead of the <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">fail</span>();
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Failed</span>
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-string">'boom'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: boom</span>
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'need array'</span>));
<span class="hljs-comment">// TypeError: need array</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">fail</span>();
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Failed</span>
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-string">'boom'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: boom</span>
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'need array'</span>));
<span class="hljs-comment">// TypeError: need array</span></code><button class="copy-button">copy</button></pre>
<p>Using <code>assert.fail()</code> with more than two arguments is possible but deprecated.
See below for further details.</p>
</section><section><h3><code>assert.fail(actual, expected[, message[, operator[, stackStartFn]]])</code><span><a class="mark" href="#all_assert_assertfailactual-expected-message-operator-stackstartfn" id="all_assert_assertfailactual-expected-message-operator-stackstartfn">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_fail_actual_expected_message_operator_stackstartfn"></a></h3>
<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>Calling <code>assert.fail()</code> with more than one argument is deprecated and emits a warning.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <code>assert.fail([message])</code> or other assert
functions instead.</div><p></p>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
<li><code>operator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'!='</code></li>
<li><code>stackStartFn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> <strong>Default:</strong> <code>assert.fail</code></li>
</ul>
<p>If <code>message</code> is falsy, the error message is set as the values of <code>actual</code> and
<code>expected</code> separated by the provided <code>operator</code>. If just the two <code>actual</code> and
<code>expected</code> arguments are provided, <code>operator</code> will default to <code>'!='</code>. If
<code>message</code> is provided as third argument it will be used as the error message and
the other arguments will be stored as properties on the thrown object. If
<code>stackStartFn</code> is provided, all stack frames above that function will be
removed from stacktrace (see <a href="#all_errors_errorcapturestacktracetargetobject-constructoropt"><code>Error.captureStackTrace</code></a>). If no arguments are
given, the default message <code>Failed</code> will be used.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: 'a' != 'b'</span>
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">'>'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: 1 > 2</span>
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'fail'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: fail</span>
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'whoops'</span>, <span class="hljs-string">'>'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: whoops</span>
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'need array'</span>));
<span class="hljs-comment">// TypeError: need array</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: 'a' != 'b'</span>
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">'>'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: 1 > 2</span>
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'fail'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: fail</span>
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'whoops'</span>, <span class="hljs-string">'>'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: whoops</span>
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'need array'</span>));
<span class="hljs-comment">// TypeError: need array</span></code><button class="copy-button">copy</button></pre>
<p>In the last three cases <code>actual</code>, <code>expected</code>, and <code>operator</code> have no
influence on the error message.</p>
<p>Example use of <code>stackStartFn</code> for truncating the exception's stacktrace:</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">suppressFrame</span>(<span class="hljs-params"></span>) {
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">'!=='</span>, suppressFrame);
}
<span class="hljs-title function_">suppressFrame</span>();
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: 'a' !== 'b'</span>
<span class="hljs-comment">// at repl:1:1</span>
<span class="hljs-comment">// at ContextifyScript.Script.runInThisContext (vm.js:44:33)</span>
<span class="hljs-comment">// ...</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">suppressFrame</span>(<span class="hljs-params"></span>) {
assert.<span class="hljs-title function_">fail</span>(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">'!=='</span>, suppressFrame);
}
<span class="hljs-title function_">suppressFrame</span>();
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: 'a' !== 'b'</span>
<span class="hljs-comment">// at repl:1:1</span>
<span class="hljs-comment">// at ContextifyScript.Script.runInThisContext (vm.js:44:33)</span>
<span class="hljs-comment">// ...</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>assert.ifError(value)</code><span><a class="mark" href="#all_assert_assertiferrorvalue" id="all_assert_assertiferrorvalue">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_iferror_value"></a></h3>
<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>Instead of throwing the original error it is now wrapped into an [<code>AssertionError</code>][] that contains the full stack trace.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Value may now only be <code>undefined</code> or <code>null</code>. Before all falsy values were handled the same as <code>null</code> and did not throw.</p></td></tr>
<tr><td>v0.1.97</td>
<td><p><span>Added in: v0.1.97</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Throws <code>value</code> if <code>value</code> is not <code>undefined</code> or <code>null</code>. This is useful when
testing the <code>error</code> argument in callbacks. The stack trace contains all frames
from the error passed to <code>ifError()</code> including the potential new frames for
<code>ifError()</code> itself.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0</span>
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-string">'error'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'</span>
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>());
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error</span>
<span class="hljs-comment">// Create some random error frames.</span>
<span class="hljs-keyword">let</span> err;
(<span class="hljs-keyword">function</span> <span class="hljs-title function_">errorFrame</span>(<span class="hljs-params"></span>) {
err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'test error'</span>);
})();
(<span class="hljs-keyword">function</span> <span class="hljs-title function_">ifErrorFrame</span>(<span class="hljs-params"></span>) {
assert.<span class="hljs-title function_">ifError</span>(err);
})();
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error</span>
<span class="hljs-comment">// at ifErrorFrame</span>
<span class="hljs-comment">// at errorFrame</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0</span>
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-string">'error'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'</span>
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>());
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error</span>
<span class="hljs-comment">// Create some random error frames.</span>
<span class="hljs-keyword">let</span> err;
(<span class="hljs-keyword">function</span> <span class="hljs-title function_">errorFrame</span>(<span class="hljs-params"></span>) {
err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'test error'</span>);
})();
(<span class="hljs-keyword">function</span> <span class="hljs-title function_">ifErrorFrame</span>(<span class="hljs-params"></span>) {
assert.<span class="hljs-title function_">ifError</span>(err);
})();
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error</span>
<span class="hljs-comment">// at ifErrorFrame</span>
<span class="hljs-comment">// at errorFrame</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>assert.match(string, regexp[, message])</code><span><a class="mark" href="#all_assert_assertmatchstring-regexp-message" id="all_assert_assertmatchstring-regexp-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_match_string_regexp_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p><span>Added in: v13.6.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>regexp</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type"><RegExp></a></li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>Expects the <code>string</code> input to match the regular expression.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">match</span>(<span class="hljs-string">'I will fail'</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The input did not match the regular ...</span>
assert.<span class="hljs-title function_">match</span>(<span class="hljs-number">123</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.</span>
assert.<span class="hljs-title function_">match</span>(<span class="hljs-string">'I will pass'</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">match</span>(<span class="hljs-string">'I will fail'</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The input did not match the regular ...</span>
assert.<span class="hljs-title function_">match</span>(<span class="hljs-number">123</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.</span>
assert.<span class="hljs-title function_">match</span>(<span class="hljs-string">'I will pass'</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></pre>
<p>If the values do not match, or if the <code>string</code> argument is of another type than
<code>string</code>, an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code> property set equal
to the value of the <code>message</code> parameter. If the <code>message</code> parameter is
undefined, a default error message is assigned. If the <code>message</code> parameter is an
instance of an <a href="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>
</section><section><h3><code>assert.notDeepEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertnotdeepequalactual-expected-message" id="all_assert_assertnotdeepequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_notdeepequal_actual_expected_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0, v14.18.0</td>
<td><p>In Legacy assertion mode, changed status from Deprecated to Legacy.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>NaN is now treated as being identical if both sides are NaN.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>Error</code> names and messages are now properly compared.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>Set</code> and <code>Map</code> content is also compared.</p></td></tr>
<tr><td>v6.4.0, v4.7.1</td>
<td><p>Typed array slices are handled correctly now.</p></td></tr>
<tr><td>v6.1.0, v4.5.0</td>
<td><p>Objects with circular references can be used as inputs now.</p></td></tr>
<tr><td>v5.10.1, v4.4.3</td>
<td><p>Handle non-<code>Uint8Array</code> typed arrays correctly.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p><strong>Strict assertion mode</strong></p>
<p>An alias of <a href="#all_assert_assertnotdeepstrictequalactual-expected-message"><code>assert.notDeepStrictEqual()</code></a>.</p>
<p><strong>Legacy assertion mode</strong></p>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_assert_assertnotdeepstrictequalactual-expected-message"><code>assert.notDeepStrictEqual()</code></a> instead.</div><p></p>
<p>Tests for any deep inequality. Opposite of <a href="#all_assert_assertdeepequalactual-expected-message"><code>assert.deepEqual()</code></a>.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">const</span> obj1 = {
<span class="hljs-attr">a</span>: {
<span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
},
};
<span class="hljs-keyword">const</span> obj2 = {
<span class="hljs-attr">a</span>: {
<span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
},
};
<span class="hljs-keyword">const</span> obj3 = {
<span class="hljs-attr">a</span>: {
<span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
},
};
<span class="hljs-keyword">const</span> obj4 = { <span class="hljs-attr">__proto__</span>: obj1 };
assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj1);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }</span>
assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj2);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj3);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }</span>
assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj4);
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> obj1 = {
<span class="hljs-attr">a</span>: {
<span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
},
};
<span class="hljs-keyword">const</span> obj2 = {
<span class="hljs-attr">a</span>: {
<span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
},
};
<span class="hljs-keyword">const</span> obj3 = {
<span class="hljs-attr">a</span>: {
<span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
},
};
<span class="hljs-keyword">const</span> obj4 = { <span class="hljs-attr">__proto__</span>: obj1 };
assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj1);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }</span>
assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj2);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj3);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }</span>
assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj4);
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></pre>
<p>If the values are deeply equal, an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown with a
<code>message</code> property set equal to the value of the <code>message</code> parameter. If the
<code>message</code> parameter is undefined, a default error message is assigned. If the
<code>message</code> parameter is an instance of an <a href="#all_errors_class-error"><code>Error</code></a> then it will be thrown
instead of the <code>AssertionError</code>.</p>
</section><section><h3><code>assert.notDeepStrictEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertnotdeepstrictequalactual-expected-message" id="all_assert_assertnotdeepstrictequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_notdeepstrictequal_actual_expected_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>-0</code> and <code>+0</code> are not considered equal anymore.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>NaN</code> is now compared using the <a href="https://tc39.github.io/ecma262/#sec-samevaluezero">SameValueZero</a> comparison.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>Error</code> names and messages are now properly compared.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>Set</code> and <code>Map</code> content is also compared.</p></td></tr>
<tr><td>v6.1.0</td>
<td><p>Objects with circular references can be used as inputs now.</p></td></tr>
<tr><td>v6.4.0, v4.7.1</td>
<td><p>Typed array slices are handled correctly now.</p></td></tr>
<tr><td>v5.10.1, v4.4.3</td>
<td><p>Handle non-<code>Uint8Array</code> typed arrays correctly.</p></td></tr>
<tr><td>v1.2.0</td>
<td><p><span>Added in: v1.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>Tests for deep strict inequality. Opposite of <a href="#all_assert_assertdeepstrictequalactual-expected-message"><code>assert.deepStrictEqual()</code></a>.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">notDeepStrictEqual</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-string">'1'</span> });
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">notDeepStrictEqual</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-string">'1'</span> });
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></pre>
<p>If the values are deeply and strictly equal, an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown
with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If
the <code>message</code> parameter is undefined, a default error message is assigned. If
the <code>message</code> parameter is an instance of an <a href="#all_errors_class-error"><code>Error</code></a> then it will be thrown
instead of the <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>
</section><section><h3><code>assert.notEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertnotequalactual-expected-message" id="all_assert_assertnotequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_notequal_actual_expected_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0, v14.18.0</td>
<td><p>In Legacy assertion mode, changed status from Deprecated to Legacy.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>NaN is now treated as being identical if both sides are NaN.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p><strong>Strict assertion mode</strong></p>
<p>An alias of <a href="#all_assert_assertnotstrictequalactual-expected-message"><code>assert.notStrictEqual()</code></a>.</p>
<p><strong>Legacy assertion mode</strong></p>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_assert_assertnotstrictequalactual-expected-message"><code>assert.notStrictEqual()</code></a> instead.</div><p></p>
<p>Tests shallow, coercive inequality with the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality"><code>!=</code> operator</a>. <code>NaN</code> is
specially handled and treated as being identical if both sides are <code>NaN</code>.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
assert.<span class="hljs-title function_">notEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">notEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// AssertionError: 1 != 1</span>
assert.<span class="hljs-title function_">notEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>);
<span class="hljs-comment">// AssertionError: 1 != '1'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
assert.<span class="hljs-title function_">notEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">notEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// AssertionError: 1 != 1</span>
assert.<span class="hljs-title function_">notEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>);
<span class="hljs-comment">// AssertionError: 1 != '1'</span></code><button class="copy-button">copy</button></pre>
<p>If the values are equal, an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code>
property set equal to the value of the <code>message</code> parameter. If the <code>message</code>
parameter is undefined, a default error message is assigned. If the <code>message</code>
parameter is an instance of an <a href="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
</section><section><h3><code>assert.notStrictEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertnotstrictequalactual-expected-message" id="all_assert_assertnotstrictequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_notstrictequal_actual_expected_message"></a></h3>
<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>Used comparison changed from Strict Equality to <code>Object.is()</code>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>Tests strict inequality between the <code>actual</code> and <code>expected</code> parameters as
determined by <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is"><code>Object.is()</code></a>.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// 1</span>
assert.<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>);
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// 1</span>
assert.<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>);
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></pre>
<p>If the values are strictly equal, an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown with a
<code>message</code> property set equal to the value of the <code>message</code> parameter. If the
<code>message</code> parameter is undefined, a default error message is assigned. If the
<code>message</code> parameter is an instance of an <a href="#all_errors_class-error"><code>Error</code></a> then it will be thrown
instead of the <code>AssertionError</code>.</p>
</section><section><h3><code>assert.ok(value[, message])</code><span><a class="mark" href="#all_assert_assertokvalue-message" id="all_assert_assertokvalue-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_ok_value_message"></a></h3>
<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>assert.ok()</code> (no arguments) will now use a predefined error message.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>Tests if <code>value</code> is truthy. It is equivalent to
<code>assert.equal(!!value, true, message)</code>.</p>
<p>If <code>value</code> is not truthy, an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code>
property set equal to the value of the <code>message</code> parameter. If the <code>message</code>
parameter is <code>undefined</code>, a default error message is assigned. If the <code>message</code>
parameter is an instance of an <a href="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.
If no arguments are passed in at all <code>message</code> will be set to the string:
<code>'No value argument passed to `assert.ok()`'</code>.</p>
<p>Be aware that in the <code>repl</code> the error message will be different to the one
thrown in a file! See below for further details.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-literal">true</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-number">1</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">ok</span>();
<span class="hljs-comment">// AssertionError: No value argument passed to `assert.ok()`</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-literal">false</span>, <span class="hljs-string">'it\'s false'</span>);
<span class="hljs-comment">// AssertionError: it's false</span>
<span class="hljs-comment">// In the repl:</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-keyword">typeof</span> <span class="hljs-number">123</span> === <span class="hljs-string">'string'</span>);
<span class="hljs-comment">// AssertionError: false == true</span>
<span class="hljs-comment">// In a file (e.g. test.js):</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-keyword">typeof</span> <span class="hljs-number">123</span> === <span class="hljs-string">'string'</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// assert.ok(typeof 123 === 'string')</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-literal">false</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// assert.ok(false)</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// assert.ok(0)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-literal">true</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-number">1</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">ok</span>();
<span class="hljs-comment">// AssertionError: No value argument passed to `assert.ok()`</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-literal">false</span>, <span class="hljs-string">'it\'s false'</span>);
<span class="hljs-comment">// AssertionError: it's false</span>
<span class="hljs-comment">// In the repl:</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-keyword">typeof</span> <span class="hljs-number">123</span> === <span class="hljs-string">'string'</span>);
<span class="hljs-comment">// AssertionError: false == true</span>
<span class="hljs-comment">// In a file (e.g. test.js):</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-keyword">typeof</span> <span class="hljs-number">123</span> === <span class="hljs-string">'string'</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// assert.ok(typeof 123 === 'string')</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-literal">false</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// assert.ok(false)</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// assert.ok(0)</span></code><button class="copy-button">copy</button></pre>
<pre class="with-40-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
<span class="hljs-comment">// Using `assert()` works the same:</span>
<span class="hljs-title function_">assert</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// assert(0)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-comment">// Using `assert()` works the same:</span>
<span class="hljs-title function_">assert</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// assert(0)</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>assert.rejects(asyncFn[, error][, message])</code><span><a class="mark" href="#all_assert_assertrejectsasyncfn-error-message" id="all_assert_assertrejectsasyncfn-error-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_rejects_asyncfn_error_message"></a></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>asyncFn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type"><RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Awaits the <code>asyncFn</code> promise or, if <code>asyncFn</code> is a function, immediately
calls the function and awaits the returned promise to complete. It will then
check that the promise is rejected.</p>
<p>If <code>asyncFn</code> is a function and it throws an error synchronously,
<code>assert.rejects()</code> will return a rejected <code>Promise</code> with that error. If the
function does not return a promise, <code>assert.rejects()</code> will return a rejected
<code>Promise</code> with an <a href="#all_errors_err_invalid_return_value"><code>ERR_INVALID_RETURN_VALUE</code></a> error. In both cases the error
handler is skipped.</p>
<p>Besides the async nature to await the completion behaves identically to
<a href="#all_assert_assertthrowsfn-error-message"><code>assert.throws()</code></a>.</p>
<p>If specified, <code>error</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><code>Class</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>, a validation function,
an object where each property will be tested for, or an instance of error where
each property will be tested for including the non-enumerable <code>message</code> and
<code>name</code> properties.</p>
<p>If specified, <code>message</code> will be the message provided by the <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>
if the <code>asyncFn</code> fails to reject.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
<span class="hljs-keyword">await</span> assert.<span class="hljs-title function_">rejects</span>(
<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
},
{
<span class="hljs-attr">name</span>: <span class="hljs-string">'TypeError'</span>,
<span class="hljs-attr">message</span>: <span class="hljs-string">'Wrong value'</span>,
},
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">await</span> assert.<span class="hljs-title function_">rejects</span>(
<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
},
{
<span class="hljs-attr">name</span>: <span class="hljs-string">'TypeError'</span>,
<span class="hljs-attr">message</span>: <span class="hljs-string">'Wrong value'</span>,
},
);
})();</code><button class="copy-button">copy</button></pre>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
<span class="hljs-keyword">await</span> assert.<span class="hljs-title function_">rejects</span>(
<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">name</span>, <span class="hljs-string">'TypeError'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">message</span>, <span class="hljs-string">'Wrong value'</span>);
<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
},
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">await</span> assert.<span class="hljs-title function_">rejects</span>(
<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">name</span>, <span class="hljs-string">'TypeError'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">message</span>, <span class="hljs-string">'Wrong value'</span>);
<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
},
);
})();</code><button class="copy-button">copy</button></pre>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">rejects</span>(
<span class="hljs-title class_">Promise</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">'Wrong value'</span>)),
<span class="hljs-title class_">Error</span>,
).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// ...</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">rejects</span>(
<span class="hljs-title class_">Promise</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">'Wrong value'</span>)),
<span class="hljs-title class_">Error</span>,
).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// ...</span>
});</code><button class="copy-button">copy</button></pre>
<p><code>error</code> cannot be a string. If a string is provided as the second
argument, then <code>error</code> is assumed to be omitted and the string will be used for
<code>message</code> instead. This can lead to easy-to-miss mistakes. Please read the
example in <a href="#all_assert_assertthrowsfn-error-message"><code>assert.throws()</code></a> carefully if using a string as the second
argument gets considered.</p>
</section><section><h3><code>assert.strictEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertstrictequalactual-expected-message" id="all_assert_assertstrictequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_strictequal_actual_expected_message"></a></h3>
<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>Used comparison changed from Strict Equality to <code>Object.is()</code>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>message</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/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>Tests strict equality between the <code>actual</code> and <code>expected</code> parameters as
determined by <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is"><code>Object.is()</code></a>.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// 1 !== 2</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-string">'Hello foobar'</span>, <span class="hljs-string">'Hello World!'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + 'Hello foobar'</span>
<span class="hljs-comment">// - 'Hello World!'</span>
<span class="hljs-comment">// ^</span>
<span class="hljs-keyword">const</span> apples = <span class="hljs-number">1</span>;
<span class="hljs-keyword">const</span> oranges = <span class="hljs-number">2</span>;
assert.<span class="hljs-title function_">strictEqual</span>(apples, oranges, <span class="hljs-string">`apples <span class="hljs-subst">${apples}</span> !== oranges <span class="hljs-subst">${oranges}</span>`</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Inputs are not identical'</span>));
<span class="hljs-comment">// TypeError: Inputs are not identical</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// 1 !== 2</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-string">'Hello foobar'</span>, <span class="hljs-string">'Hello World!'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + 'Hello foobar'</span>
<span class="hljs-comment">// - 'Hello World!'</span>
<span class="hljs-comment">// ^</span>
<span class="hljs-keyword">const</span> apples = <span class="hljs-number">1</span>;
<span class="hljs-keyword">const</span> oranges = <span class="hljs-number">2</span>;
assert.<span class="hljs-title function_">strictEqual</span>(apples, oranges, <span class="hljs-string">`apples <span class="hljs-subst">${apples}</span> !== oranges <span class="hljs-subst">${oranges}</span>`</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Inputs are not identical'</span>));
<span class="hljs-comment">// TypeError: Inputs are not identical</span></code><button class="copy-button">copy</button></pre>
<p>If the values are not strictly equal, an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> is thrown with a
<code>message</code> property set equal to the value of the <code>message</code> parameter. If the
<code>message</code> parameter is undefined, a default error message is assigned. If the
<code>message</code> parameter is an instance of an <a href="#all_errors_class-error"><code>Error</code></a> then it will be thrown
instead of the <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>
</section><section><h3><code>assert.throws(fn[, error][, message])</code><span><a class="mark" href="#all_assert_assertthrowsfn-error-message" id="all_assert_assertthrowsfn-error-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_throws_fn_error_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.2.0</td>
<td><p>The <code>error</code> parameter can be an object containing regular expressions now.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>The <code>error</code> parameter can now be an object as well.</p></td></tr>
<tr><td>v4.2.0</td>
<td><p>The <code>error</code> parameter can now be an arrow function.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type"><RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Expects the function <code>fn</code> to throw an error.</p>
<p>If specified, <code>error</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><code>Class</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>, a validation function,
a validation object where each property will be tested for strict deep equality,
or an instance of error where each property will be tested for strict deep
equality including the non-enumerable <code>message</code> and <code>name</code> properties. When
using an object, it is also possible to use a regular expression, when
validating against a string property. See below for examples.</p>
<p>If specified, <code>message</code> will be appended to the message provided by the
<code>AssertionError</code> if the <code>fn</code> call fails to throw or in case the error validation
fails.</p>
<p>Custom validation object/error instance:</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
<span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
err.<span class="hljs-property">code</span> = <span class="hljs-number">404</span>;
err.<span class="hljs-property">foo</span> = <span class="hljs-string">'bar'</span>;
err.<span class="hljs-property">info</span> = {
<span class="hljs-attr">nested</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">baz</span>: <span class="hljs-string">'text'</span>,
};
err.<span class="hljs-property">reg</span> = <span class="hljs-regexp">/abc/i</span>;
assert.<span class="hljs-title function_">throws</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> err;
},
{
<span class="hljs-attr">name</span>: <span class="hljs-string">'TypeError'</span>,
<span class="hljs-attr">message</span>: <span class="hljs-string">'Wrong value'</span>,
<span class="hljs-attr">info</span>: {
<span class="hljs-attr">nested</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">baz</span>: <span class="hljs-string">'text'</span>,
},
<span class="hljs-comment">// Only properties on the validation object will be tested for.</span>
<span class="hljs-comment">// Using nested objects requires all properties to be present. Otherwise</span>
<span class="hljs-comment">// the validation is going to fail.</span>
},
);
<span class="hljs-comment">// Using regular expressions to validate error properties:</span>
assert.<span class="hljs-title function_">throws</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> err;
},
{
<span class="hljs-comment">// The `name` and `message` properties are strings and using regular</span>
<span class="hljs-comment">// expressions on those will match against the string. If they fail, an</span>
<span class="hljs-comment">// error is thrown.</span>
<span class="hljs-attr">name</span>: <span class="hljs-regexp">/^TypeError$/</span>,
<span class="hljs-attr">message</span>: <span class="hljs-regexp">/Wrong/</span>,
<span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span>,
<span class="hljs-attr">info</span>: {
<span class="hljs-attr">nested</span>: <span class="hljs-literal">true</span>,
<span class="hljs-comment">// It is not possible to use regular expressions for nested properties!</span>
<span class="hljs-attr">baz</span>: <span class="hljs-string">'text'</span>,
},
<span class="hljs-comment">// The `reg` property contains a regular expression and only if the</span>
<span class="hljs-comment">// validation object contains an identical regular expression, it is going</span>
<span class="hljs-comment">// to pass.</span>
<span class="hljs-attr">reg</span>: <span class="hljs-regexp">/abc/i</span>,
},
);
<span class="hljs-comment">// Fails due to the different `message` and `name` properties:</span>
assert.<span class="hljs-title function_">throws</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> otherErr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Not found'</span>);
<span class="hljs-comment">// Copy all enumerable properties from `err` to `otherErr`.</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [key, value] <span class="hljs-keyword">of</span> <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">entries</span>(err)) {
otherErr[key] = value;
}
<span class="hljs-keyword">throw</span> otherErr;
},
<span class="hljs-comment">// The error's `message` and `name` properties will also be checked when using</span>
<span class="hljs-comment">// an error as validation object.</span>
err,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
<span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
err.<span class="hljs-property">code</span> = <span class="hljs-number">404</span>;
err.<span class="hljs-property">foo</span> = <span class="hljs-string">'bar'</span>;
err.<span class="hljs-property">info</span> = {
<span class="hljs-attr">nested</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">baz</span>: <span class="hljs-string">'text'</span>,
};
err.<span class="hljs-property">reg</span> = <span class="hljs-regexp">/abc/i</span>;
assert.<span class="hljs-title function_">throws</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> err;
},
{
<span class="hljs-attr">name</span>: <span class="hljs-string">'TypeError'</span>,
<span class="hljs-attr">message</span>: <span class="hljs-string">'Wrong value'</span>,
<span class="hljs-attr">info</span>: {
<span class="hljs-attr">nested</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">baz</span>: <span class="hljs-string">'text'</span>,
},
<span class="hljs-comment">// Only properties on the validation object will be tested for.</span>
<span class="hljs-comment">// Using nested objects requires all properties to be present. Otherwise</span>
<span class="hljs-comment">// the validation is going to fail.</span>
},
);
<span class="hljs-comment">// Using regular expressions to validate error properties:</span>
assert.<span class="hljs-title function_">throws</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> err;
},
{
<span class="hljs-comment">// The `name` and `message` properties are strings and using regular</span>
<span class="hljs-comment">// expressions on those will match against the string. If they fail, an</span>
<span class="hljs-comment">// error is thrown.</span>
<span class="hljs-attr">name</span>: <span class="hljs-regexp">/^TypeError$/</span>,
<span class="hljs-attr">message</span>: <span class="hljs-regexp">/Wrong/</span>,
<span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span>,
<span class="hljs-attr">info</span>: {
<span class="hljs-attr">nested</span>: <span class="hljs-literal">true</span>,
<span class="hljs-comment">// It is not possible to use regular expressions for nested properties!</span>
<span class="hljs-attr">baz</span>: <span class="hljs-string">'text'</span>,
},
<span class="hljs-comment">// The `reg` property contains a regular expression and only if the</span>
<span class="hljs-comment">// validation object contains an identical regular expression, it is going</span>
<span class="hljs-comment">// to pass.</span>
<span class="hljs-attr">reg</span>: <span class="hljs-regexp">/abc/i</span>,
},
);
<span class="hljs-comment">// Fails due to the different `message` and `name` properties:</span>
assert.<span class="hljs-title function_">throws</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> otherErr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Not found'</span>);
<span class="hljs-comment">// Copy all enumerable properties from `err` to `otherErr`.</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [key, value] <span class="hljs-keyword">of</span> <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">entries</span>(err)) {
otherErr[key] = value;
}
<span class="hljs-keyword">throw</span> otherErr;
},
<span class="hljs-comment">// The error's `message` and `name` properties will also be checked when using</span>
<span class="hljs-comment">// an error as validation object.</span>
err,
);</code><button class="copy-button">copy</button></pre>
<p>Validate instanceof using constructor:</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">throws</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-title class_">Error</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">throws</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-title class_">Error</span>,
);</code><button class="copy-button">copy</button></pre>
<p>Validate error message using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>:</p>
<p>Using a regular expression runs <code>.toString</code> on the error object, and will
therefore also include the error name.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">throws</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-regexp">/^Error: Wrong value$/</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">throws</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-regexp">/^Error: Wrong value$/</span>,
);</code><button class="copy-button">copy</button></pre>
<p>Custom error validation:</p>
<p>The function must return <code>true</code> to indicate all internal validations passed.
It will otherwise fail with an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
assert.<span class="hljs-title function_">throws</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-title function_">assert</span>(err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Error</span>);
<span class="hljs-title function_">assert</span>(<span class="hljs-regexp">/value/</span>.<span class="hljs-title function_">test</span>(err));
<span class="hljs-comment">// Avoid returning anything from validation functions besides `true`.</span>
<span class="hljs-comment">// Otherwise, it's not clear what part of the validation failed. Instead,</span>
<span class="hljs-comment">// throw an error about the specific validation that failed (as done in this</span>
<span class="hljs-comment">// example) and add as much helpful debugging information to that error as</span>
<span class="hljs-comment">// possible.</span>
<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
},
<span class="hljs-string">'unexpected error'</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
assert.<span class="hljs-title function_">throws</span>(
<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>);
},
<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-title function_">assert</span>(err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Error</span>);
<span class="hljs-title function_">assert</span>(<span class="hljs-regexp">/value/</span>.<span class="hljs-title function_">test</span>(err));
<span class="hljs-comment">// Avoid returning anything from validation functions besides `true`.</span>
<span class="hljs-comment">// Otherwise, it's not clear what part of the validation failed. Instead,</span>
<span class="hljs-comment">// throw an error about the specific validation that failed (as done in this</span>
<span class="hljs-comment">// example) and add as much helpful debugging information to that error as</span>
<span class="hljs-comment">// possible.</span>
<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
},
<span class="hljs-string">'unexpected error'</span>,
);</code><button class="copy-button">copy</button></pre>
<p><code>error</code> cannot be a string. If a string is provided as the second
argument, then <code>error</code> is assumed to be omitted and the string will be used for
<code>message</code> instead. This can lead to easy-to-miss mistakes. Using the same
message as the thrown error message is going to result in an
<code>ERR_AMBIGUOUS_ARGUMENT</code> error. Please read the example below carefully if using
a string as the second argument gets considered:</p>
<pre class="with-45-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">throwingFirst</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'First'</span>);
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">throwingSecond</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Second'</span>);
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">notThrowing</span>(<span class="hljs-params"></span>) {}
<span class="hljs-comment">// The second argument is a string and the input function threw an Error.</span>
<span class="hljs-comment">// The first case will not throw as it does not match for the error message</span>
<span class="hljs-comment">// thrown by the input function!</span>
assert.<span class="hljs-title function_">throws</span>(throwingFirst, <span class="hljs-string">'Second'</span>);
<span class="hljs-comment">// In the next example the message has no benefit over the message from the</span>
<span class="hljs-comment">// error and since it is not clear if the user intended to actually match</span>
<span class="hljs-comment">// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.</span>
assert.<span class="hljs-title function_">throws</span>(throwingSecond, <span class="hljs-string">'Second'</span>);
<span class="hljs-comment">// TypeError [ERR_AMBIGUOUS_ARGUMENT]</span>
<span class="hljs-comment">// The string is only used (as message) in case the function does not throw:</span>
assert.<span class="hljs-title function_">throws</span>(notThrowing, <span class="hljs-string">'Second'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Missing expected exception: Second</span>
<span class="hljs-comment">// If it was intended to match for the error message do this instead:</span>
<span class="hljs-comment">// It does not throw because the error messages match.</span>
assert.<span class="hljs-title function_">throws</span>(throwingSecond, <span class="hljs-regexp">/Second$/</span>);
<span class="hljs-comment">// If the error message does not match, an AssertionError is thrown.</span>
assert.<span class="hljs-title function_">throws</span>(throwingFirst, <span class="hljs-regexp">/Second$/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">throwingFirst</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'First'</span>);
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">throwingSecond</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Second'</span>);
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">notThrowing</span>(<span class="hljs-params"></span>) {}
<span class="hljs-comment">// The second argument is a string and the input function threw an Error.</span>
<span class="hljs-comment">// The first case will not throw as it does not match for the error message</span>
<span class="hljs-comment">// thrown by the input function!</span>
assert.<span class="hljs-title function_">throws</span>(throwingFirst, <span class="hljs-string">'Second'</span>);
<span class="hljs-comment">// In the next example the message has no benefit over the message from the</span>
<span class="hljs-comment">// error and since it is not clear if the user intended to actually match</span>
<span class="hljs-comment">// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.</span>
assert.<span class="hljs-title function_">throws</span>(throwingSecond, <span class="hljs-string">'Second'</span>);
<span class="hljs-comment">// TypeError [ERR_AMBIGUOUS_ARGUMENT]</span>
<span class="hljs-comment">// The string is only used (as message) in case the function does not throw:</span>
assert.<span class="hljs-title function_">throws</span>(notThrowing, <span class="hljs-string">'Second'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Missing expected exception: Second</span>
<span class="hljs-comment">// If it was intended to match for the error message do this instead:</span>
<span class="hljs-comment">// It does not throw because the error messages match.</span>
assert.<span class="hljs-title function_">throws</span>(throwingSecond, <span class="hljs-regexp">/Second$/</span>);
<span class="hljs-comment">// If the error message does not match, an AssertionError is thrown.</span>
assert.<span class="hljs-title function_">throws</span>(throwingFirst, <span class="hljs-regexp">/Second$/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]</span></code><button class="copy-button">copy</button></pre>
<p>Due to the confusing error-prone notation, avoid a string as the second
argument.</p></section>
</section>
<section><h2>Asynchronous context tracking<span><a class="mark" href="#all_async_context_asynchronous-context-tracking" id="all_async_context_asynchronous-context-tracking">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynchronous_context_tracking"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/async_hooks.js">lib/async_hooks.js</a></p>
<section><h3>Introduction<span><a class="mark" href="#all_async_context_introduction" id="all_async_context_introduction">#</a></span><a aria-hidden="true" class="legacy" id="async_context_introduction"></a></h3>
<p>These classes are used to associate state and propagate it throughout
callbacks and promise chains.
They allow storing data throughout the lifetime of a web request
or any other asynchronous duration. It is similar to thread-local storage
in other languages.</p>
<p>The <code>AsyncLocalStorage</code> and <code>AsyncResource</code> classes are part of the
<code>node:async_hooks</code> module:</p>
<pre class="with-73-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_">AsyncLocalStorage</span>, <span class="hljs-title class_">AsyncResource</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span>, <span class="hljs-title class_">AsyncResource</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>AsyncLocalStorage</code><span><a class="mark" href="#all_async_context_class-asynclocalstorage" id="all_async_context_class-asynclocalstorage">#</a></span><a aria-hidden="true" class="legacy" id="async_context_class_asynclocalstorage"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.4.0</td>
<td><p>AsyncLocalStorage is now Stable. Previously, it had been Experimental.</p></td></tr>
<tr><td>v13.10.0, v12.17.0</td>
<td><p><span>Added in: v13.10.0, v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>This class creates stores that stay coherent through asynchronous operations.</p>
<p>While you can create your own implementation on top of the <code>node:async_hooks</code>
module, <code>AsyncLocalStorage</code> should be preferred as it is a performant and memory
safe implementation that involves significant optimizations that are non-obvious
to implement.</p>
<p>The following example uses <code>AsyncLocalStorage</code> to build a simple logger
that assigns IDs to incoming HTTP requests and includes them in messages
logged within each request.</p>
<pre class="with-58-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> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">const</span> asyncLocalStorage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">logWithId</span>(<span class="hljs-params">msg</span>) {
<span class="hljs-keyword">const</span> id = asyncLocalStorage.<span class="hljs-title function_">getStore</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${id !== <span class="hljs-literal">undefined</span> ? id : <span class="hljs-string">'-'</span>}</span>:`</span>, msg);
}
<span class="hljs-keyword">let</span> idSeq = <span class="hljs-number">0</span>;
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
asyncLocalStorage.<span class="hljs-title function_">run</span>(idSeq++, <span class="hljs-function">() =></span> {
<span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'start'</span>);
<span class="hljs-comment">// Imagine any chain of async operations here</span>
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
<span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'finish'</span>);
res.<span class="hljs-title function_">end</span>();
});
});
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);
http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 0: start</span>
<span class="hljs-comment">// 1: start</span>
<span class="hljs-comment">// 0: finish</span>
<span class="hljs-comment">// 1: finish</span></code><code class="language-js cjs"><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> { <span class="hljs-title class_">AsyncLocalStorage</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> asyncLocalStorage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">logWithId</span>(<span class="hljs-params">msg</span>) {
<span class="hljs-keyword">const</span> id = asyncLocalStorage.<span class="hljs-title function_">getStore</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${id !== <span class="hljs-literal">undefined</span> ? id : <span class="hljs-string">'-'</span>}</span>:`</span>, msg);
}
<span class="hljs-keyword">let</span> idSeq = <span class="hljs-number">0</span>;
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
asyncLocalStorage.<span class="hljs-title function_">run</span>(idSeq++, <span class="hljs-function">() =></span> {
<span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'start'</span>);
<span class="hljs-comment">// Imagine any chain of async operations here</span>
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
<span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'finish'</span>);
res.<span class="hljs-title function_">end</span>();
});
});
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);
http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 0: start</span>
<span class="hljs-comment">// 1: start</span>
<span class="hljs-comment">// 0: finish</span>
<span class="hljs-comment">// 1: finish</span></code><button class="copy-button">copy</button></pre>
<p>Each instance of <code>AsyncLocalStorage</code> maintains an independent storage context.
Multiple instances can safely exist simultaneously without risk of interfering
with each other's data.</p>
<h4><code>new AsyncLocalStorage()</code><span><a class="mark" href="#all_async_context_new-asynclocalstorage" id="all_async_context_new-asynclocalstorage">#</a></span><a aria-hidden="true" class="legacy" id="async_context_new_asynclocalstorage"></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</td>
<td><p>Removed experimental onPropagate option.</p></td></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p>Add option onPropagate.</p></td></tr>
<tr><td>v13.10.0, v12.17.0</td>
<td><p><span>Added in: v13.10.0, v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Creates a new instance of <code>AsyncLocalStorage</code>. Store is only provided within a
<code>run()</code> call or after an <code>enterWith()</code> call.</p>
<h4>Static method: <code>AsyncLocalStorage.bind(fn)</code><span><a class="mark" href="#all_async_context_static-method-asynclocalstoragebindfn" id="all_async_context_static-method-asynclocalstoragebindfn">#</a></span><a aria-hidden="true" class="legacy" id="async_context_static_method_asynclocalstorage_bind_fn"></a></h4>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_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> The function to bind to the current execution context.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A new function that calls <code>fn</code> within the captured
execution context.</li>
</ul>
<p>Binds the given function to the current execution context.</p>
<h4>Static method: <code>AsyncLocalStorage.snapshot()</code><span><a class="mark" href="#all_async_context_static-method-asynclocalstoragesnapshot" id="all_async_context_static-method-asynclocalstoragesnapshot">#</a></span><a aria-hidden="true" class="legacy" id="async_context_static_method_asynclocalstorage_snapshot"></a></h4>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A new function with the signature
<code>(fn: (...args) : R, ...args) : R</code>.</li>
</ul>
<p>Captures the current execution context and returns a function that accepts a
function as an argument. Whenever the returned function is called, it
calls the function passed to it within the captured context.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> asyncLocalStorage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
<span class="hljs-keyword">const</span> runInAsyncScope = asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-number">123</span>, <span class="hljs-function">() =></span> <span class="hljs-title class_">AsyncLocalStorage</span>.<span class="hljs-title function_">snapshot</span>());
<span class="hljs-keyword">const</span> result = asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-number">321</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-function">() =></span> asyncLocalStorage.<span class="hljs-title function_">getStore</span>()));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); <span class="hljs-comment">// returns 123</span></code> <button class="copy-button">copy</button></pre>
<p>AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
async context tracking purposes, for example:</p>
<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
#runInAsyncScope = <span class="hljs-title class_">AsyncLocalStorage</span>.<span class="hljs-title function_">snapshot</span>();
<span class="hljs-title function_">get</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.#<span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-function">() =></span> asyncLocalStorage.<span class="hljs-title function_">getStore</span>()); }
}
<span class="hljs-keyword">const</span> foo = asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-number">123</span>, <span class="hljs-function">() =></span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>());
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-number">321</span>, <span class="hljs-function">() =></span> foo.<span class="hljs-title function_">get</span>())); <span class="hljs-comment">// returns 123</span></code> <button class="copy-button">copy</button></pre>
<h4><code>asyncLocalStorage.disable()</code><span><a class="mark" href="#all_async_context_asynclocalstoragedisable" id="all_async_context_asynclocalstoragedisable">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_disable"></a></h4>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Disables the instance of <code>AsyncLocalStorage</code>. All subsequent calls
to <code>asyncLocalStorage.getStore()</code> will return <code>undefined</code> until
<code>asyncLocalStorage.run()</code> or <code>asyncLocalStorage.enterWith()</code> is called again.</p>
<p>When calling <code>asyncLocalStorage.disable()</code>, all current contexts linked to the
instance will be exited.</p>
<p>Calling <code>asyncLocalStorage.disable()</code> is required before the
<code>asyncLocalStorage</code> can be garbage collected. This does not apply to stores
provided by the <code>asyncLocalStorage</code>, as those objects are garbage collected
along with the corresponding async resources.</p>
<p>Use this method when the <code>asyncLocalStorage</code> is not in use anymore
in the current process.</p>
<h4><code>asyncLocalStorage.getStore()</code><span><a class="mark" href="#all_async_context_asynclocalstoragegetstore" id="all_async_context_asynclocalstoragegetstore">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_getstore"></a></h4>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Returns the current store.
If called outside of an asynchronous context initialized by
calling <code>asyncLocalStorage.run()</code> or <code>asyncLocalStorage.enterWith()</code>, it
returns <code>undefined</code>.</p>
<h4><code>asyncLocalStorage.enterWith(store)</code><span><a class="mark" href="#all_async_context_asynclocalstorageenterwithstore" id="all_async_context_asynclocalstorageenterwithstore">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_enterwith_store"></a></h4>
<div class="api_metadata">
<span>Added in: v13.11.0, v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>store</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Transitions into the context for the remainder of the current
synchronous execution and then persists the store through any following
asynchronous calls.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
<span class="hljs-comment">// Replaces previous store with the given store object</span>
asyncLocalStorage.<span class="hljs-title function_">enterWith</span>(store);
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
<span class="hljs-title function_">someAsyncOperation</span>(<span class="hljs-function">() =></span> {
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span>
});</code> <button class="copy-button">copy</button></pre>
<p>This transition will continue for the <em>entire</em> synchronous execution.
This means that if, for example, the context is entered within an event
handler subsequent event handlers will also run within that context unless
specifically bound to another context with an <code>AsyncResource</code>. That is why
<code>run()</code> should be preferred over <code>enterWith()</code> unless there are strong reasons
to use the latter method.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'my-event'</span>, <span class="hljs-function">() =></span> {
asyncLocalStorage.<span class="hljs-title function_">enterWith</span>(store);
});
emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'my-event'</span>, <span class="hljs-function">() =></span> {
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span>
});
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
emitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'my-event'</span>);
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span></code> <button class="copy-button">copy</button></pre>
<h4><code>asyncLocalStorage.run(store, callback[, ...args])</code><span><a class="mark" href="#all_async_context_asynclocalstoragerunstore-callback-args" id="all_async_context_asynclocalstoragerunstore-callback-args">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_run_store_callback_args"></a></h4>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<ul>
<li><code>store</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Runs a function synchronously within a context and returns its
return value. The store is not accessible outside of the callback function.
The store is accessible to any asynchronous operations created within the
callback.</p>
<p>The optional <code>args</code> are passed to the callback function.</p>
<p>If the callback function throws an error, the error is thrown by <code>run()</code> too.
The stacktrace is not impacted by this call and the context is exited.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">try</span> {
asyncLocalStorage.<span class="hljs-title function_">run</span>(store, <span class="hljs-function">() =></span> {
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
}, <span class="hljs-number">200</span>);
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>();
});
} <span class="hljs-keyword">catch</span> (e) {
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
<span class="hljs-comment">// The error will be caught here</span>
}</code> <button class="copy-button">copy</button></pre>
<h4><code>asyncLocalStorage.exit(callback[, ...args])</code><span><a class="mark" href="#all_async_context_asynclocalstorageexitcallback-args" id="all_async_context_asynclocalstorageexitcallback-args">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_exit_callback_args"></a></h4>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Runs a function synchronously outside of a context and returns its
return value. The store is not accessible within the callback function or
the asynchronous operations created within the callback. Any <code>getStore()</code>
call done within the callback function will always return <code>undefined</code>.</p>
<p>The optional <code>args</code> are passed to the callback function.</p>
<p>If the callback function throws an error, the error is thrown by <code>exit()</code> too.
The stacktrace is not impacted by this call and the context is re-entered.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-comment">// Within a call to run</span>
<span class="hljs-keyword">try</span> {
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object or value</span>
asyncLocalStorage.<span class="hljs-title function_">exit</span>(<span class="hljs-function">() =></span> {
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>();
});
} <span class="hljs-keyword">catch</span> (e) {
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object or value</span>
<span class="hljs-comment">// The error will be caught here</span>
}</code> <button class="copy-button">copy</button></pre>
<h4>Usage with <code>async/await</code><span><a class="mark" href="#all_async_context_usage-with-asyncawait" id="all_async_context_usage-with-asyncawait">#</a></span><a aria-hidden="true" class="legacy" id="async_context_usage_with_async_await"></a></h4>
<p>If, within an async function, only one <code>await</code> call is to run within a context,
the following pattern should be used:</p>
<pre><code class="language-js"><span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">fn</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">await</span> asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>(), <span class="hljs-function">() =></span> {
asyncLocalStorage.<span class="hljs-title function_">getStore</span>().<span class="hljs-title function_">set</span>(<span class="hljs-string">'key'</span>, value);
<span class="hljs-keyword">return</span> <span class="hljs-title function_">foo</span>(); <span class="hljs-comment">// The return value of foo will be awaited</span>
});
}</code> <button class="copy-button">copy</button></pre>
<p>In this example, the store is only available in the callback function and the
functions called by <code>foo</code>. Outside of <code>run</code>, calling <code>getStore</code> will return
<code>undefined</code>.</p>
<h4>Troubleshooting: Context loss<span><a class="mark" href="#all_async_context_troubleshooting-context-loss" id="all_async_context_troubleshooting-context-loss">#</a></span><a aria-hidden="true" class="legacy" id="async_context_troubleshooting_context_loss"></a></h4>
<p>In most cases, <code>AsyncLocalStorage</code> works without issues. In rare situations, the
current store is lost in one of the asynchronous operations.</p>
<p>If your code is callback-based, it is enough to promisify it with
<a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a> so it starts working with native promises.</p>
<p>If you need to use a callback-based API or your code assumes
a custom thenable implementation, use the <a href="#all_async_context_class-asyncresource"><code>AsyncResource</code></a> class
to associate the asynchronous operation with the correct execution context.
Find the function call responsible for the context loss by logging the content
of <code>asyncLocalStorage.getStore()</code> after the calls you suspect are responsible
for the loss. When the code logs <code>undefined</code>, the last callback called is
probably responsible for the context loss.</p>
</section><section><h3>Class: <code>AsyncResource</code><span><a class="mark" href="#all_async_context_class-asyncresource" id="all_async_context_class-asyncresource">#</a></span><a aria-hidden="true" class="legacy" id="async_context_class_asyncresource"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.4.0</td>
<td><p>AsyncResource is now Stable. Previously, it had been Experimental.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The class <code>AsyncResource</code> is designed to be extended by the embedder's async
resources. Using this, users can easily trigger the lifetime events of their
own resources.</p>
<p>The <code>init</code> hook will trigger when an <code>AsyncResource</code> is instantiated.</p>
<p>The following is an overview of the <code>AsyncResource</code> API.</p>
<pre class="with-72-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_">AsyncResource</span>, executionAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-comment">// AsyncResource() is meant to be extended. Instantiating a</span>
<span class="hljs-comment">// new AsyncResource() also triggers init. If triggerAsyncId is omitted then</span>
<span class="hljs-comment">// async_hook.executionAsyncId() is used.</span>
<span class="hljs-keyword">const</span> asyncResource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncResource</span>(
type, { <span class="hljs-attr">triggerAsyncId</span>: <span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-attr">requireManualDestroy</span>: <span class="hljs-literal">false</span> },
);
<span class="hljs-comment">// Run a function in the execution context of the resource. This will</span>
<span class="hljs-comment">// * establish the context of the resource</span>
<span class="hljs-comment">// * trigger the AsyncHooks before callbacks</span>
<span class="hljs-comment">// * call the provided function `fn` with the supplied arguments</span>
<span class="hljs-comment">// * trigger the AsyncHooks after callbacks</span>
<span class="hljs-comment">// * restore the original execution context</span>
asyncResource.<span class="hljs-title function_">runInAsyncScope</span>(fn, thisArg, ...args);
<span class="hljs-comment">// Call AsyncHooks destroy callbacks.</span>
asyncResource.<span class="hljs-title function_">emitDestroy</span>();
<span class="hljs-comment">// Return the unique ID assigned to the AsyncResource instance.</span>
asyncResource.<span class="hljs-title function_">asyncId</span>();
<span class="hljs-comment">// Return the trigger ID for the AsyncResource instance.</span>
asyncResource.<span class="hljs-title function_">triggerAsyncId</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-comment">// AsyncResource() is meant to be extended. Instantiating a</span>
<span class="hljs-comment">// new AsyncResource() also triggers init. If triggerAsyncId is omitted then</span>
<span class="hljs-comment">// async_hook.executionAsyncId() is used.</span>
<span class="hljs-keyword">const</span> asyncResource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncResource</span>(
type, { <span class="hljs-attr">triggerAsyncId</span>: <span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-attr">requireManualDestroy</span>: <span class="hljs-literal">false</span> },
);
<span class="hljs-comment">// Run a function in the execution context of the resource. This will</span>
<span class="hljs-comment">// * establish the context of the resource</span>
<span class="hljs-comment">// * trigger the AsyncHooks before callbacks</span>
<span class="hljs-comment">// * call the provided function `fn` with the supplied arguments</span>
<span class="hljs-comment">// * trigger the AsyncHooks after callbacks</span>
<span class="hljs-comment">// * restore the original execution context</span>
asyncResource.<span class="hljs-title function_">runInAsyncScope</span>(fn, thisArg, ...args);
<span class="hljs-comment">// Call AsyncHooks destroy callbacks.</span>
asyncResource.<span class="hljs-title function_">emitDestroy</span>();
<span class="hljs-comment">// Return the unique ID assigned to the AsyncResource instance.</span>
asyncResource.<span class="hljs-title function_">asyncId</span>();
<span class="hljs-comment">// Return the trigger ID for the AsyncResource instance.</span>
asyncResource.<span class="hljs-title function_">triggerAsyncId</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>new AsyncResource(type[, options])</code><span><a class="mark" href="#all_async_context_new-asyncresourcetype-options" id="all_async_context_new-asyncresourcetype-options">#</a></span><a aria-hidden="true" class="legacy" id="async_context_new_asyncresource_type_options"></a></h4>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The type of async event.</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>triggerAsyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ID of the execution context that created this
async event. <strong>Default:</strong> <code>executionAsyncId()</code>.</li>
<li><code>requireManualDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, disables <code>emitDestroy</code>
when the object is garbage collected. This usually does not need to be set
(even if <code>emitDestroy</code> is called manually), unless the resource's <code>asyncId</code>
is retrieved and the sensitive API's <code>emitDestroy</code> is called with it.
When set to <code>false</code>, the <code>emitDestroy</code> call on garbage collection
will only take place if there is at least one active <code>destroy</code> hook.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Example usage:</p>
<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">DBQuery</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">AsyncResource</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">db</span>) {
<span class="hljs-variable language_">super</span>(<span class="hljs-string">'DBQuery'</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span> = db;
}
<span class="hljs-title function_">getInfo</span>(<span class="hljs-params">query, callback</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span>.<span class="hljs-title function_">get</span>(query, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =></span> {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runInAsyncScope</span>(callback, <span class="hljs-literal">null</span>, err, data);
});
}
<span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span> = <span class="hljs-literal">null</span>;
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emitDestroy</span>();
}
}</code> <button class="copy-button">copy</button></pre>
<h4>Static method: <code>AsyncResource.bind(fn[, type[, thisArg]])</code><span><a class="mark" href="#all_async_context_static-method-asyncresourcebindfn-type-thisarg" id="all_async_context_static-method-asyncresourcebindfn-type-thisarg">#</a></span><a aria-hidden="true" class="legacy" id="async_context_static_method_asyncresource_bind_fn_type_thisarg"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The <code>asyncResource</code> property added to the bound function has been deprecated and will be removed in a future version.</p></td></tr>
<tr><td>v17.8.0, v16.15.0</td>
<td><p>Changed the default when <code>thisArg</code> is undefined to use <code>this</code> from the caller.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Added optional thisArg.</p></td></tr>
<tr><td>v14.8.0, v12.19.0</td>
<td><p><span>Added in: v14.8.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to bind to the current execution context.</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> An optional name to associate with the underlying
<code>AsyncResource</code>.</li>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Binds the given function to the current execution context.</p>
<h4><code>asyncResource.bind(fn[, thisArg])</code><span><a class="mark" href="#all_async_context_asyncresourcebindfn-thisarg" id="all_async_context_asyncresourcebindfn-thisarg">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_bind_fn_thisarg"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The <code>asyncResource</code> property added to the bound function has been deprecated and will be removed in a future version.</p></td></tr>
<tr><td>v17.8.0, v16.15.0</td>
<td><p>Changed the default when <code>thisArg</code> is undefined to use <code>this</code> from the caller.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Added optional thisArg.</p></td></tr>
<tr><td>v14.8.0, v12.19.0</td>
<td><p><span>Added in: v14.8.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to bind to the current <code>AsyncResource</code>.</li>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Binds the given function to execute to this <code>AsyncResource</code>'s scope.</p>
<h4><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code><span><a class="mark" href="#all_async_context_asyncresourceruninasyncscopefn-thisarg-args" id="all_async_context_asyncresourceruninasyncscopefn-thisarg-args">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_runinasyncscope_fn_thisarg_args"></a></h4>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
</div>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to call in the execution context of this async
resource.</li>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The receiver to be used for the function call.</li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional arguments to pass to the function.</li>
</ul>
<p>Call the provided function with the provided arguments in the execution context
of the async resource. This will establish the context, trigger the AsyncHooks
before callbacks, call the function, trigger the AsyncHooks after callbacks, and
then restore the original execution context.</p>
<h4><code>asyncResource.emitDestroy()</code><span><a class="mark" href="#all_async_context_asyncresourceemitdestroy" id="all_async_context_asyncresourceemitdestroy">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_emitdestroy"></a></h4>
<ul>
<li>Returns: <a href="#all_async_hooks_class-asyncresource" class="type"><AsyncResource></a> A reference to <code>asyncResource</code>.</li>
</ul>
<p>Call all <code>destroy</code> hooks. This should only ever be called once. An error will
be thrown if it is called more than once. This <strong>must</strong> be manually called. If
the resource is left to be collected by the GC then the <code>destroy</code> hooks will
never be called.</p>
<h4><code>asyncResource.asyncId()</code><span><a class="mark" href="#all_async_context_asyncresourceasyncid" id="all_async_context_asyncresourceasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_asyncid"></a></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The unique <code>asyncId</code> assigned to the resource.</li>
</ul>
<h4><code>asyncResource.triggerAsyncId()</code><span><a class="mark" href="#all_async_context_asyncresourcetriggerasyncid" id="all_async_context_asyncresourcetriggerasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_triggerasyncid"></a></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The same <code>triggerAsyncId</code> that is passed to the
<code>AsyncResource</code> constructor.</li>
</ul>
<p><a id="async-resource-worker-pool"></a></p>
<h4>Using <code>AsyncResource</code> for a <code>Worker</code> thread pool<span><a class="mark" href="#all_async_context_using-asyncresource-for-a-worker-thread-pool" id="all_async_context_using-asyncresource-for-a-worker-thread-pool">#</a></span><a aria-hidden="true" class="legacy" id="async_context_using_asyncresource_for_a_worker_thread_pool"></a></h4>
<p>The following example shows how to use the <code>AsyncResource</code> class to properly
provide async tracking for a <a href="#all_worker_threads_class-worker"><code>Worker</code></a> pool. Other resource pools, such as
database connection pools, can follow a similar model.</p>
<p>Assuming that the task is adding two numbers, using a file named
<code>task_processor.js</code> with the following content:</p>
<pre class="with-54-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> { parentPort } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
parentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">task</span>) =></span> {
parentPort.<span class="hljs-title function_">postMessage</span>(task.<span class="hljs-property">a</span> + task.<span class="hljs-property">b</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
parentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">task</span>) =></span> {
parentPort.<span class="hljs-title function_">postMessage</span>(task.<span class="hljs-property">a</span> + task.<span class="hljs-property">b</span>);
});</code><button class="copy-button">copy</button></pre>
<p>a Worker pool around it could use the following structure:</p>
<pre class="with-54-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_">AsyncResource</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Worker</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
<span class="hljs-keyword">const</span> kTaskInfo = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kTaskInfo'</span>);
<span class="hljs-keyword">const</span> kWorkerFreedEvent = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kWorkerFreedEvent'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">AsyncResource</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">callback</span>) {
<span class="hljs-variable language_">super</span>(<span class="hljs-string">'WorkerPoolTaskInfo'</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span> = callback;
}
<span class="hljs-title function_">done</span>(<span class="hljs-params">err, result</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span>, <span class="hljs-literal">null</span>, err, result);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emitDestroy</span>(); <span class="hljs-comment">// `TaskInfo`s are used only once.</span>
}
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPool</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">numThreads</span>) {
<span class="hljs-variable language_">super</span>();
<span class="hljs-variable language_">this</span>.<span class="hljs-property">numThreads</span> = numThreads;
<span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span> = [];
<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span> = [];
<span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span> = [];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < numThreads; i++)
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
<span class="hljs-comment">// Any time the kWorkerFreedEvent is emitted, dispatch</span>
<span class="hljs-comment">// the next task pending in the queue, if any.</span>
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">on</span>(kWorkerFreedEvent, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-property">length</span> > <span class="hljs-number">0</span>) {
<span class="hljs-keyword">const</span> { task, callback } = <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">shift</span>();
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runTask</span>(task, callback);
}
});
}
<span class="hljs-title function_">addNewWorker</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'task_processor.js'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>));
worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
<span class="hljs-comment">// In case of success: Call the callback that was passed to `runTask`,</span>
<span class="hljs-comment">// remove the `TaskInfo` associated with the Worker, and mark it as free</span>
<span class="hljs-comment">// again.</span>
worker[kTaskInfo].<span class="hljs-title function_">done</span>(<span class="hljs-literal">null</span>, result);
worker[kTaskInfo] = <span class="hljs-literal">null</span>;
<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
});
worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-comment">// In case of an uncaught exception: Call the callback that was passed to</span>
<span class="hljs-comment">// `runTask` with the error.</span>
<span class="hljs-keyword">if</span> (worker[kTaskInfo])
worker[kTaskInfo].<span class="hljs-title function_">done</span>(err, <span class="hljs-literal">null</span>);
<span class="hljs-keyword">else</span>
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err);
<span class="hljs-comment">// Remove the worker from the list and start a new Worker to replace the</span>
<span class="hljs-comment">// current one.</span>
<span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">splice</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">indexOf</span>(worker), <span class="hljs-number">1</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
});
<span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">push</span>(worker);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
}
<span class="hljs-title function_">runTask</span>(<span class="hljs-params">task, callback</span>) {
<span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-property">length</span> === <span class="hljs-number">0</span>) {
<span class="hljs-comment">// No free threads, wait until a worker thread becomes free.</span>
<span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">push</span>({ task, callback });
<span class="hljs-keyword">return</span>;
}
<span class="hljs-keyword">const</span> worker = <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">pop</span>();
worker[kTaskInfo] = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span>(callback);
worker.<span class="hljs-title function_">postMessage</span>(task);
}
<span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>) worker.<span class="hljs-title function_">terminate</span>();
}
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncResource</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> kTaskInfo = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kTaskInfo'</span>);
<span class="hljs-keyword">const</span> kWorkerFreedEvent = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kWorkerFreedEvent'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">AsyncResource</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">callback</span>) {
<span class="hljs-variable language_">super</span>(<span class="hljs-string">'WorkerPoolTaskInfo'</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span> = callback;
}
<span class="hljs-title function_">done</span>(<span class="hljs-params">err, result</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span>, <span class="hljs-literal">null</span>, err, result);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emitDestroy</span>(); <span class="hljs-comment">// `TaskInfo`s are used only once.</span>
}
}
<span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPool</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">numThreads</span>) {
<span class="hljs-variable language_">super</span>();
<span class="hljs-variable language_">this</span>.<span class="hljs-property">numThreads</span> = numThreads;
<span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span> = [];
<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span> = [];
<span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span> = [];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < numThreads; i++)
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
<span class="hljs-comment">// Any time the kWorkerFreedEvent is emitted, dispatch</span>
<span class="hljs-comment">// the next task pending in the queue, if any.</span>
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">on</span>(kWorkerFreedEvent, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-property">length</span> > <span class="hljs-number">0</span>) {
<span class="hljs-keyword">const</span> { task, callback } = <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">shift</span>();
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runTask</span>(task, callback);
}
});
}
<span class="hljs-title function_">addNewWorker</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(path.<span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'task_processor.js'</span>));
worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
<span class="hljs-comment">// In case of success: Call the callback that was passed to `runTask`,</span>
<span class="hljs-comment">// remove the `TaskInfo` associated with the Worker, and mark it as free</span>
<span class="hljs-comment">// again.</span>
worker[kTaskInfo].<span class="hljs-title function_">done</span>(<span class="hljs-literal">null</span>, result);
worker[kTaskInfo] = <span class="hljs-literal">null</span>;
<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
});
worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-comment">// In case of an uncaught exception: Call the callback that was passed to</span>
<span class="hljs-comment">// `runTask` with the error.</span>
<span class="hljs-keyword">if</span> (worker[kTaskInfo])
worker[kTaskInfo].<span class="hljs-title function_">done</span>(err, <span class="hljs-literal">null</span>);
<span class="hljs-keyword">else</span>
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err);
<span class="hljs-comment">// Remove the worker from the list and start a new Worker to replace the</span>
<span class="hljs-comment">// current one.</span>
<span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">splice</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">indexOf</span>(worker), <span class="hljs-number">1</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
});
<span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">push</span>(worker);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
}
<span class="hljs-title function_">runTask</span>(<span class="hljs-params">task, callback</span>) {
<span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-property">length</span> === <span class="hljs-number">0</span>) {
<span class="hljs-comment">// No free threads, wait until a worker thread becomes free.</span>
<span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">push</span>({ task, callback });
<span class="hljs-keyword">return</span>;
}
<span class="hljs-keyword">const</span> worker = <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">pop</span>();
worker[kTaskInfo] = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span>(callback);
worker.<span class="hljs-title function_">postMessage</span>(task);
}
<span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>) worker.<span class="hljs-title function_">terminate</span>();
}
}
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-title class_">WorkerPool</span>;</code><button class="copy-button">copy</button></pre>
<p>Without the explicit tracking added by the <code>WorkerPoolTaskInfo</code> objects,
it would appear that the callbacks are associated with the individual <code>Worker</code>
objects. However, the creation of the <code>Worker</code>s is not associated with the
creation of the tasks and does not provide information about when tasks
were scheduled.</p>
<p>This pool could be used as follows:</p>
<pre class="with-47-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_">WorkerPool</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'./worker_pool.js'</span>;
<span class="hljs-keyword">import</span> os <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-keyword">const</span> pool = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPool</span>(os.<span class="hljs-title function_">availableParallelism</span>());
<span class="hljs-keyword">let</span> finished = <span class="hljs-number">0</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">10</span>; i++) {
pool.<span class="hljs-title function_">runTask</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">42</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">100</span> }, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(i, err, result);
<span class="hljs-keyword">if</span> (++finished === <span class="hljs-number">10</span>)
pool.<span class="hljs-title function_">close</span>();
});
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">WorkerPool</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./worker_pool.js'</span>);
<span class="hljs-keyword">const</span> os = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>);
<span class="hljs-keyword">const</span> pool = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPool</span>(os.<span class="hljs-title function_">availableParallelism</span>());
<span class="hljs-keyword">let</span> finished = <span class="hljs-number">0</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">10</span>; i++) {
pool.<span class="hljs-title function_">runTask</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">42</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">100</span> }, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(i, err, result);
<span class="hljs-keyword">if</span> (++finished === <span class="hljs-number">10</span>)
pool.<span class="hljs-title function_">close</span>();
});
}</code><button class="copy-button">copy</button></pre>
<h4>Integrating <code>AsyncResource</code> with <code>EventEmitter</code><span><a class="mark" href="#all_async_context_integrating-asyncresource-with-eventemitter" id="all_async_context_integrating-asyncresource-with-eventemitter">#</a></span><a aria-hidden="true" class="legacy" id="async_context_integrating_asyncresource_with_eventemitter"></a></h4>
<p>Event listeners triggered by an <a href="#all_events_class-eventemitter"><code>EventEmitter</code></a> may be run in a different
execution context than the one that was active when <code>eventEmitter.on()</code> was
called.</p>
<p>The following example shows how to use the <code>AsyncResource</code> class to properly
associate an event listener with the correct execution context. The same
approach can be applied to a <a href="#all_stream_stream"><code>Stream</code></a> or a similar event-driven class.</p>
<pre class="with-72-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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-title class_">AsyncResource</span>.<span class="hljs-title function_">bind</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// Execution context is bound to the current outer scope.</span>
}));
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Execution context is bound to the scope that caused 'close' to emit.</span>
});
res.<span class="hljs-title function_">end</span>();
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-title class_">AsyncResource</span>.<span class="hljs-title function_">bind</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// Execution context is bound to the current outer scope.</span>
}));
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Execution context is bound to the scope that caused 'close' to emit.</span>
});
res.<span class="hljs-title function_">end</span>();
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><button class="copy-button">copy</button></pre></section>
</section>
<section><h2>Async hooks<span><a class="mark" href="#all_async_hooks_async-hooks" id="all_async_hooks_async-hooks">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks"></a></h2>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Please migrate away from this API, if you can.
We do not recommend using the <a href="#all_async_hooks_async_hookscreatehookcallbacks"><code>createHook</code></a>, <a href="#all_async_hooks_class-asynchook"><code>AsyncHook</code></a>, and
<a href="#all_async_hooks_async_hooksexecutionasyncresource"><code>executionAsyncResource</code></a> APIs as they have usability issues, safety risks,
and performance implications. Async context tracking use cases are better
served by the stable <a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a> API. If you have a use case for
<code>createHook</code>, <code>AsyncHook</code>, or <code>executionAsyncResource</code> beyond the context
tracking need solved by <a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a> or diagnostics data currently
provided by <a href="diagnostics_channel.html">Diagnostics Channel</a>, please open an issue at
<a href="https://github.com/nodejs/node/issues">https://github.com/nodejs/node/issues</a> describing your use case so we can
create a more purpose-focused API.</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/async_hooks.js">lib/async_hooks.js</a></p>
<p>We strongly discourage the use of the <code>async_hooks</code> API.
Other APIs that can cover most of its use cases include:</p>
<ul>
<li><a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a> tracks async context</li>
<li><a href="#all_process_processgetactiveresourcesinfo"><code>process.getActiveResourcesInfo()</code></a> tracks active resources</li>
</ul>
<p>The <code>node:async_hooks</code> module provides an API to track asynchronous resources.
It can be accessed using:</p>
<pre class="with-48-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> async_hooks <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>Terminology<span><a class="mark" href="#all_async_hooks_terminology" id="all_async_hooks_terminology">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_terminology"></a></h3>
<p>An asynchronous resource represents an object with an associated callback.
This callback may be called multiple times, such as the <code>'connection'</code>
event in <code>net.createServer()</code>, or just a single time like in <code>fs.open()</code>.
A resource can also be closed before the callback is called. <code>AsyncHook</code> does
not explicitly distinguish between these different cases but will represent them
as the abstract concept that is a resource.</p>
<p>If <a href="#all_worker_threads_class-worker"><code>Worker</code></a>s are used, each thread has an independent <code>async_hooks</code>
interface, and each thread will use a new set of async IDs.</p>
</section><section><h3>Overview<span><a class="mark" href="#all_async_hooks_overview" id="all_async_hooks_overview">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_overview"></a></h3>
<p>Following is a simple overview of the public API.</p>
<pre class="with-48-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> async_hooks <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-comment">// Return the ID of the current execution context.</span>
<span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
<span class="hljs-comment">// Return the ID of the handle responsible for triggering the callback of the</span>
<span class="hljs-comment">// current execution scope to call.</span>
<span class="hljs-keyword">const</span> tid = async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();
<span class="hljs-comment">// Create a new AsyncHook instance. All of these callbacks are optional.</span>
<span class="hljs-keyword">const</span> asyncHook =
async_hooks.<span class="hljs-title function_">createHook</span>({ init, before, after, destroy, promiseResolve });
<span class="hljs-comment">// Allow callbacks of this AsyncHook instance to call. This is not an implicit</span>
<span class="hljs-comment">// action after running the constructor, and must be explicitly run to begin</span>
<span class="hljs-comment">// executing callbacks.</span>
asyncHook.<span class="hljs-title function_">enable</span>();
<span class="hljs-comment">// Disable listening for new asynchronous events.</span>
asyncHook.<span class="hljs-title function_">disable</span>();
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The following are the callbacks that can be passed to createHook().</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// init() is called during object construction. The resource may not have</span>
<span class="hljs-comment">// completed construction when this callback runs. Therefore, all fields of the</span>
<span class="hljs-comment">// resource referenced by "asyncId" may not have been populated.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { }
<span class="hljs-comment">// before() is called just before the resource's callback is called. It can be</span>
<span class="hljs-comment">// called 0-N times for handles (such as TCPWrap), and will be called exactly 1</span>
<span class="hljs-comment">// time for requests (such as FSReqCallback).</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) { }
<span class="hljs-comment">// after() is called just after the resource's callback has finished.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) { }
<span class="hljs-comment">// destroy() is called when the resource is destroyed.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { }
<span class="hljs-comment">// promiseResolve() is called only for promise resources, when the</span>
<span class="hljs-comment">// resolve() function passed to the Promise constructor is invoked</span>
<span class="hljs-comment">// (either directly or through other means of resolving a promise).</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">promiseResolve</span>(<span class="hljs-params">asyncId</span>) { }</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-comment">// Return the ID of the current execution context.</span>
<span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
<span class="hljs-comment">// Return the ID of the handle responsible for triggering the callback of the</span>
<span class="hljs-comment">// current execution scope to call.</span>
<span class="hljs-keyword">const</span> tid = async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();
<span class="hljs-comment">// Create a new AsyncHook instance. All of these callbacks are optional.</span>
<span class="hljs-keyword">const</span> asyncHook =
async_hooks.<span class="hljs-title function_">createHook</span>({ init, before, after, destroy, promiseResolve });
<span class="hljs-comment">// Allow callbacks of this AsyncHook instance to call. This is not an implicit</span>
<span class="hljs-comment">// action after running the constructor, and must be explicitly run to begin</span>
<span class="hljs-comment">// executing callbacks.</span>
asyncHook.<span class="hljs-title function_">enable</span>();
<span class="hljs-comment">// Disable listening for new asynchronous events.</span>
asyncHook.<span class="hljs-title function_">disable</span>();
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The following are the callbacks that can be passed to createHook().</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// init() is called during object construction. The resource may not have</span>
<span class="hljs-comment">// completed construction when this callback runs. Therefore, all fields of the</span>
<span class="hljs-comment">// resource referenced by "asyncId" may not have been populated.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { }
<span class="hljs-comment">// before() is called just before the resource's callback is called. It can be</span>
<span class="hljs-comment">// called 0-N times for handles (such as TCPWrap), and will be called exactly 1</span>
<span class="hljs-comment">// time for requests (such as FSReqCallback).</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) { }
<span class="hljs-comment">// after() is called just after the resource's callback has finished.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) { }
<span class="hljs-comment">// destroy() is called when the resource is destroyed.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { }
<span class="hljs-comment">// promiseResolve() is called only for promise resources, when the</span>
<span class="hljs-comment">// resolve() function passed to the Promise constructor is invoked</span>
<span class="hljs-comment">// (either directly or through other means of resolving a promise).</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">promiseResolve</span>(<span class="hljs-params">asyncId</span>) { }</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>async_hooks.createHook(callbacks)</code><span><a class="mark" href="#all_async_hooks_async_hookscreatehookcallbacks" id="all_async_hooks_async_hookscreatehookcallbacks">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_createhook_callbacks"></a></h3>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><code>callbacks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <a href="#all_async_hooks_hook-callbacks">Hook Callbacks</a> to register
<ul>
<li><code>init</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_async_hooks_initasyncid-type-triggerasyncid-resource"><code>init</code> callback</a>.</li>
<li><code>before</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_async_hooks_beforeasyncid"><code>before</code> callback</a>.</li>
<li><code>after</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_async_hooks_afterasyncid"><code>after</code> callback</a>.</li>
<li><code>destroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_async_hooks_destroyasyncid"><code>destroy</code> callback</a>.</li>
<li><code>promiseResolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_async_hooks_promiseresolveasyncid"><code>promiseResolve</code> callback</a>.</li>
</ul>
</li>
<li>Returns: <a href="#all_async_hooks_async_hookscreatehookcallbacks" class="type"><AsyncHook></a> Instance used for disabling and enabling hooks</li>
</ul>
<p>Registers functions to be called for different lifetime events of each async
operation.</p>
<p>The callbacks <code>init()</code>/<code>before()</code>/<code>after()</code>/<code>destroy()</code> are called for the
respective asynchronous event during a resource's lifetime.</p>
<p>All callbacks are optional. For example, if only resource cleanup needs to
be tracked, then only the <code>destroy</code> callback needs to be passed. The
specifics of all functions that can be passed to <code>callbacks</code> is in the
<a href="#all_async_hooks_hook-callbacks">Hook Callbacks</a> section.</p>
<pre class="with-48-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> { createHook } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">const</span> asyncHook = <span class="hljs-title function_">createHook</span>({
<span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { },
<span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { },
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> asyncHook = async_hooks.<span class="hljs-title function_">createHook</span>({
<span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { },
<span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { },
});</code><button class="copy-button">copy</button></pre>
<p>The callbacks will be inherited via the prototype chain:</p>
<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">MyAsyncCallbacks</span> {
<span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { }
<span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) {}
}
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyAddedCallbacks</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">MyAsyncCallbacks</span> {
<span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) { }
<span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) { }
}
<span class="hljs-keyword">const</span> asyncHook = async_hooks.<span class="hljs-title function_">createHook</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">MyAddedCallbacks</span>());</code> <button class="copy-button">copy</button></pre>
<p>Because promises are asynchronous resources whose lifecycle is tracked
via the async hooks mechanism, the <code>init()</code>, <code>before()</code>, <code>after()</code>, and
<code>destroy()</code> callbacks <em>must not</em> be async functions that return promises.</p>
<h4>Error handling<span><a class="mark" href="#all_async_hooks_error-handling" id="all_async_hooks_error-handling">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_error_handling"></a></h4>
<p>If any <code>AsyncHook</code> callbacks throw, the application will print the stack trace
and exit. The exit path does follow that of an uncaught exception, but
all <code>'uncaughtException'</code> listeners are removed, thus forcing the process to
exit. The <code>'exit'</code> callbacks will still be called unless the application is run
with <code>--abort-on-uncaught-exception</code>, in which case a stack trace will be
printed and the application exits, leaving a core file.</p>
<p>The reason for this error handling behavior is that these callbacks are running
at potentially volatile points in an object's lifetime, for example during
class construction and destruction. Because of this, it is deemed necessary to
bring down the process quickly in order to prevent an unintentional abort in the
future. This is subject to change in the future if a comprehensive analysis is
performed to ensure an exception can follow the normal control flow without
unintentional side effects.</p>
<h4>Printing in <code>AsyncHook</code> callbacks<span><a class="mark" href="#all_async_hooks_printing-in-asynchook-callbacks" id="all_async_hooks_printing-in-asynchook-callbacks">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_printing_in_asynchook_callbacks"></a></h4>
<p>Because printing to the console is an asynchronous operation, <code>console.log()</code>
will cause <code>AsyncHook</code> callbacks to be called. Using <code>console.log()</code> or
similar asynchronous operations inside an <code>AsyncHook</code> callback function will
cause an infinite recursion. An easy solution to this when debugging is to use a
synchronous logging operation such as <code>fs.writeFileSync(file, msg, flag)</code>.
This will print to the file and will not invoke <code>AsyncHook</code> recursively because
it is synchronous.</p>
<pre class="with-40-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> { writeFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { format } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">debug</span>(<span class="hljs-params">...args</span>) {
<span class="hljs-comment">// Use a function like this one when debugging inside an AsyncHook callback</span>
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'log.out'</span>, <span class="hljs-string">`<span class="hljs-subst">${format(...args)}</span>\n`</span>, { <span class="hljs-attr">flag</span>: <span class="hljs-string">'a'</span> });
}</code><code class="language-js cjs"><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> 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_">debug</span>(<span class="hljs-params">...args</span>) {
<span class="hljs-comment">// Use a function like this one when debugging inside an AsyncHook callback</span>
fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'log.out'</span>, <span class="hljs-string">`<span class="hljs-subst">${util.format(...args)}</span>\n`</span>, { <span class="hljs-attr">flag</span>: <span class="hljs-string">'a'</span> });
}</code><button class="copy-button">copy</button></pre>
<p>If an asynchronous operation is needed for logging, it is possible to keep
track of what caused the asynchronous operation using the information
provided by <code>AsyncHook</code> itself. The logging should then be skipped when
it was the logging itself that caused the <code>AsyncHook</code> callback to be called. By
doing this, the otherwise infinite recursion is broken.</p>
</section><section><h3>Class: <code>AsyncHook</code><span><a class="mark" href="#all_async_hooks_class-asynchook" id="all_async_hooks_class-asynchook">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_class_asynchook"></a></h3>
<p>The class <code>AsyncHook</code> exposes an interface for tracking lifetime events
of asynchronous operations.</p>
<h4><code>asyncHook.enable()</code><span><a class="mark" href="#all_async_hooks_asynchookenable" id="all_async_hooks_asynchookenable">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_asynchook_enable"></a></h4>
<ul>
<li>Returns: <a href="#all_async_hooks_async_hookscreatehookcallbacks" class="type"><AsyncHook></a> A reference to <code>asyncHook</code>.</li>
</ul>
<p>Enable the callbacks for a given <code>AsyncHook</code> instance. If no callbacks are
provided, enabling is a no-op.</p>
<p>The <code>AsyncHook</code> instance is disabled by default. If the <code>AsyncHook</code> instance
should be enabled immediately after creation, the following pattern can be used.</p>
<pre class="with-48-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> { createHook } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">const</span> hook = <span class="hljs-title function_">createHook</span>(callbacks).<span class="hljs-title function_">enable</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> hook = async_hooks.<span class="hljs-title function_">createHook</span>(callbacks).<span class="hljs-title function_">enable</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>asyncHook.disable()</code><span><a class="mark" href="#all_async_hooks_asynchookdisable" id="all_async_hooks_asynchookdisable">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_asynchook_disable"></a></h4>
<ul>
<li>Returns: <a href="#all_async_hooks_async_hookscreatehookcallbacks" class="type"><AsyncHook></a> A reference to <code>asyncHook</code>.</li>
</ul>
<p>Disable the callbacks for a given <code>AsyncHook</code> instance from the global pool of
<code>AsyncHook</code> callbacks to be executed. Once a hook has been disabled it will not
be called again until enabled.</p>
<p>For API consistency <code>disable()</code> also returns the <code>AsyncHook</code> instance.</p>
<h4>Hook callbacks<span><a class="mark" href="#all_async_hooks_hook-callbacks" id="all_async_hooks_hook-callbacks">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_hook_callbacks"></a></h4>
<p>Key events in the lifetime of asynchronous events have been categorized into
four areas: instantiation, before/after the callback is called, and when the
instance is destroyed.</p>
<h5><code>init(asyncId, type, triggerAsyncId, resource)</code><span><a class="mark" href="#all_async_hooks_initasyncid-type-triggerasyncid-resource" id="all_async_hooks_initasyncid-type-triggerasyncid-resource">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_init_asyncid_type_triggerasyncid_resource"></a></h5>
<ul>
<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A unique ID for the async resource.</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The type of the async resource.</li>
<li><code>triggerAsyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The unique ID of the async resource in whose
execution context this async resource was created.</li>
<li><code>resource</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Reference to the resource representing the async
operation, needs to be released during <em>destroy</em>.</li>
</ul>
<p>Called when a class is constructed that has the <em>possibility</em> to emit an
asynchronous event. This <em>does not</em> mean the instance must call
<code>before</code>/<code>after</code> before <code>destroy</code> is called, only that the possibility
exists.</p>
<p>This behavior can be observed by doing something like opening a resource then
closing it before the resource can be used. The following snippet demonstrates
this.</p>
<pre class="with-72-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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-title function_">createServer</span>().<span class="hljs-title function_">listen</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">close</span>(); });
<span class="hljs-comment">// OR</span>
<span class="hljs-built_in">clearTimeout</span>(<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">10</span>));</code><code class="language-js cjs"><span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>).<span class="hljs-title function_">createServer</span>().<span class="hljs-title function_">listen</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">close</span>(); });
<span class="hljs-comment">// OR</span>
<span class="hljs-built_in">clearTimeout</span>(<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">10</span>));</code><button class="copy-button">copy</button></pre>
<p>Every new resource is assigned an ID that is unique within the scope of the
current Node.js instance.</p>
<h6><code>type</code><span><a class="mark" href="#all_async_hooks_type" id="all_async_hooks_type">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_type"></a></h6>
<p>The <code>type</code> is a string identifying the type of resource that caused
<code>init</code> to be called. Generally, it will correspond to the name of the
resource's constructor.</p>
<p>The <code>type</code> of resources created by Node.js itself can change in any Node.js
release. Valid values include <code>TLSWRAP</code>,
<code>TCPWRAP</code>, <code>TCPSERVERWRAP</code>, <code>GETADDRINFOREQWRAP</code>, <code>FSREQCALLBACK</code>,
<code>Microtask</code>, and <code>Timeout</code>. Inspect the source code of the Node.js version used
to get the full list.</p>
<p>Furthermore users of <a href="#all_async_context_class-asyncresource"><code>AsyncResource</code></a> create async resources independent
of Node.js itself.</p>
<p>There is also the <code>PROMISE</code> resource type, which is used to track <code>Promise</code>
instances and asynchronous work scheduled by them.</p>
<p>Users are able to define their own <code>type</code> when using the public embedder API.</p>
<p>It is possible to have type name collisions. Embedders are encouraged to use
unique prefixes, such as the npm package name, to prevent collisions when
listening to the hooks.</p>
<h6><code>triggerAsyncId</code><span><a class="mark" href="#all_async_hooks_triggerasyncid" id="all_async_hooks_triggerasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_triggerasyncid"></a></h6>
<p><code>triggerAsyncId</code> is the <code>asyncId</code> of the resource that caused (or "triggered")
the new resource to initialize and that caused <code>init</code> to call. This is different
from <code>async_hooks.executionAsyncId()</code> that only shows <em>when</em> a resource was
created, while <code>triggerAsyncId</code> shows <em>why</em> a resource was created.</p>
<p>The following is a simple demonstration of <code>triggerAsyncId</code>:</p>
<pre class="with-69-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> { createHook, executionAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">import</span> { stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> net <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">createHook</span>({
<span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
<span class="hljs-keyword">const</span> eid = <span class="hljs-title function_">executionAsyncId</span>();
fs.<span class="hljs-title function_">writeSync</span>(
stdout.<span class="hljs-property">fd</span>,
<span class="hljs-string">`<span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>): trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
},
}).<span class="hljs-title function_">enable</span>();
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createHook, executionAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> { stdout } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</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_">createHook</span>({
<span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
<span class="hljs-keyword">const</span> eid = <span class="hljs-title function_">executionAsyncId</span>();
fs.<span class="hljs-title function_">writeSync</span>(
stdout.<span class="hljs-property">fd</span>,
<span class="hljs-string">`<span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>): trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
},
}).<span class="hljs-title function_">enable</span>();
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);</code><button class="copy-button">copy</button></pre>
<p>Output when hitting the server with <code>nc localhost 8080</code>:</p>
<pre><code class="language-console">TCPSERVERWRAP(5): trigger: 1 execution: 1
TCPWRAP(7): trigger: 5 execution: 0</code> <button class="copy-button">copy</button></pre>
<p>The <code>TCPSERVERWRAP</code> is the server which receives the connections.</p>
<p>The <code>TCPWRAP</code> is the new connection from the client. When a new
connection is made, the <code>TCPWrap</code> instance is immediately constructed. This
happens outside of any JavaScript stack. (An <code>executionAsyncId()</code> of <code>0</code> means
that it is being executed from C++ with no JavaScript stack above it.) With only
that information, it would be impossible to link resources together in
terms of what caused them to be created, so <code>triggerAsyncId</code> is given the task
of propagating what resource is responsible for the new resource's existence.</p>
<h6><code>resource</code><span><a class="mark" href="#all_async_hooks_resource" id="all_async_hooks_resource">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_resource"></a></h6>
<p><code>resource</code> is an object that represents the actual async resource that has
been initialized. The API to access the object may be specified by the
creator of the resource. Resources created by Node.js itself are internal
and may change at any time. Therefore no API is specified for these.</p>
<p>In some cases the resource object is reused for performance reasons, it is
thus not safe to use it as a key in a <code>WeakMap</code> or add properties to it.</p>
<h6>Asynchronous context example<span><a class="mark" href="#all_async_hooks_asynchronous-context-example" id="all_async_hooks_asynchronous-context-example">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_asynchronous_context_example"></a></h6>
<p>The context tracking use case is covered by the stable API <a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a>.
This example only illustrates async hooks operation but <a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a>
fits better to this use case.</p>
<p>The following is an example with additional information about the calls to
<code>init</code> between the <code>before</code> and <code>after</code> calls, specifically what the
callback to <code>listen()</code> will look like. The output formatting is slightly more
elaborate to make calling context easier to see.</p>
<pre class="with-48-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> async_hooks <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</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">import</span> net <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">import</span> { stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> { fd } = stdout;
<span class="hljs-keyword">let</span> indent = <span class="hljs-number">0</span>;
async_hooks.<span class="hljs-title function_">createHook</span>({
<span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
<span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
<span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
fs.<span class="hljs-title function_">writeSync</span>(
fd,
<span class="hljs-string">`<span class="hljs-subst">${indentStr}</span><span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>):`</span> +
<span class="hljs-string">` trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
},
<span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) {
<span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>before: <span class="hljs-subst">${asyncId}</span>\n`</span>);
indent += <span class="hljs-number">2</span>;
},
<span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) {
indent -= <span class="hljs-number">2</span>;
<span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>after: <span class="hljs-subst">${asyncId}</span>\n`</span>);
},
<span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) {
<span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>destroy: <span class="hljs-subst">${asyncId}</span>\n`</span>);
},
}).<span class="hljs-title function_">enable</span>();
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">() =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Let's wait 10ms before logging the server started.</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">'>>>'</span>, async_hooks.<span class="hljs-title function_">executionAsyncId</span>());
}, <span class="hljs-number">10</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</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> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> { fd } = process.<span class="hljs-property">stdout</span>;
<span class="hljs-keyword">let</span> indent = <span class="hljs-number">0</span>;
async_hooks.<span class="hljs-title function_">createHook</span>({
<span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
<span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
<span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
fs.<span class="hljs-title function_">writeSync</span>(
fd,
<span class="hljs-string">`<span class="hljs-subst">${indentStr}</span><span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>):`</span> +
<span class="hljs-string">` trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
},
<span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) {
<span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>before: <span class="hljs-subst">${asyncId}</span>\n`</span>);
indent += <span class="hljs-number">2</span>;
},
<span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) {
indent -= <span class="hljs-number">2</span>;
<span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>after: <span class="hljs-subst">${asyncId}</span>\n`</span>);
},
<span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) {
<span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>destroy: <span class="hljs-subst">${asyncId}</span>\n`</span>);
},
}).<span class="hljs-title function_">enable</span>();
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">() =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Let's wait 10ms before logging the server started.</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">'>>>'</span>, async_hooks.<span class="hljs-title function_">executionAsyncId</span>());
}, <span class="hljs-number">10</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Output from only starting the server:</p>
<pre><code class="language-console">TCPSERVERWRAP(5): trigger: 1 execution: 1
TickObject(6): trigger: 5 execution: 1
before: 6
Timeout(7): trigger: 6 execution: 6
after: 6
destroy: 6
before: 7
<span class="hljs-meta prompt_">></span><span class="language-bash">>> 7</span>
TickObject(8): trigger: 7 execution: 7
after: 7
before: 8
after: 8</code> <button class="copy-button">copy</button></pre>
<p>As illustrated in the example, <code>executionAsyncId()</code> and <code>execution</code> each specify
the value of the current execution context; which is delineated by calls to
<code>before</code> and <code>after</code>.</p>
<p>Only using <code>execution</code> to graph resource allocation results in the following:</p>
<pre><code class="language-console"> root(1)
^
|
TickObject(6)
^
|
Timeout(7)</code> <button class="copy-button">copy</button></pre>
<p>The <code>TCPSERVERWRAP</code> is not part of this graph, even though it was the reason for
<code>console.log()</code> being called. This is because binding to a port without a host
name is a <em>synchronous</em> operation, but to maintain a completely asynchronous
API the user's callback is placed in a <code>process.nextTick()</code>. Which is why
<code>TickObject</code> is present in the output and is a 'parent' for <code>.listen()</code>
callback.</p>
<p>The graph only shows <em>when</em> a resource was created, not <em>why</em>, so to track
the <em>why</em> use <code>triggerAsyncId</code>. Which can be represented with the following
graph:</p>
<pre><code class="language-console"> bootstrap(1)
|
˅
TCPSERVERWRAP(5)
|
˅
TickObject(6)
|
˅
Timeout(7)</code> <button class="copy-button">copy</button></pre>
<h5><code>before(asyncId)</code><span><a class="mark" href="#all_async_hooks_beforeasyncid" id="all_async_hooks_beforeasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_before_asyncid"></a></h5>
<ul>
<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>When an asynchronous operation is initiated (such as a TCP server receiving a
new connection) or completes (such as writing data to disk) a callback is
called to notify the user. The <code>before</code> callback is called just before said
callback is executed. <code>asyncId</code> is the unique identifier assigned to the
resource about to execute the callback.</p>
<p>The <code>before</code> callback will be called 0 to N times. The <code>before</code> callback
will typically be called 0 times if the asynchronous operation was cancelled
or, for example, if no connections are received by a TCP server. Persistent
asynchronous resources like a TCP server will typically call the <code>before</code>
callback multiple times, while other operations like <code>fs.open()</code> will call
it only once.</p>
<h5><code>after(asyncId)</code><span><a class="mark" href="#all_async_hooks_afterasyncid" id="all_async_hooks_afterasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_after_asyncid"></a></h5>
<ul>
<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Called immediately after the callback specified in <code>before</code> is completed.</p>
<p>If an uncaught exception occurs during execution of the callback, then <code>after</code>
will run <em>after</em> the <code>'uncaughtException'</code> event is emitted or a <code>domain</code>'s
handler runs.</p>
<h5><code>destroy(asyncId)</code><span><a class="mark" href="#all_async_hooks_destroyasyncid" id="all_async_hooks_destroyasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_destroy_asyncid"></a></h5>
<ul>
<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Called after the resource corresponding to <code>asyncId</code> is destroyed. It is also
called asynchronously from the embedder API <code>emitDestroy()</code>.</p>
<p>Some resources depend on garbage collection for cleanup, so if a reference is
made to the <code>resource</code> object passed to <code>init</code> it is possible that <code>destroy</code>
will never be called, causing a memory leak in the application. If the resource
does not depend on garbage collection, then this will not be an issue.</p>
<p>Using the destroy hook results in additional overhead because it enables
tracking of <code>Promise</code> instances via the garbage collector.</p>
<h5><code>promiseResolve(asyncId)</code><span><a class="mark" href="#all_async_hooks_promiseresolveasyncid" id="all_async_hooks_promiseresolveasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_promiseresolve_asyncid"></a></h5>
<div class="api_metadata">
<span>Added in: v8.6.0</span>
</div>
<ul>
<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Called when the <code>resolve</code> function passed to the <code>Promise</code> constructor is
invoked (either directly or through other means of resolving a promise).</p>
<p><code>resolve()</code> does not do any observable synchronous work.</p>
<p>The <code>Promise</code> is not necessarily fulfilled or rejected at this point if the
<code>Promise</code> was resolved by assuming the state of another <code>Promise</code>.</p>
<pre><code class="language-js"><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-title function_">resolve</span>(<span class="hljs-literal">true</span>)).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">a</span>) =></span> {});</code> <button class="copy-button">copy</button></pre>
<p>calls the following callbacks:</p>
<pre><code class="language-text">init for PROMISE with id 5, trigger id: 1
promise resolve 5 # corresponds to resolve(true)
init for PROMISE with id 6, trigger id: 5 # the Promise returned by then()
before 6 # the then() callback is entered
promise resolve 6 # the then() callback resolves the promise by returning
after 6</code> <button class="copy-button">copy</button></pre>
<h4><code>async_hooks.executionAsyncResource()</code><span><a class="mark" href="#all_async_hooks_async_hooksexecutionasyncresource" id="all_async_hooks_async_hooksexecutionasyncresource">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_executionasyncresource"></a></h4>
<div class="api_metadata">
<span>Added in: v13.9.0, v12.17.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The resource representing the current execution.
Useful to store data within the resource.</li>
</ul>
<p>Resource objects returned by <code>executionAsyncResource()</code> are most often internal
Node.js handle objects with undocumented APIs. Using any functions or properties
on the object is likely to crash your application and should be avoided.</p>
<p>Using <code>executionAsyncResource()</code> in the top-level execution context will
return an empty object as there is no handle or request object to use,
but having an object representing the top-level can be helpful.</p>
<pre class="with-81-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> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { executionAsyncId, executionAsyncResource } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>()); <span class="hljs-comment">// 1 {}</span>
<span class="hljs-title function_">open</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>), <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>()); <span class="hljs-comment">// 7 FSReqWrap</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { open } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { executionAsyncId, executionAsyncResource } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>()); <span class="hljs-comment">// 1 {}</span>
<span class="hljs-title function_">open</span>(__filename, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>()); <span class="hljs-comment">// 7 FSReqWrap</span>
});</code><button class="copy-button">copy</button></pre>
<p>This can be used to implement continuation local storage without the
use of a tracking <code>Map</code> to store the metadata:</p>
<pre class="with-46-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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> {
executionAsyncId,
executionAsyncResource,
createHook,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">const</span> sym = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'state'</span>); <span class="hljs-comment">// Private symbol to avoid pollution</span>
<span class="hljs-title function_">createHook</span>({
<span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) {
<span class="hljs-keyword">const</span> cr = <span class="hljs-title function_">executionAsyncResource</span>();
<span class="hljs-keyword">if</span> (cr) {
resource[sym] = cr[sym];
}
},
}).<span class="hljs-title function_">enable</span>();
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
<span class="hljs-title function_">executionAsyncResource</span>()[sym] = { <span class="hljs-attr">state</span>: req.<span class="hljs-property">url</span> };
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(<span class="hljs-title function_">executionAsyncResource</span>()[sym]));
}, <span class="hljs-number">100</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> {
executionAsyncId,
executionAsyncResource,
createHook,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> sym = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'state'</span>); <span class="hljs-comment">// Private symbol to avoid pollution</span>
<span class="hljs-title function_">createHook</span>({
<span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) {
<span class="hljs-keyword">const</span> cr = <span class="hljs-title function_">executionAsyncResource</span>();
<span class="hljs-keyword">if</span> (cr) {
resource[sym] = cr[sym];
}
},
}).<span class="hljs-title function_">enable</span>();
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
<span class="hljs-title function_">executionAsyncResource</span>()[sym] = { <span class="hljs-attr">state</span>: req.<span class="hljs-property">url</span> };
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(<span class="hljs-title function_">executionAsyncResource</span>()[sym]));
}, <span class="hljs-number">100</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>async_hooks.executionAsyncId()</code><span><a class="mark" href="#all_async_hooks_async_hooksexecutionasyncid" id="all_async_hooks_async_hooksexecutionasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_executionasyncid"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.2.0</td>
<td><p>Renamed from <code>currentId</code>.</p></td></tr>
<tr><td>v8.1.0</td>
<td><p><span>Added in: v8.1.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The <code>asyncId</code> of the current execution context. Useful to
track when something calls.</li>
</ul>
<pre class="with-52-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> { executionAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>()); <span class="hljs-comment">// 1 - bootstrap</span>
<span class="hljs-keyword">const</span> path = <span class="hljs-string">'.'</span>;
fs.<span class="hljs-title function_">open</span>(path, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>()); <span class="hljs-comment">// 6 - open()</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</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-variable language_">console</span>.<span class="hljs-title function_">log</span>(async_hooks.<span class="hljs-title function_">executionAsyncId</span>()); <span class="hljs-comment">// 1 - bootstrap</span>
<span class="hljs-keyword">const</span> path = <span class="hljs-string">'.'</span>;
fs.<span class="hljs-title function_">open</span>(path, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(async_hooks.<span class="hljs-title function_">executionAsyncId</span>()); <span class="hljs-comment">// 6 - open()</span>
});</code><button class="copy-button">copy</button></pre>
<p>The ID returned from <code>executionAsyncId()</code> is related to execution timing, not
causality (which is covered by <code>triggerAsyncId()</code>):</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {
<span class="hljs-comment">// Returns the ID of the server, not of the new connection, because the</span>
<span class="hljs-comment">// callback runs in the execution scope of the server's MakeCallback().</span>
async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
}).<span class="hljs-title function_">listen</span>(port, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Returns the ID of a TickObject (process.nextTick()) because all</span>
<span class="hljs-comment">// callbacks passed to .listen() are wrapped in a nextTick().</span>
async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
});</code> <button class="copy-button">copy</button></pre>
<p>Promise contexts may not get precise <code>executionAsyncIds</code> by default.
See the section on <a href="#all_async_hooks_promise-execution-tracking">promise execution tracking</a>.</p>
<h4><code>async_hooks.triggerAsyncId()</code><span><a class="mark" href="#all_async_hooks_async_hookstriggerasyncid" id="all_async_hooks_async_hookstriggerasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_triggerasyncid"></a></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ID of the resource responsible for calling the callback
that is currently being executed.</li>
</ul>
<pre><code class="language-js"><span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {
<span class="hljs-comment">// The resource that caused (or triggered) this callback to be called</span>
<span class="hljs-comment">// was that of the new connection. Thus the return value of triggerAsyncId()</span>
<span class="hljs-comment">// is the asyncId of "conn".</span>
async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();
}).<span class="hljs-title function_">listen</span>(port, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Even though all callbacks passed to .listen() are wrapped in a nextTick()</span>
<span class="hljs-comment">// the callback itself exists because the call to the server's .listen()</span>
<span class="hljs-comment">// was made. So the return value would be the ID of the server.</span>
async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();
});</code> <button class="copy-button">copy</button></pre>
<p>Promise contexts may not get valid <code>triggerAsyncId</code>s by default. See
the section on <a href="#all_async_hooks_promise-execution-tracking">promise execution tracking</a>.</p>
<h4><code>async_hooks.asyncWrapProviders</code><span><a class="mark" href="#all_async_hooks_async_hooksasyncwrapproviders" id="all_async_hooks_async_hooksasyncwrapproviders">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_asyncwrapproviders"></a></h4>
<div class="api_metadata">
<span>Added in: v17.2.0, v16.14.0</span>
</div>
<ul>
<li>Returns: A map of provider types to the corresponding numeric id.
This map contains all the event types that might be emitted by the <code>async_hooks.init()</code> event.</li>
</ul>
<p>This feature suppresses the deprecated usage of <code>process.binding('async_wrap').Providers</code>.
See: <a href="#all_deprecations_dep0111-processbinding">DEP0111</a></p>
</section><section><h3>Promise execution tracking<span><a class="mark" href="#all_async_hooks_promise-execution-tracking" id="all_async_hooks_promise-execution-tracking">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_promise_execution_tracking"></a></h3>
<p>By default, promise executions are not assigned <code>asyncId</code>s due to the relatively
expensive nature of the <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit">promise introspection API</a> provided by
V8. This means that programs using promises or <code>async</code>/<code>await</code> will not get
correct execution and trigger ids for promise callback contexts by default.</p>
<pre class="with-73-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> { executionAsyncId, triggerAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${executionAsyncId()}</span> tid <span class="hljs-subst">${triggerAsyncId()}</span>`</span>);
});
<span class="hljs-comment">// produces:</span>
<span class="hljs-comment">// eid 1 tid 0</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { executionAsyncId, triggerAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${executionAsyncId()}</span> tid <span class="hljs-subst">${triggerAsyncId()}</span>`</span>);
});
<span class="hljs-comment">// produces:</span>
<span class="hljs-comment">// eid 1 tid 0</span></code><button class="copy-button">copy</button></pre>
<p>Observe that the <code>then()</code> callback claims to have executed in the context of the
outer scope even though there was an asynchronous hop involved. Also,
the <code>triggerAsyncId</code> value is <code>0</code>, which means that we are missing context about
the resource that caused (triggered) the <code>then()</code> callback to be executed.</p>
<p>Installing async hooks via <code>async_hooks.createHook</code> enables promise execution
tracking:</p>
<pre class="with-85-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> { createHook, executionAsyncId, triggerAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-title function_">createHook</span>({ <span class="hljs-title function_">init</span>(<span class="hljs-params"></span>) {} }).<span class="hljs-title function_">enable</span>(); <span class="hljs-comment">// forces PromiseHooks to be enabled.</span>
<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${executionAsyncId()}</span> tid <span class="hljs-subst">${triggerAsyncId()}</span>`</span>);
});
<span class="hljs-comment">// produces:</span>
<span class="hljs-comment">// eid 7 tid 6</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createHook, executionAsyncId, triggerAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-title function_">createHook</span>({ <span class="hljs-title function_">init</span>(<span class="hljs-params"></span>) {} }).<span class="hljs-title function_">enable</span>(); <span class="hljs-comment">// forces PromiseHooks to be enabled.</span>
<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${executionAsyncId()}</span> tid <span class="hljs-subst">${triggerAsyncId()}</span>`</span>);
});
<span class="hljs-comment">// produces:</span>
<span class="hljs-comment">// eid 7 tid 6</span></code><button class="copy-button">copy</button></pre>
<p>In this example, adding any actual hook function enabled the tracking of
promises. There are two promises in the example above; the promise created by
<code>Promise.resolve()</code> and the promise returned by the call to <code>then()</code>. In the
example above, the first promise got the <code>asyncId</code> <code>6</code> and the latter got
<code>asyncId</code> <code>7</code>. During the execution of the <code>then()</code> callback, we are executing
in the context of promise with <code>asyncId</code> <code>7</code>. This promise was triggered by
async resource <code>6</code>.</p>
<p>Another subtlety with promises is that <code>before</code> and <code>after</code> callbacks are run
only on chained promises. That means promises not created by <code>then()</code>/<code>catch()</code>
will not have the <code>before</code> and <code>after</code> callbacks fired on them. For more details
see the details of the V8 <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit">PromiseHooks</a> API.</p>
</section><section><h3>JavaScript embedder API<span><a class="mark" href="#all_async_hooks_javascript-embedder-api" id="all_async_hooks_javascript-embedder-api">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_javascript_embedder_api"></a></h3>
<p>Library developers that handle their own asynchronous resources performing tasks
like I/O, connection pooling, or managing callback queues may use the
<code>AsyncResource</code> JavaScript API so that all the appropriate callbacks are called.</p>
<h4>Class: <code>AsyncResource</code><span><a class="mark" href="#all_async_hooks_class-asyncresource" id="all_async_hooks_class-asyncresource">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_class_asyncresource"></a></h4>
<p>The documentation for this class has moved <a href="#all_async_context_class-asyncresource"><code>AsyncResource</code></a>.</p>
</section><section><h3>Class: <code>AsyncLocalStorage</code><span><a class="mark" href="#all_async_hooks_class-asynclocalstorage" id="all_async_hooks_class-asynclocalstorage">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_class_asynclocalstorage"></a></h3>
<p>The documentation for this class has moved <a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a>.</p></section>
</section>
<section><h2>Buffer<span><a class="mark" href="#all_buffer_buffer" id="all_buffer_buffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/buffer.js">lib/buffer.js</a></p>
<p><code>Buffer</code> objects are used to represent a fixed-length sequence of bytes. Many
Node.js APIs support <code>Buffer</code>s.</p>
<p>The <code>Buffer</code> class is a subclass of JavaScript's <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> class and
extends it with methods that cover additional use cases. Node.js APIs accept
plain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>s wherever <code>Buffer</code>s are supported as well.</p>
<p>While the <code>Buffer</code> class is available within the global scope, it is still
recommended to explicitly reference it via an import or require statement.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Creates a zero-filled Buffer of length 10.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-comment">// Creates a Buffer of length 10,</span>
<span class="hljs-comment">// filled with bytes which all have the value `1`.</span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// Creates an uninitialized buffer of length 10.</span>
<span class="hljs-comment">// This is faster than calling Buffer.alloc() but the returned</span>
<span class="hljs-comment">// Buffer instance might contain old data that needs to be</span>
<span class="hljs-comment">// overwritten using fill(), write(), or other functions that fill the Buffer's</span>
<span class="hljs-comment">// contents.</span>
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">10</span>);
<span class="hljs-comment">// Creates a Buffer containing the bytes [1, 2, 3].</span>
<span class="hljs-keyword">const</span> buf4 = <span class="hljs-title class_">Buffer</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-comment">// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries</span>
<span class="hljs-comment">// are all truncated using `(value & 255)` to fit into the range 0–255.</span>
<span class="hljs-keyword">const</span> buf5 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">257</span>, <span class="hljs-number">257.5</span>, -<span class="hljs-number">255</span>, <span class="hljs-string">'1'</span>]);
<span class="hljs-comment">// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':</span>
<span class="hljs-comment">// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)</span>
<span class="hljs-comment">// [116, 195, 169, 115, 116] (in decimal notation)</span>
<span class="hljs-keyword">const</span> buf6 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'tést'</span>);
<span class="hljs-comment">// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].</span>
<span class="hljs-keyword">const</span> buf7 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'tést'</span>, <span class="hljs-string">'latin1'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Creates a zero-filled Buffer of length 10.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-comment">// Creates a Buffer of length 10,</span>
<span class="hljs-comment">// filled with bytes which all have the value `1`.</span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// Creates an uninitialized buffer of length 10.</span>
<span class="hljs-comment">// This is faster than calling Buffer.alloc() but the returned</span>
<span class="hljs-comment">// Buffer instance might contain old data that needs to be</span>
<span class="hljs-comment">// overwritten using fill(), write(), or other functions that fill the Buffer's</span>
<span class="hljs-comment">// contents.</span>
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">10</span>);
<span class="hljs-comment">// Creates a Buffer containing the bytes [1, 2, 3].</span>
<span class="hljs-keyword">const</span> buf4 = <span class="hljs-title class_">Buffer</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-comment">// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries</span>
<span class="hljs-comment">// are all truncated using `(value & 255)` to fit into the range 0–255.</span>
<span class="hljs-keyword">const</span> buf5 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">257</span>, <span class="hljs-number">257.5</span>, -<span class="hljs-number">255</span>, <span class="hljs-string">'1'</span>]);
<span class="hljs-comment">// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':</span>
<span class="hljs-comment">// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)</span>
<span class="hljs-comment">// [116, 195, 169, 115, 116] (in decimal notation)</span>
<span class="hljs-keyword">const</span> buf6 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'tést'</span>);
<span class="hljs-comment">// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].</span>
<span class="hljs-keyword">const</span> buf7 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'tést'</span>, <span class="hljs-string">'latin1'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>Buffers and character encodings<span><a class="mark" href="#all_buffer_buffers-and-character-encodings" id="all_buffer_buffers-and-character-encodings">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffers_and_character_encodings"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.7.0, v14.18.0</td>
<td><p>Introduced <code>base64url</code> encoding.</p></td></tr>
<tr><td>v6.4.0</td>
<td><p>Introduced <code>latin1</code> as an alias for <code>binary</code>.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>Removed the deprecated <code>raw</code> and <code>raws</code> encodings.</p></td></tr>
</tbody></table>
</details>
</div>
<p>When converting between <code>Buffer</code>s and strings, a character encoding may be
specified. If no character encoding is specified, UTF-8 will be used as the
default.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello world'</span>, <span class="hljs-string">'utf8'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: 68656c6c6f20776f726c64</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'base64'</span>));
<span class="hljs-comment">// Prints: aGVsbG8gd29ybGQ=</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'fhqwhgads'</span>, <span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: <Buffer 66 68 71 77 68 67 61 64 73></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'fhqwhgads'</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello world'</span>, <span class="hljs-string">'utf8'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: 68656c6c6f20776f726c64</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'base64'</span>));
<span class="hljs-comment">// Prints: aGVsbG8gd29ybGQ=</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'fhqwhgads'</span>, <span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: <Buffer 66 68 71 77 68 67 61 64 73></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'fhqwhgads'</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00></span></code><button class="copy-button">copy</button></pre>
<p>Node.js buffers accept all case variations of encoding strings that they
receive. For example, UTF-8 can be specified as <code>'utf8'</code>, <code>'UTF8'</code>, or <code>'uTf8'</code>.</p>
<p>The character encodings currently supported by Node.js are the following:</p>
<ul>
<li>
<p><code>'utf8'</code> (alias: <code>'utf-8'</code>): Multi-byte encoded Unicode characters. Many web
pages and other document formats use <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a>. This is the default character
encoding. When decoding a <code>Buffer</code> into a string that does not exclusively
contain valid UTF-8 data, the Unicode replacement character <code>U+FFFD</code> � will be
used to represent those errors.</p>
</li>
<li>
<p><code>'utf16le'</code> (alias: <code>'utf-16le'</code>): Multi-byte encoded Unicode characters.
Unlike <code>'utf8'</code>, each character in the string will be encoded using either 2
or 4 bytes. Node.js only supports the <a href="https://en.wikipedia.org/wiki/Endianness">little-endian</a> variant of
<a href="https://en.wikipedia.org/wiki/UTF-16">UTF-16</a>.</p>
</li>
<li>
<p><code>'latin1'</code>: Latin-1 stands for <a href="https://en.wikipedia.org/wiki/ISO-8859-1">ISO-8859-1</a>. This character encoding only
supports the Unicode characters from <code>U+0000</code> to <code>U+00FF</code>. Each character is
encoded using a single byte. Characters that do not fit into that range are
truncated and will be mapped to characters in that range.</p>
</li>
</ul>
<p>Converting a <code>Buffer</code> into a string using one of the above is referred to as
decoding, and converting a string into a <code>Buffer</code> is referred to as encoding.</p>
<p>Node.js also supports the following binary-to-text encodings. For
binary-to-text encodings, the naming convention is reversed: Converting a
<code>Buffer</code> into a string is typically referred to as encoding, and converting a
string into a <code>Buffer</code> as decoding.</p>
<ul>
<li>
<p><code>'base64'</code>: <a href="https://en.wikipedia.org/wiki/Base64">Base64</a> encoding. When creating a <code>Buffer</code> from a string,
this encoding will also correctly accept "URL and Filename Safe Alphabet" as
specified in <a href="https://tools.ietf.org/html/rfc4648#section-5">RFC 4648, Section 5</a>. Whitespace characters such as spaces,
tabs, and new lines contained within the base64-encoded string are ignored.</p>
</li>
<li>
<p><code>'base64url'</code>: <a href="https://tools.ietf.org/html/rfc4648#section-5">base64url</a> encoding as specified in
<a href="https://tools.ietf.org/html/rfc4648#section-5">RFC 4648, Section 5</a>. When creating a <code>Buffer</code> from a string, this
encoding will also correctly accept regular base64-encoded strings. When
encoding a <code>Buffer</code> to a string, this encoding will omit padding.</p>
</li>
<li>
<p><code>'hex'</code>: Encode each byte as two hexadecimal characters. Data truncation
may occur when decoding strings that do not exclusively consist of an even
number of hexadecimal characters. See below for an example.</p>
</li>
</ul>
<p>The following legacy character encodings are also supported:</p>
<ul>
<li>
<p><code>'ascii'</code>: For 7-bit <a href="https://en.wikipedia.org/wiki/ASCII">ASCII</a> data only. When encoding a string into a
<code>Buffer</code>, this is equivalent to using <code>'latin1'</code>. When decoding a <code>Buffer</code>
into a string, using this encoding will additionally unset the highest bit of
each byte before decoding as <code>'latin1'</code>.
Generally, there should be no reason to use this encoding, as <code>'utf8'</code>
(or, if the data is known to always be ASCII-only, <code>'latin1'</code>) will be a
better choice when encoding or decoding ASCII-only text. It is only provided
for legacy compatibility.</p>
</li>
<li>
<p><code>'binary'</code>: Alias for <code>'latin1'</code>.
The name of this encoding can be very misleading, as all of the
encodings listed here convert between strings and binary data. For converting
between strings and <code>Buffer</code>s, typically <code>'utf8'</code> is the right choice.</p>
</li>
<li>
<p><code>'ucs2'</code>, <code>'ucs-2'</code>: Aliases of <code>'utf16le'</code>. UCS-2 used to refer to a variant
of UTF-16 that did not support characters that had code points larger than
U+FFFF. In Node.js, these code points are always supported.</p>
</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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1ag123'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// Prints <Buffer 1a>, data truncated when first non-hexadecimal value</span>
<span class="hljs-comment">// ('g') encountered.</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1a7'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1634'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// Prints <Buffer 16 34>, all data represented.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1ag123'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// Prints <Buffer 1a>, data truncated when first non-hexadecimal value</span>
<span class="hljs-comment">// ('g') encountered.</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1a7'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1634'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// Prints <Buffer 16 34>, all data represented.</span></code><button class="copy-button">copy</button></pre>
<p>Modern Web browsers follow the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a> which aliases
both <code>'latin1'</code> and <code>'ISO-8859-1'</code> to <code>'win-1252'</code>. This means that while doing
something like <code>http.get()</code>, if the returned charset is one of those listed in
the WHATWG specification it is possible that the server actually returned
<code>'win-1252'</code>-encoded data, and using <code>'latin1'</code> encoding may incorrectly decode
the characters.</p>
</section><section><h3>Buffers and TypedArrays<span><a class="mark" href="#all_buffer_buffers-and-typedarrays" id="all_buffer_buffers-and-typedarrays">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffers_and_typedarrays"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v3.0.0</td>
<td><p>The <code>Buffer</code>s class now inherits from <code>Uint8Array</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<p><code>Buffer</code> instances are also JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>
instances. All <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> methods are available on <code>Buffer</code>s. There are,
however, subtle incompatibilities between the <code>Buffer</code> API and the
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> API.</p>
<p>In particular:</p>
<ul>
<li>While <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice"><code>TypedArray.prototype.slice()</code></a> creates a copy of part of the <code>TypedArray</code>,
<a href="#all_buffer_bufslicestart-end"><code>Buffer.prototype.slice()</code></a> creates a view over the existing <code>Buffer</code>
without copying. This behavior can be surprising, and only exists for legacy
compatibility. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray"><code>TypedArray.prototype.subarray()</code></a> can be used to achieve
the behavior of <a href="#all_buffer_bufslicestart-end"><code>Buffer.prototype.slice()</code></a> on both <code>Buffer</code>s
and other <code>TypedArray</code>s and should be preferred.</li>
<li><a href="#all_buffer_buftostringencoding-start-end"><code>buf.toString()</code></a> is incompatible with its <code>TypedArray</code> equivalent.</li>
<li>A number of methods, e.g. <a href="#all_buffer_bufindexofvalue-byteoffset-encoding"><code>buf.indexOf()</code></a>, support additional arguments.</li>
</ul>
<p>There are two ways to create new <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instances from a <code>Buffer</code>:</p>
<ul>
<li>Passing a <code>Buffer</code> to a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> constructor will copy the <code>Buffer</code>s
contents, interpreted as an array of integers, and not as a byte sequence
of the target type.</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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</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-keyword">const</span> uint32array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>(buf);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(uint32array);
<span class="hljs-comment">// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</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-keyword">const</span> uint32array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>(buf);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(uint32array);
<span class="hljs-comment">// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]</span></code><button class="copy-button">copy</button></pre>
<ul>
<li>Passing the <code>Buffer</code>s underlying <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> will create a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> that shares its memory with the <code>Buffer</code>.</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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-string">'utf16le'</span>);
<span class="hljs-keyword">const</span> uint16array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(
buf.<span class="hljs-property">buffer</span>,
buf.<span class="hljs-property">byteOffset</span>,
buf.<span class="hljs-property">length</span> / <span class="hljs-title class_">Uint16Array</span>.<span class="hljs-property">BYTES_PER_ELEMENT</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(uint16array);
<span class="hljs-comment">// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-string">'utf16le'</span>);
<span class="hljs-keyword">const</span> uint16array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(
buf.<span class="hljs-property">buffer</span>,
buf.<span class="hljs-property">byteOffset</span>,
buf.<span class="hljs-property">length</span> / <span class="hljs-title class_">Uint16Array</span>.<span class="hljs-property">BYTES_PER_ELEMENT</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(uint16array);
<span class="hljs-comment">// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]</span></code><button class="copy-button">copy</button></pre>
<p>It is possible to create a new <code>Buffer</code> that shares the same allocated
memory as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instance by using the <code>TypedArray</code> object's
<code>.buffer</code> property in the same way. <a href="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length"><code>Buffer.from()</code></a>
behaves like <code>new Uint8Array()</code> in this context.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(<span class="hljs-number">2</span>);
arr[<span class="hljs-number">0</span>] = <span class="hljs-number">5000</span>;
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">4000</span>;
<span class="hljs-comment">// Copies the contents of `arr`.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr);
<span class="hljs-comment">// Shares memory with `arr`.</span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr.<span class="hljs-property">buffer</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 88 a0></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2);
<span class="hljs-comment">// Prints: <Buffer 88 13 a0 0f></span>
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">6000</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 88 a0></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2);
<span class="hljs-comment">// Prints: <Buffer 88 13 70 17></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(<span class="hljs-number">2</span>);
arr[<span class="hljs-number">0</span>] = <span class="hljs-number">5000</span>;
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">4000</span>;
<span class="hljs-comment">// Copies the contents of `arr`.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr);
<span class="hljs-comment">// Shares memory with `arr`.</span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr.<span class="hljs-property">buffer</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 88 a0></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2);
<span class="hljs-comment">// Prints: <Buffer 88 13 a0 0f></span>
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">6000</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 88 a0></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2);
<span class="hljs-comment">// Prints: <Buffer 88 13 70 17></span></code><button class="copy-button">copy</button></pre>
<p>When creating a <code>Buffer</code> using a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>'s <code>.buffer</code>, it is
possible to use only a portion of the underlying <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> by passing in
<code>byteOffset</code> and <code>length</code> parameters.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(<span class="hljs-number">20</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr.<span class="hljs-property">buffer</span>, <span class="hljs-number">0</span>, <span class="hljs-number">16</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 16</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(<span class="hljs-number">20</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr.<span class="hljs-property">buffer</span>, <span class="hljs-number">0</span>, <span class="hljs-number">16</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 16</span></code><button class="copy-button">copy</button></pre>
<p>The <code>Buffer.from()</code> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from"><code>TypedArray.from()</code></a> have different signatures and
implementations. Specifically, the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> variants accept a second
argument that is a mapping function that is invoked on every element of the
typed array:</p>
<ul>
<li><code>TypedArray.from(source[, mapFn[, thisArg]])</code></li>
</ul>
<p>The <code>Buffer.from()</code> method, however, does not support the use of a mapping
function:</p>
<ul>
<li><a href="#all_buffer_static-method-bufferfromarray"><code>Buffer.from(array)</code></a></li>
<li><a href="#all_buffer_static-method-bufferfrombuffer"><code>Buffer.from(buffer)</code></a></li>
<li><a href="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a></li>
<li><a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string[, encoding])</code></a></li>
</ul>
</section><section><h3>Buffers and iteration<span><a class="mark" href="#all_buffer_buffers-and-iteration" id="all_buffer_buffers-and-iteration">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffers_and_iteration"></a></h3>
<p><code>Buffer</code> instances can be iterated over using <code>for..of</code> syntax:</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</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">for</span> (<span class="hljs-keyword">const</span> b <span class="hljs-keyword">of</span> buf) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 1</span>
<span class="hljs-comment">// 2</span>
<span class="hljs-comment">// 3</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</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">for</span> (<span class="hljs-keyword">const</span> b <span class="hljs-keyword">of</span> buf) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 1</span>
<span class="hljs-comment">// 2</span>
<span class="hljs-comment">// 3</span></code><button class="copy-button">copy</button></pre>
<p>Additionally, the <a href="#all_buffer_bufvalues"><code>buf.values()</code></a>, <a href="#all_buffer_bufkeys"><code>buf.keys()</code></a>, and
<a href="#all_buffer_bufentries"><code>buf.entries()</code></a> methods can be used to create iterators.</p>
</section><section><h3>Class: <code>Blob</code><span><a class="mark" href="#all_buffer_class-blob" id="all_buffer_class-blob">#</a></span><a aria-hidden="true" class="legacy" id="buffer_class_blob"></a></h3>
<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, v16.17.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.7.0, v14.18.0</td>
<td><p><span>Added in: v15.7.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>A <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob"><code>Blob</code></a> encapsulates immutable, raw data that can be safely shared across
multiple worker threads.</p>
<h4><code>new buffer.Blob([sources[, options]])</code><span><a class="mark" href="#all_buffer_new-bufferblobsources-options" id="all_buffer_new-bufferblobsources-options">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_blob_sources_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>v16.7.0</td>
<td><p>Added the standard <code>endings</code> option to replace line-endings, and removed the non-standard <code>encoding</code> option.</p></td></tr>
<tr><td>v15.7.0, v14.18.0</td>
<td><p><span>Added in: v15.7.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>sources</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer[]></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="#all_buffer_class-blob" class="type"><Blob[]></a> An
array of string, <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/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="#all_buffer_class-blob" class="type"><Blob></a> objects,
or any mix of such objects, that will be stored within the <code>Blob</code>.</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>endings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> One of either <code>'transparent'</code> or <code>'native'</code>. When set
to <code>'native'</code>, line endings in string source parts will be converted to
the platform native line-ending as specified by <code>require('node:os').EOL</code>.</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The Blob content-type. The intent is for <code>type</code> to convey
the MIME media type of the data, however no validation of the type format
is performed.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>Blob</code> object containing a concatenation of the given sources.</p>
<p><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/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>, and <a href="#all_buffer_class-buffer" class="type"><Buffer></a> sources are copied into
the 'Blob' and can therefore be safely modified after the 'Blob' is created.</p>
<p>String sources are encoded as UTF-8 byte sequences and copied into the Blob.
Unmatched surrogate pairs within each string part will be replaced by Unicode
U+FFFD replacement characters.</p>
<h4><code>blob.arrayBuffer()</code><span><a class="mark" href="#all_buffer_blobarraybuffer" id="all_buffer_blobarraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_arraybuffer"></a></h4>
<div class="api_metadata">
<span>Added in: v15.7.0, v14.18.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Returns a promise that fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> containing a copy of
the <code>Blob</code> data.</p>
<h5><code>blob.bytes()</code><span><a class="mark" href="#all_buffer_blobbytes" id="all_buffer_blobbytes">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_bytes"></a></h5>
<div class="api_metadata">
<span>Added in: v22.3.0</span>
</div>
<p>The <code>blob.bytes()</code> method returns the byte of the <code>Blob</code> object as a <code>Promise<Uint8Array></code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Blob</span>([<span class="hljs-string">'hello'</span>]);
blob.<span class="hljs-title function_">bytes</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">bytes</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(bytes); <span class="hljs-comment">// Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ]</span>
});</code> <button class="copy-button">copy</button></pre>
<h4><code>blob.size</code><span><a class="mark" href="#all_buffer_blobsize" id="all_buffer_blobsize">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_size"></a></h4>
<div class="api_metadata">
<span>Added in: v15.7.0, v14.18.0</span>
</div>
<p>The total size of the <code>Blob</code> in bytes.</p>
<h4><code>blob.slice([start[, end[, type]]])</code><span><a class="mark" href="#all_buffer_blobslicestart-end-type" id="all_buffer_blobslicestart-end-type">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_slice_start_end_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.7.0, v14.18.0</span>
</div>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The starting index.</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ending index.</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The content-type for the new <code>Blob</code></li>
</ul>
<p>Creates and returns a new <code>Blob</code> containing a subset of this <code>Blob</code> objects
data. The original <code>Blob</code> is not altered.</p>
<h4><code>blob.stream()</code><span><a class="mark" href="#all_buffer_blobstream" id="all_buffer_blobstream">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_stream"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li>Returns: <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a></li>
</ul>
<p>Returns a new <code>ReadableStream</code> that allows the content of the <code>Blob</code> to be read.</p>
<h4><code>blob.text()</code><span><a class="mark" href="#all_buffer_blobtext" id="all_buffer_blobtext">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_text"></a></h4>
<div class="api_metadata">
<span>Added in: v15.7.0, v14.18.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Returns a promise that fulfills with the contents of the <code>Blob</code> decoded as a
UTF-8 string.</p>
<h4><code>blob.type</code><span><a class="mark" href="#all_buffer_blobtype" id="all_buffer_blobtype">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.7.0, v14.18.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The content-type of the <code>Blob</code>.</p>
<h4><code>Blob</code> objects and <code>MessageChannel</code><span><a class="mark" href="#all_buffer_blob-objects-and-messagechannel" id="all_buffer_blob-objects-and-messagechannel">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_objects_and_messagechannel"></a></h4>
<p>Once a <a href="#all_buffer_class-blob" class="type"><Blob></a> object is created, it can be sent via <code>MessagePort</code> to multiple
destinations without transferring or immediately copying the data. The data
contained by the <code>Blob</code> is copied only when the <code>arrayBuffer()</code> or <code>text()</code>
methods are called.</p>
<pre class="with-62-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_">Blob</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-built_in">setTimeout</span> <span class="hljs-keyword">as</span> delay } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;
<span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Blob</span>([<span class="hljs-string">'hello there'</span>]);
<span class="hljs-keyword">const</span> mc1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
<span class="hljs-keyword">const</span> mc2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
mc1.<span class="hljs-property">port1</span>.<span class="hljs-property">onmessage</span> = <span class="hljs-title function_">async</span> ({ data }) => {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">await</span> data.<span class="hljs-title function_">arrayBuffer</span>());
mc1.<span class="hljs-property">port1</span>.<span class="hljs-title function_">close</span>();
};
mc2.<span class="hljs-property">port1</span>.<span class="hljs-property">onmessage</span> = <span class="hljs-title function_">async</span> ({ data }) => {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">delay</span>(<span class="hljs-number">1000</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">await</span> data.<span class="hljs-title function_">arrayBuffer</span>());
mc2.<span class="hljs-property">port1</span>.<span class="hljs-title function_">close</span>();
};
mc1.<span class="hljs-property">port2</span>.<span class="hljs-title function_">postMessage</span>(blob);
mc2.<span class="hljs-property">port2</span>.<span class="hljs-title function_">postMessage</span>(blob);
<span class="hljs-comment">// The Blob is still usable after posting.</span>
blob.<span class="hljs-title function_">text</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Blob</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">setTimeout</span>: delay } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);
<span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Blob</span>([<span class="hljs-string">'hello there'</span>]);
<span class="hljs-keyword">const</span> mc1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
<span class="hljs-keyword">const</span> mc2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
mc1.<span class="hljs-property">port1</span>.<span class="hljs-property">onmessage</span> = <span class="hljs-title function_">async</span> ({ data }) => {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">await</span> data.<span class="hljs-title function_">arrayBuffer</span>());
mc1.<span class="hljs-property">port1</span>.<span class="hljs-title function_">close</span>();
};
mc2.<span class="hljs-property">port1</span>.<span class="hljs-property">onmessage</span> = <span class="hljs-title function_">async</span> ({ data }) => {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">delay</span>(<span class="hljs-number">1000</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">await</span> data.<span class="hljs-title function_">arrayBuffer</span>());
mc2.<span class="hljs-property">port1</span>.<span class="hljs-title function_">close</span>();
};
mc1.<span class="hljs-property">port2</span>.<span class="hljs-title function_">postMessage</span>(blob);
mc2.<span class="hljs-property">port2</span>.<span class="hljs-title function_">postMessage</span>(blob);
<span class="hljs-comment">// The Blob is still usable after posting.</span>
blob.<span class="hljs-title function_">text</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>Buffer</code><span><a class="mark" href="#all_buffer_class-buffer" id="all_buffer_class-buffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_class_buffer"></a></h3>
<p>The <code>Buffer</code> class is a global type for dealing with binary data directly.
It can be constructed in a variety of ways.</p>
<h4>Static method: <code>Buffer.alloc(size[, fill[, encoding]])</code><span><a class="mark" href="#all_buffer_static-method-bufferallocsize-fill-encoding" id="all_buffer_static-method-bufferallocsize-fill-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_alloc_size_fill_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Throw ERR_INVALID_ARG_TYPE or ERR_OUT_OF_RANGE instead of ERR_INVALID_ARG_VALUE for invalid input arguments.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE for invalid input arguments.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Specifying an invalid string for <code>fill</code> triggers a thrown exception.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Specifying an invalid string for <code>fill</code> now results in a zero-filled buffer.</p></td></tr>
<tr><td>v5.10.0</td>
<td><p><span>Added in: v5.10.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The desired length of the new <code>Buffer</code>.</li>
<li><code>fill</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> A value to pre-fill the new <code>Buffer</code>
with. <strong>Default:</strong> <code>0</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> If <code>fill</code> is a string, this is its encoding.
<strong>Default:</strong> <code>'utf8'</code>.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Allocates a new <code>Buffer</code> of <code>size</code> bytes. If <code>fill</code> is <code>undefined</code>, the
<code>Buffer</code> will be zero-filled.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">5</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 00 00 00 00 00></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">5</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 00 00 00 00 00></span></code><button class="copy-button">copy</button></pre>
<p>If <code>size</code> is larger than
<a href="#all_buffer_bufferconstantsmax_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#all_errors_err_out_of_range"><code>ERR_OUT_OF_RANGE</code></a>
is thrown.</p>
<p>If <code>fill</code> is specified, the allocated <code>Buffer</code> will be initialized by calling
<a href="#all_buffer_buffillvalue-offset-end-encoding"><code>buf.fill(fill)</code></a>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">5</span>, <span class="hljs-string">'a'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 61 61 61 61 61></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">5</span>, <span class="hljs-string">'a'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 61 61 61 61 61></span></code><button class="copy-button">copy</button></pre>
<p>If both <code>fill</code> and <code>encoding</code> are specified, the allocated <code>Buffer</code> will be
initialized by calling <a href="#all_buffer_buffillvalue-offset-end-encoding"><code>buf.fill(fill, encoding)</code></a>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">11</span>, <span class="hljs-string">'aGVsbG8gd29ybGQ='</span>, <span class="hljs-string">'base64'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">11</span>, <span class="hljs-string">'aGVsbG8gd29ybGQ='</span>, <span class="hljs-string">'base64'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64></span></code><button class="copy-button">copy</button></pre>
<p>Calling <a href="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc()</code></a> can be measurably slower than the alternative
<a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> but ensures that the newly created <code>Buffer</code> instance
contents will never contain sensitive data from previous allocations, including
data that might not have been allocated for <code>Buffer</code>s.</p>
<p>A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</p>
<h4>Static method: <code>Buffer.allocUnsafe(size)</code><span><a class="mark" href="#all_buffer_static-method-bufferallocunsafesize" id="all_buffer_static-method-bufferallocunsafesize">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_allocunsafe_size"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Throw ERR_INVALID_ARG_TYPE or ERR_OUT_OF_RANGE instead of ERR_INVALID_ARG_VALUE for invalid input arguments.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE for invalid input arguments.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Passing a negative <code>size</code> will now throw an error.</p></td></tr>
<tr><td>v5.10.0</td>
<td><p><span>Added in: v5.10.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The desired length of the new <code>Buffer</code>.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Allocates a new <code>Buffer</code> of <code>size</code> bytes. If <code>size</code> is larger than
<a href="#all_buffer_bufferconstantsmax_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#all_errors_err_out_of_range"><code>ERR_OUT_OF_RANGE</code></a>
is thrown.</p>
<p>The underlying memory for <code>Buffer</code> instances created in this way is <em>not
initialized</em>. The contents of the newly created <code>Buffer</code> are unknown and
<em>may contain sensitive data</em>. Use <a href="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc()</code></a> instead to initialize
<code>Buffer</code> instances with zeroes.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32></span>
buf.<span class="hljs-title function_">fill</span>(<span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32></span>
buf.<span class="hljs-title function_">fill</span>(<span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00></span></code><button class="copy-button">copy</button></pre>
<p>A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</p>
<p>The <code>Buffer</code> module pre-allocates an internal <code>Buffer</code> instance of
size <a href="#all_buffer_class-property-bufferpoolsize"><code>Buffer.poolSize</code></a> that is used as a pool for the fast allocation of new
<code>Buffer</code> instances created using <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a>, <a href="#all_buffer_static-method-bufferfromarray"><code>Buffer.from(array)</code></a>,
<a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string)</code></a>, and <a href="#all_buffer_static-method-bufferconcatlist-totallength"><code>Buffer.concat()</code></a> only when <code>size</code> is less than
<code>Buffer.poolSize >>> 1</code> (floor of <a href="#all_buffer_class-property-bufferpoolsize"><code>Buffer.poolSize</code></a> divided by two).</p>
<p>Use of this pre-allocated internal memory pool is a key difference between
calling <code>Buffer.alloc(size, fill)</code> vs. <code>Buffer.allocUnsafe(size).fill(fill)</code>.
Specifically, <code>Buffer.alloc(size, fill)</code> will <em>never</em> use the internal <code>Buffer</code>
pool, while <code>Buffer.allocUnsafe(size).fill(fill)</code> <em>will</em> use the internal
<code>Buffer</code> pool if <code>size</code> is less than or equal to half <a href="#all_buffer_class-property-bufferpoolsize"><code>Buffer.poolSize</code></a>. The
difference is subtle but can be important when an application requires the
additional performance that <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> provides.</p>
<h4>Static method: <code>Buffer.allocUnsafeSlow(size)</code><span><a class="mark" href="#all_buffer_static-method-bufferallocunsafeslowsize" id="all_buffer_static-method-bufferallocunsafeslowsize">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_allocunsafeslow_size"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Throw ERR_INVALID_ARG_TYPE or ERR_OUT_OF_RANGE instead of ERR_INVALID_ARG_VALUE for invalid input arguments.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE for invalid input arguments.</p></td></tr>
<tr><td>v5.12.0</td>
<td><p><span>Added in: v5.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The desired length of the new <code>Buffer</code>.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Allocates a new <code>Buffer</code> of <code>size</code> bytes. If <code>size</code> is larger than
<a href="#all_buffer_bufferconstantsmax_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#all_errors_err_out_of_range"><code>ERR_OUT_OF_RANGE</code></a>
is thrown. A zero-length <code>Buffer</code> is created if <code>size</code> is 0.</p>
<p>The underlying memory for <code>Buffer</code> instances created in this way is <em>not
initialized</em>. The contents of the newly created <code>Buffer</code> are unknown and
<em>may contain sensitive data</em>. Use <a href="#all_buffer_buffillvalue-offset-end-encoding"><code>buf.fill(0)</code></a> to initialize
such <code>Buffer</code> instances with zeroes.</p>
<p>When using <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> to allocate new <code>Buffer</code> instances,
allocations less than <code>Buffer.poolSize >>> 1</code> (4KiB when default poolSize is used) are sliced
from a single pre-allocated <code>Buffer</code>. This allows applications to avoid the
garbage collection overhead of creating many individually allocated <code>Buffer</code>
instances. This approach improves both performance and memory usage by
eliminating the need to track and clean up as many individual <code>ArrayBuffer</code> objects.</p>
<p>However, in the case where a developer may need to retain a small chunk of
memory from a pool for an indeterminate amount of time, it may be appropriate
to create an un-pooled <code>Buffer</code> instance using <code>Buffer.allocUnsafeSlow()</code> and
then copying out the relevant bits.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Need to keep around a few small chunks of memory.</span>
<span class="hljs-keyword">const</span> store = [];
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">let</span> data;
<span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (data = readable.<span class="hljs-title function_">read</span>())) {
<span class="hljs-comment">// Allocate for retained data.</span>
<span class="hljs-keyword">const</span> sb = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafeSlow</span>(<span class="hljs-number">10</span>);
<span class="hljs-comment">// Copy the data into the new allocation.</span>
data.<span class="hljs-title function_">copy</span>(sb, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">10</span>);
store.<span class="hljs-title function_">push</span>(sb);
}
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Need to keep around a few small chunks of memory.</span>
<span class="hljs-keyword">const</span> store = [];
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">let</span> data;
<span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (data = readable.<span class="hljs-title function_">read</span>())) {
<span class="hljs-comment">// Allocate for retained data.</span>
<span class="hljs-keyword">const</span> sb = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafeSlow</span>(<span class="hljs-number">10</span>);
<span class="hljs-comment">// Copy the data into the new allocation.</span>
data.<span class="hljs-title function_">copy</span>(sb, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">10</span>);
store.<span class="hljs-title function_">push</span>(sb);
}
});</code><button class="copy-button">copy</button></pre>
<p>A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</p>
<h4>Static method: <code>Buffer.byteLength(string[, encoding])</code><span><a class="mark" href="#all_buffer_static-method-bufferbytelengthstring-encoding" id="all_buffer_static-method-bufferbytelengthstring-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_bytelength_string_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>Passing invalid input will now throw an error.</p></td></tr>
<tr><td>v5.10.0</td>
<td><p>The <code>string</code> parameter can now be any <code>TypedArray</code>, <code>DataView</code> or <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> A
value to calculate the length of.</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 <code>string</code> is a string, this is its encoding.
<strong>Default:</strong> <code>'utf8'</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of bytes contained within <code>string</code>.</li>
</ul>
<p>Returns the byte length of a string when encoded using <code>encoding</code>.
This is not the same as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length"><code>String.prototype.length</code></a>, which does not account
for the encoding that is used to convert the string into bytes.</p>
<p>For <code>'base64'</code>, <code>'base64url'</code>, and <code>'hex'</code>, this function assumes valid input.
For strings that contain non-base64/hex-encoded data (e.g. whitespace), the
return value might be greater than the length of a <code>Buffer</code> created from the
string.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> str = <span class="hljs-string">'\u00bd + \u00bc = \u00be'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${str}</span>: <span class="hljs-subst">${str.length}</span> characters, `</span> +
<span class="hljs-string">`<span class="hljs-subst">${Buffer.byteLength(str, <span class="hljs-string">'utf8'</span>)}</span> bytes`</span>);
<span class="hljs-comment">// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> str = <span class="hljs-string">'\u00bd + \u00bc = \u00be'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${str}</span>: <span class="hljs-subst">${str.length}</span> characters, `</span> +
<span class="hljs-string">`<span class="hljs-subst">${Buffer.byteLength(str, <span class="hljs-string">'utf8'</span>)}</span> bytes`</span>);
<span class="hljs-comment">// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes</span></code><button class="copy-button">copy</button></pre>
<p>When <code>string</code> is a <code>Buffer</code>/<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView"><code>DataView</code></a>/<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>/<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>/
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a>, the byte length as reported by <code>.byteLength</code>
is returned.</p>
<h4>Static method: <code>Buffer.compare(buf1, buf2)</code><span><a class="mark" href="#all_buffer_static-method-buffercomparebuf1-buf2" id="all_buffer_static-method-buffercomparebuf1-buf2">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_compare_buf1_buf2"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The arguments can now be <code>Uint8Array</code>s.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buf1</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li>
<li><code>buf2</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Either <code>-1</code>, <code>0</code>, or <code>1</code>, depending on the result of the
comparison. See <a href="#all_buffer_bufcomparetarget-targetstart-targetend-sourcestart-sourceend"><code>buf.compare()</code></a> for details.</li>
</ul>
<p>Compares <code>buf1</code> to <code>buf2</code>, typically for the purpose of sorting arrays of
<code>Buffer</code> instances. This is equivalent to calling
<a href="#all_buffer_bufcomparetarget-targetstart-targetend-sourcestart-sourceend"><code>buf1.compare(buf2)</code></a>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1234'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'0123'</span>);
<span class="hljs-keyword">const</span> arr = [buf1, buf2];
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arr.<span class="hljs-title function_">sort</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-property">compare</span>));
<span class="hljs-comment">// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]</span>
<span class="hljs-comment">// (This result is equal to: [buf2, buf1].)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1234'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'0123'</span>);
<span class="hljs-keyword">const</span> arr = [buf1, buf2];
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arr.<span class="hljs-title function_">sort</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-property">compare</span>));
<span class="hljs-comment">// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]</span>
<span class="hljs-comment">// (This result is equal to: [buf2, buf1].)</span></code><button class="copy-button">copy</button></pre>
<h4>Static method: <code>Buffer.concat(list[, totalLength])</code><span><a class="mark" href="#all_buffer_static-method-bufferconcatlist-totallength" id="all_buffer_static-method-bufferconcatlist-totallength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_concat_list_totallength"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The elements of <code>list</code> can now be <code>Uint8Array</code>s.</p></td></tr>
<tr><td>v0.7.11</td>
<td><p><span>Added in: v0.7.11</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>list</code> <a href="#all_buffer_class-buffer" class="type"><Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array[]></a> List of <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>
instances to concatenate.</li>
<li><code>totalLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Total length of the <code>Buffer</code> instances in <code>list</code>
when concatenated.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Returns a new <code>Buffer</code> which is the result of concatenating all the <code>Buffer</code>
instances in the <code>list</code> together.</p>
<p>If the list has no items, or if the <code>totalLength</code> is 0, then a new zero-length
<code>Buffer</code> is returned.</p>
<p>If <code>totalLength</code> is not provided, it is calculated from the <code>Buffer</code> instances
in <code>list</code> by adding their lengths.</p>
<p>If <code>totalLength</code> is provided, it is coerced to an unsigned integer. If the
combined length of the <code>Buffer</code>s in <code>list</code> exceeds <code>totalLength</code>, the result is
truncated to <code>totalLength</code>. If the combined length of the <code>Buffer</code>s in <code>list</code> is
less than <code>totalLength</code>, the remaining space is filled with zeros.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Create a single `Buffer` from a list of three `Buffer` instances.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">14</span>);
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">18</span>);
<span class="hljs-keyword">const</span> totalLength = buf1.<span class="hljs-property">length</span> + buf2.<span class="hljs-property">length</span> + buf3.<span class="hljs-property">length</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(totalLength);
<span class="hljs-comment">// Prints: 42</span>
<span class="hljs-keyword">const</span> bufA = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">concat</span>([buf1, buf2, buf3], totalLength);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(bufA);
<span class="hljs-comment">// Prints: <Buffer 00 00 00 00 ...></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(bufA.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 42</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Create a single `Buffer` from a list of three `Buffer` instances.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">14</span>);
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">18</span>);
<span class="hljs-keyword">const</span> totalLength = buf1.<span class="hljs-property">length</span> + buf2.<span class="hljs-property">length</span> + buf3.<span class="hljs-property">length</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(totalLength);
<span class="hljs-comment">// Prints: 42</span>
<span class="hljs-keyword">const</span> bufA = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">concat</span>([buf1, buf2, buf3], totalLength);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(bufA);
<span class="hljs-comment">// Prints: <Buffer 00 00 00 00 ...></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(bufA.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 42</span></code><button class="copy-button">copy</button></pre>
<p><code>Buffer.concat()</code> may also use the internal <code>Buffer</code> pool like
<a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> does.</p>
<h4>Static method: <code>Buffer.copyBytesFrom(view[, offset[, length]])</code><span><a class="mark" href="#all_buffer_static-method-buffercopybytesfromview-offset-length" id="all_buffer_static-method-buffercopybytesfromview-offset-length">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_copybytesfrom_view_offset_length"></a></h4>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<ul>
<li><code>view</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> to copy.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The starting offset within <code>view</code>. <strong>Default:</strong>: <code>0</code>.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of elements from <code>view</code> to copy.
<strong>Default:</strong> <code>view.length - offset</code>.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Copies the underlying memory of <code>view</code> into a new <code>Buffer</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> u16 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>([<span class="hljs-number">0</span>, <span class="hljs-number">0xffff</span>]);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">copyBytesFrom</span>(u16, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
u16[<span class="hljs-number">1</span>] = <span class="hljs-number">0</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>); <span class="hljs-comment">// 2</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf[<span class="hljs-number">0</span>]); <span class="hljs-comment">// 255</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf[<span class="hljs-number">1</span>]); <span class="hljs-comment">// 255</span></code> <button class="copy-button">copy</button></pre>
<h4>Static method: <code>Buffer.from(array)</code><span><a class="mark" href="#all_buffer_static-method-bufferfromarray" id="all_buffer_static-method-bufferfromarray">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_from_array"></a></h4>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li><code>array</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a></li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Allocates a new <code>Buffer</code> using an <code>array</code> of bytes in the range <code>0</code> – <code>255</code>.
Array entries outside that range will be truncated to fit into it.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x62</span>, <span class="hljs-number">0x75</span>, <span class="hljs-number">0x66</span>, <span class="hljs-number">0x66</span>, <span class="hljs-number">0x65</span>, <span class="hljs-number">0x72</span>]);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x62</span>, <span class="hljs-number">0x75</span>, <span class="hljs-number">0x66</span>, <span class="hljs-number">0x66</span>, <span class="hljs-number">0x65</span>, <span class="hljs-number">0x72</span>]);</code><button class="copy-button">copy</button></pre>
<p>If <code>array</code> is an <code>Array</code>-like object (that is, one with a <code>length</code> property of
type <code>number</code>), it is treated as if it is an array, unless it is a <code>Buffer</code> or
a <code>Uint8Array</code>. This means all other <code>TypedArray</code> variants get treated as an
<code>Array</code>. To create a <code>Buffer</code> from the bytes backing a <code>TypedArray</code>, use
<a href="#all_buffer_static-method-buffercopybytesfromview-offset-length"><code>Buffer.copyBytesFrom()</code></a>.</p>
<p>A <code>TypeError</code> will be thrown if <code>array</code> is not an <code>Array</code> or another type
appropriate for <code>Buffer.from()</code> variants.</p>
<p><code>Buffer.from(array)</code> and <a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string)</code></a> may also use the internal
<code>Buffer</code> pool like <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> does.</p>
<h4>Static method: <code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code><span><a class="mark" href="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length" id="all_buffer_static-method-bufferfromarraybuffer-byteoffset-length">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_from_arraybuffer_byteoffset_length"></a></h4>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li><code>arrayBuffer</code> <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/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> An <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a>, for example the <code>.buffer</code> property of a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>.</li>
<li><code>byteOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Index of first byte to expose. <strong>Default:</strong> <code>0</code>.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to expose.
<strong>Default:</strong> <code>arrayBuffer.byteLength - byteOffset</code>.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>This creates a view of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> without copying the underlying
memory. For example, when passed a reference to the <code>.buffer</code> property of a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instance, the newly created <code>Buffer</code> will share the same
allocated memory as the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>'s underlying <code>ArrayBuffer</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(<span class="hljs-number">2</span>);
arr[<span class="hljs-number">0</span>] = <span class="hljs-number">5000</span>;
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">4000</span>;
<span class="hljs-comment">// Shares memory with `arr`.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr.<span class="hljs-property">buffer</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 88 13 a0 0f></span>
<span class="hljs-comment">// Changing the original Uint16Array changes the Buffer also.</span>
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">6000</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 88 13 70 17></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(<span class="hljs-number">2</span>);
arr[<span class="hljs-number">0</span>] = <span class="hljs-number">5000</span>;
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">4000</span>;
<span class="hljs-comment">// Shares memory with `arr`.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr.<span class="hljs-property">buffer</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 88 13 a0 0f></span>
<span class="hljs-comment">// Changing the original Uint16Array changes the Buffer also.</span>
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">6000</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 88 13 70 17></span></code><button class="copy-button">copy</button></pre>
<p>The optional <code>byteOffset</code> and <code>length</code> arguments specify a memory range within
the <code>arrayBuffer</code> that will be shared by the <code>Buffer</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(ab, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 2</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(ab, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 2</span></code><button class="copy-button">copy</button></pre>
<p>A <code>TypeError</code> will be thrown if <code>arrayBuffer</code> is not an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> or a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> or another type appropriate for <code>Buffer.from()</code>
variants.</p>
<p>It is important to remember that a backing <code>ArrayBuffer</code> can cover a range
of memory that extends beyond the bounds of a <code>TypedArray</code> view. A new
<code>Buffer</code> created using the <code>buffer</code> property of a <code>TypedArray</code> may extend
beyond the range of the <code>TypedArray</code>:</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> arrA = <span class="hljs-title class_">Uint8Array</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x63</span>, <span class="hljs-number">0x64</span>, <span class="hljs-number">0x65</span>, <span class="hljs-number">0x66</span>]); <span class="hljs-comment">// 4 elements</span>
<span class="hljs-keyword">const</span> arrB = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(arrA.<span class="hljs-property">buffer</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 2 elements</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arrA.<span class="hljs-property">buffer</span> === arrB.<span class="hljs-property">buffer</span>); <span class="hljs-comment">// true</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arrB.<span class="hljs-property">buffer</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 63 64 65 66></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> arrA = <span class="hljs-title class_">Uint8Array</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x63</span>, <span class="hljs-number">0x64</span>, <span class="hljs-number">0x65</span>, <span class="hljs-number">0x66</span>]); <span class="hljs-comment">// 4 elements</span>
<span class="hljs-keyword">const</span> arrB = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(arrA.<span class="hljs-property">buffer</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 2 elements</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arrA.<span class="hljs-property">buffer</span> === arrB.<span class="hljs-property">buffer</span>); <span class="hljs-comment">// true</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arrB.<span class="hljs-property">buffer</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 63 64 65 66></span></code><button class="copy-button">copy</button></pre>
<h4>Static method: <code>Buffer.from(buffer)</code><span><a class="mark" href="#all_buffer_static-method-bufferfrombuffer" id="all_buffer_static-method-bufferfrombuffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_from_buffer"></a></h4>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> An existing <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> from
which to copy data.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Copies the passed <code>buffer</code> data onto a new <code>Buffer</code> instance.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf1);
buf1[<span class="hljs-number">0</span>] = <span class="hljs-number">0x61</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: auffer</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buffer</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf1);
buf1[<span class="hljs-number">0</span>] = <span class="hljs-number">0x61</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: auffer</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buffer</span></code><button class="copy-button">copy</button></pre>
<p>A <code>TypeError</code> will be thrown if <code>buffer</code> is not a <code>Buffer</code> or another type
appropriate for <code>Buffer.from()</code> variants.</p>
<h4>Static method: <code>Buffer.from(object[, offsetOrEncoding[, length]])</code><span><a class="mark" href="#all_buffer_static-method-bufferfromobject-offsetorencoding-length" id="all_buffer_static-method-bufferfromobject-offsetorencoding-length">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_from_object_offsetorencoding_length"></a></h4>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
</div>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object supporting <code>Symbol.toPrimitive</code> or <code>valueOf()</code>.</li>
<li><code>offsetOrEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A byte-offset or encoding.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> A length.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>For objects whose <code>valueOf()</code> function returns a value not strictly equal to
<code>object</code>, returns <code>Buffer.from(object.valueOf(), offsetOrEncoding, length)</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">'this is a test'</span>));
<span class="hljs-comment">// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">'this is a test'</span>));
<span class="hljs-comment">// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74></span></code><button class="copy-button">copy</button></pre>
<p>For objects that support <code>Symbol.toPrimitive</code>, returns
<code>Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding)</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
[<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">toPrimitive</span>]() {
<span class="hljs-keyword">return</span> <span class="hljs-string">'this is a test'</span>;
}
}
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>(), <span class="hljs-string">'utf8'</span>);
<span class="hljs-comment">// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
[<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">toPrimitive</span>]() {
<span class="hljs-keyword">return</span> <span class="hljs-string">'this is a test'</span>;
}
}
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>(), <span class="hljs-string">'utf8'</span>);
<span class="hljs-comment">// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74></span></code><button class="copy-button">copy</button></pre>
<p>A <code>TypeError</code> will be thrown if <code>object</code> does not have the mentioned methods or
is not of another type appropriate for <code>Buffer.from()</code> variants.</p>
<h4>Static method: <code>Buffer.from(string[, encoding])</code><span><a class="mark" href="#all_buffer_static-method-bufferfromstring-encoding" id="all_buffer_static-method-bufferfromstring-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_from_string_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string to encode.</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 of <code>string</code>. <strong>Default:</strong> <code>'utf8'</code>.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Creates a new <code>Buffer</code> containing <code>string</code>. The <code>encoding</code> parameter identifies
the character encoding to be used when converting <code>string</code> into bytes.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this is a tést'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'7468697320697320612074c3a97374'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: this is a tést</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: this is a tést</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'latin1'</span>));
<span class="hljs-comment">// Prints: this is a tést</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this is a tést'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'7468697320697320612074c3a97374'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: this is a tést</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: this is a tést</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'latin1'</span>));
<span class="hljs-comment">// Prints: this is a tést</span></code><button class="copy-button">copy</button></pre>
<p>A <code>TypeError</code> will be thrown if <code>string</code> is not a string or another type
appropriate for <code>Buffer.from()</code> variants.</p>
<p><a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string)</code></a> may also use the internal <code>Buffer</code> pool like
<a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> does.</p>
<h4>Static method: <code>Buffer.isBuffer(obj)</code><span><a class="mark" href="#all_buffer_static-method-bufferisbufferobj" id="all_buffer_static-method-bufferisbufferobj">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_isbuffer_obj"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.101</span>
</div>
<ul>
<li><code>obj</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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 <code>true</code> if <code>obj</code> is a <code>Buffer</code>, <code>false</code> otherwise.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-string">'a string'</span>); <span class="hljs-comment">// false</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>([]); <span class="hljs-comment">// false</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">1024</span>)); <span class="hljs-comment">// false</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-string">'a string'</span>); <span class="hljs-comment">// false</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>([]); <span class="hljs-comment">// false</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">1024</span>)); <span class="hljs-comment">// false</span></code><button class="copy-button">copy</button></pre>
<h4>Static method: <code>Buffer.isEncoding(encoding)</code><span><a class="mark" href="#all_buffer_static-method-bufferisencodingencoding" id="all_buffer_static-method-bufferisencodingencoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_isencoding_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</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> A character encoding name to check.</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 <code>true</code> if <code>encoding</code> is the name of a supported character encoding,
or <code>false</code> otherwise.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">'utf/8'</span>));
<span class="hljs-comment">// Prints: false</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">''</span>));
<span class="hljs-comment">// Prints: false</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">'utf/8'</span>));
<span class="hljs-comment">// Prints: false</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">''</span>));
<span class="hljs-comment">// Prints: false</span></code><button class="copy-button">copy</button></pre>
<h4>Class property: <code>Buffer.poolSize</code><span><a class="mark" href="#all_buffer_class-property-bufferpoolsize" id="all_buffer_class-property-bufferpoolsize">#</a></span><a aria-hidden="true" class="legacy" id="buffer_class_property_buffer_poolsize"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.3</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>8192</code></li>
</ul>
<p>This is the size (in bytes) of pre-allocated internal <code>Buffer</code> instances used
for pooling. This value may be modified.</p>
<h4><code>buf[index]</code><span><a class="mark" href="#all_buffer_bufindex" id="all_buffer_bufindex">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_index"></a></h4>
<ul>
<li><code>index</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>The index operator <code>[index]</code> can be used to get and set the octet at position
<code>index</code> in <code>buf</code>. The values refer to individual bytes, so the legal value
range is between <code>0x00</code> and <code>0xFF</code> (hex) or <code>0</code> and <code>255</code> (decimal).</p>
<p>This operator is inherited from <code>Uint8Array</code>, so its behavior on out-of-bounds
access is the same as <code>Uint8Array</code>. In other words, <code>buf[index]</code> returns
<code>undefined</code> when <code>index</code> is negative or greater or equal to <code>buf.length</code>, and
<code>buf[index] = value</code> does not modify the buffer if <code>index</code> is negative or
<code>>= buf.length</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Copy an ASCII string into a `Buffer` one byte at a time.</span>
<span class="hljs-comment">// (This only works for ASCII-only strings. In general, one should use</span>
<span class="hljs-comment">// `Buffer.from()` to perform this conversion.)</span>
<span class="hljs-keyword">const</span> str = <span class="hljs-string">'Node.js'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(str.<span class="hljs-property">length</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < str.<span class="hljs-property">length</span>; i++) {
buf[i] = str.<span class="hljs-title function_">charCodeAt</span>(i);
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: Node.js</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Copy an ASCII string into a `Buffer` one byte at a time.</span>
<span class="hljs-comment">// (This only works for ASCII-only strings. In general, one should use</span>
<span class="hljs-comment">// `Buffer.from()` to perform this conversion.)</span>
<span class="hljs-keyword">const</span> str = <span class="hljs-string">'Node.js'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(str.<span class="hljs-property">length</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < str.<span class="hljs-property">length</span>; i++) {
buf[i] = str.<span class="hljs-title function_">charCodeAt</span>(i);
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: Node.js</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.buffer</code><span><a class="mark" href="#all_buffer_bufbuffer" id="all_buffer_bufbuffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_buffer"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> The underlying <code>ArrayBuffer</code> object based on which this <code>Buffer</code>
object is created.</li>
</ul>
<p>This <code>ArrayBuffer</code> is not guaranteed to correspond exactly to the original
<code>Buffer</code>. See the notes on <code>buf.byteOffset</code> for details.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> arrayBuffer = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">16</span>);
<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arrayBuffer);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buffer.<span class="hljs-property">buffer</span> === arrayBuffer);
<span class="hljs-comment">// Prints: true</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> arrayBuffer = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">16</span>);
<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arrayBuffer);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buffer.<span class="hljs-property">buffer</span> === arrayBuffer);
<span class="hljs-comment">// Prints: true</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.byteOffset</code><span><a class="mark" href="#all_buffer_bufbyteoffset" id="all_buffer_bufbyteoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_byteoffset"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The <code>byteOffset</code> of the <code>Buffer</code>s underlying <code>ArrayBuffer</code> object.</li>
</ul>
<p>When setting <code>byteOffset</code> in <code>Buffer.from(ArrayBuffer, byteOffset, length)</code>,
or sometimes when allocating a <code>Buffer</code> smaller than <code>Buffer.poolSize</code>, the
buffer does not start from a zero offset on the underlying <code>ArrayBuffer</code>.</p>
<p>This can cause problems when accessing the underlying <code>ArrayBuffer</code> directly
using <code>buf.buffer</code>, as other parts of the <code>ArrayBuffer</code> may be unrelated
to the <code>Buffer</code> object itself.</p>
<p>A common issue when creating a <code>TypedArray</code> object that shares its memory with
a <code>Buffer</code> is that in this case one needs to specify the <code>byteOffset</code> correctly:</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Create a buffer smaller than `Buffer.poolSize`.</span>
<span class="hljs-keyword">const</span> nodeBuffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</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-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]);
<span class="hljs-comment">// When casting the Node.js Buffer to an Int8Array, use the byteOffset</span>
<span class="hljs-comment">// to refer only to the part of `nodeBuffer.buffer` that contains the memory</span>
<span class="hljs-comment">// for `nodeBuffer`.</span>
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Int8Array</span>(nodeBuffer.<span class="hljs-property">buffer</span>, nodeBuffer.<span class="hljs-property">byteOffset</span>, nodeBuffer.<span class="hljs-property">length</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Create a buffer smaller than `Buffer.poolSize`.</span>
<span class="hljs-keyword">const</span> nodeBuffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</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-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]);
<span class="hljs-comment">// When casting the Node.js Buffer to an Int8Array, use the byteOffset</span>
<span class="hljs-comment">// to refer only to the part of `nodeBuffer.buffer` that contains the memory</span>
<span class="hljs-comment">// for `nodeBuffer`.</span>
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Int8Array</span>(nodeBuffer.<span class="hljs-property">buffer</span>, nodeBuffer.<span class="hljs-property">byteOffset</span>, nodeBuffer.<span class="hljs-property">length</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])</code><span><a class="mark" href="#all_buffer_bufcomparetarget-targetstart-targetend-sourcestart-sourceend" id="all_buffer_bufcomparetarget-targetstart-targetend-sourcestart-sourceend">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>target</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v5.11.0</td>
<td><p>Additional parameters for specifying offsets are supported now.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>target</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> A <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> with which to
compare <code>buf</code>.</li>
<li><code>targetStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>target</code> at which to begin
comparison. <strong>Default:</strong> <code>0</code>.</li>
<li><code>targetEnd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>target</code> at which to end comparison
(not inclusive). <strong>Default:</strong> <code>target.length</code>.</li>
<li><code>sourceStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>buf</code> at which to begin comparison.
<strong>Default:</strong> <code>0</code>.</li>
<li><code>sourceEnd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>buf</code> at which to end comparison
(not inclusive). <strong>Default:</strong> <a href="#all_buffer_buflength"><code>buf.length</code></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>Compares <code>buf</code> with <code>target</code> and returns a number indicating whether <code>buf</code>
comes before, after, or is the same as <code>target</code> in sort order.
Comparison is based on the actual sequence of bytes in each <code>Buffer</code>.</p>
<ul>
<li><code>0</code> is returned if <code>target</code> is the same as <code>buf</code></li>
<li><code>1</code> is returned if <code>target</code> should come <em>before</em> <code>buf</code> when sorted.</li>
<li><code>-1</code> is returned if <code>target</code> should come <em>after</em> <code>buf</code> when sorted.</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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABC'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'BCD'</span>);
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABCD'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf1));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf3));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">compare</span>(buf1));
<span class="hljs-comment">// Prints: 1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">compare</span>(buf3));
<span class="hljs-comment">// Prints: 1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>([buf1, buf2, buf3].<span class="hljs-title function_">sort</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-property">compare</span>));
<span class="hljs-comment">// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]</span>
<span class="hljs-comment">// (This result is equal to: [buf1, buf3, buf2].)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABC'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'BCD'</span>);
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABCD'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf1));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf3));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">compare</span>(buf1));
<span class="hljs-comment">// Prints: 1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">compare</span>(buf3));
<span class="hljs-comment">// Prints: 1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>([buf1, buf2, buf3].<span class="hljs-title function_">sort</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-property">compare</span>));
<span class="hljs-comment">// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]</span>
<span class="hljs-comment">// (This result is equal to: [buf1, buf3, buf2].)</span></code><button class="copy-button">copy</button></pre>
<p>The optional <code>targetStart</code>, <code>targetEnd</code>, <code>sourceStart</code>, and <code>sourceEnd</code>
arguments can be used to limit the comparison to specific ranges within <code>target</code>
and <code>buf</code> respectively.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</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-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</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-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2, <span class="hljs-number">5</span>, <span class="hljs-number">9</span>, <span class="hljs-number">0</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">5</span>));
<span class="hljs-comment">// Prints: 1</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</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-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</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-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2, <span class="hljs-number">5</span>, <span class="hljs-number">9</span>, <span class="hljs-number">0</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">5</span>));
<span class="hljs-comment">// Prints: 1</span></code><button class="copy-button">copy</button></pre>
<p><a href="#all_errors_err_out_of_range"><code>ERR_OUT_OF_RANGE</code></a> is thrown if <code>targetStart < 0</code>, <code>sourceStart < 0</code>,
<code>targetEnd > target.byteLength</code>, or <code>sourceEnd > source.byteLength</code>.</p>
<h4><code>buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])</code><span><a class="mark" href="#all_buffer_bufcopytarget-targetstart-sourcestart-sourceend" id="all_buffer_bufcopytarget-targetstart-sourcestart-sourceend">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_copy_target_targetstart_sourcestart_sourceend"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>target</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> A <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> to copy into.</li>
<li><code>targetStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>target</code> at which to begin
writing. <strong>Default:</strong> <code>0</code>.</li>
<li><code>sourceStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>buf</code> from which to begin copying.
<strong>Default:</strong> <code>0</code>.</li>
<li><code>sourceEnd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>buf</code> at which to stop copying (not
inclusive). <strong>Default:</strong> <a href="#all_buffer_buflength"><code>buf.length</code></a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of bytes copied.</li>
</ul>
<p>Copies data from a region of <code>buf</code> to a region in <code>target</code>, even if the <code>target</code>
memory region overlaps with <code>buf</code>.</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set"><code>TypedArray.prototype.set()</code></a> performs the same operation, and is available
for all TypedArrays, including Node.js <code>Buffer</code>s, although it takes
different function arguments.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Create two `Buffer` instances.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">'!'</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">26</span>; i++) {
<span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
buf1[i] = i + <span class="hljs-number">97</span>;
}
<span class="hljs-comment">// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.</span>
buf1.<span class="hljs-title function_">copy</span>(buf2, <span class="hljs-number">8</span>, <span class="hljs-number">16</span>, <span class="hljs-number">20</span>);
<span class="hljs-comment">// This is equivalent to:</span>
<span class="hljs-comment">// buf2.set(buf1.subarray(16, 20), 8);</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">25</span>));
<span class="hljs-comment">// Prints: !!!!!!!!qrst!!!!!!!!!!!!!</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Create two `Buffer` instances.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">'!'</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">26</span>; i++) {
<span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
buf1[i] = i + <span class="hljs-number">97</span>;
}
<span class="hljs-comment">// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.</span>
buf1.<span class="hljs-title function_">copy</span>(buf2, <span class="hljs-number">8</span>, <span class="hljs-number">16</span>, <span class="hljs-number">20</span>);
<span class="hljs-comment">// This is equivalent to:</span>
<span class="hljs-comment">// buf2.set(buf1.subarray(16, 20), 8);</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">25</span>));
<span class="hljs-comment">// Prints: !!!!!!!!qrst!!!!!!!!!!!!!</span></code><button class="copy-button">copy</button></pre>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Create a `Buffer` and copy data from one region to an overlapping region</span>
<span class="hljs-comment">// within the same `Buffer`.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</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">26</span>; i++) {
<span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
buf[i] = i + <span class="hljs-number">97</span>;
}
buf.<span class="hljs-title function_">copy</span>(buf, <span class="hljs-number">0</span>, <span class="hljs-number">4</span>, <span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: efghijghijklmnopqrstuvwxyz</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Create a `Buffer` and copy data from one region to an overlapping region</span>
<span class="hljs-comment">// within the same `Buffer`.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</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">26</span>; i++) {
<span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
buf[i] = i + <span class="hljs-number">97</span>;
}
buf.<span class="hljs-title function_">copy</span>(buf, <span class="hljs-number">0</span>, <span class="hljs-number">4</span>, <span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: efghijghijklmnopqrstuvwxyz</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.entries()</code><span><a class="mark" href="#all_buffer_bufentries" id="all_buffer_bufentries">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_entries"></a></h4>
<div class="api_metadata">
<span>Added in: v1.1.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li>
</ul>
<p>Creates and returns an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterator</a> of <code>[index, byte]</code> pairs from the contents
of <code>buf</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Log the entire contents of a `Buffer`.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> pair <span class="hljs-keyword">of</span> buf.<span class="hljs-title function_">entries</span>()) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(pair);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// [0, 98]</span>
<span class="hljs-comment">// [1, 117]</span>
<span class="hljs-comment">// [2, 102]</span>
<span class="hljs-comment">// [3, 102]</span>
<span class="hljs-comment">// [4, 101]</span>
<span class="hljs-comment">// [5, 114]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Log the entire contents of a `Buffer`.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> pair <span class="hljs-keyword">of</span> buf.<span class="hljs-title function_">entries</span>()) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(pair);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// [0, 98]</span>
<span class="hljs-comment">// [1, 117]</span>
<span class="hljs-comment">// [2, 102]</span>
<span class="hljs-comment">// [3, 102]</span>
<span class="hljs-comment">// [4, 101]</span>
<span class="hljs-comment">// [5, 114]</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.equals(otherBuffer)</code><span><a class="mark" href="#all_buffer_bufequalsotherbuffer" id="all_buffer_bufequalsotherbuffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_equals_otherbuffer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The arguments can now be <code>Uint8Array</code>s.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>otherBuffer</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> A <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> with which to
compare <code>buf</code>.</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 <code>true</code> if both <code>buf</code> and <code>otherBuffer</code> have exactly the same bytes,
<code>false</code> otherwise. Equivalent to
<a href="#all_buffer_bufcomparetarget-targetstart-targetend-sourcestart-sourceend"><code>buf.compare(otherBuffer) === 0</code></a>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABC'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'414243'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABCD'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">equals</span>(buf2));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">equals</span>(buf3));
<span class="hljs-comment">// Prints: false</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABC'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'414243'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABCD'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">equals</span>(buf2));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">equals</span>(buf3));
<span class="hljs-comment">// Prints: false</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.fill(value[, offset[, end]][, encoding])</code><span><a class="mark" href="#all_buffer_buffillvalue-offset-end-encoding" id="all_buffer_buffillvalue-offset-end-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_fill_value_offset_end_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Throws <code>ERR_OUT_OF_RANGE</code> instead of <code>ERR_INDEX_OUT_OF_RANGE</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Negative <code>end</code> values throw an <code>ERR_INDEX_OUT_OF_RANGE</code> error.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Specifying an invalid string for <code>value</code> triggers a thrown exception.</p></td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>encoding</code> parameter is supported now.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The value with which to fill <code>buf</code>.
Empty value (string, Uint8Array, Buffer) is coerced to <code>0</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to fill <code>buf</code>.
<strong>Default:</strong> <code>0</code>.</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where to stop filling <code>buf</code> (not inclusive). <strong>Default:</strong>
<a href="#all_buffer_buflength"><code>buf.length</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> The encoding for <code>value</code> if <code>value</code> is a string.
<strong>Default:</strong> <code>'utf8'</code>.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> A reference to <code>buf</code>.</li>
</ul>
<p>Fills <code>buf</code> with the specified <code>value</code>. If the <code>offset</code> and <code>end</code> are not given,
the entire <code>buf</code> will be filled:</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Fill a `Buffer` with the ASCII character 'h'.</span>
<span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">50</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">'h'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh</span>
<span class="hljs-comment">// Fill a buffer with empty string</span>
<span class="hljs-keyword">const</span> c = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">5</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">''</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(c.<span class="hljs-title function_">fill</span>(<span class="hljs-string">''</span>));
<span class="hljs-comment">// Prints: <Buffer 00 00 00 00 00></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Fill a `Buffer` with the ASCII character 'h'.</span>
<span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">50</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">'h'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh</span>
<span class="hljs-comment">// Fill a buffer with empty string</span>
<span class="hljs-keyword">const</span> c = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">5</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">''</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(c.<span class="hljs-title function_">fill</span>(<span class="hljs-string">''</span>));
<span class="hljs-comment">// Prints: <Buffer 00 00 00 00 00></span></code><button class="copy-button">copy</button></pre>
<p><code>value</code> is coerced to a <code>uint32</code> value if it is not a string, <code>Buffer</code>, or
integer. If the resulting integer is greater than <code>255</code> (decimal), <code>buf</code> will be
filled with <code>value & 255</code>.</p>
<p>If the final write of a <code>fill()</code> operation falls on a multi-byte character,
then only the bytes of that character that fit into <code>buf</code> are written:</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Fill a `Buffer` with character that takes up two bytes in UTF-8.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">5</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">'\u0222'</span>));
<span class="hljs-comment">// Prints: <Buffer c8 a2 c8 a2 c8></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Fill a `Buffer` with character that takes up two bytes in UTF-8.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">5</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">'\u0222'</span>));
<span class="hljs-comment">// Prints: <Buffer c8 a2 c8 a2 c8></span></code><button class="copy-button">copy</button></pre>
<p>If <code>value</code> contains invalid characters, it is truncated; if no valid
fill data remains, an exception is thrown:</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">5</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">fill</span>(<span class="hljs-string">'a'</span>));
<span class="hljs-comment">// Prints: <Buffer 61 61 61 61 61></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">fill</span>(<span class="hljs-string">'aazz'</span>, <span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: <Buffer aa aa aa aa aa></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">fill</span>(<span class="hljs-string">'zz'</span>, <span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Throws an exception.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">5</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">fill</span>(<span class="hljs-string">'a'</span>));
<span class="hljs-comment">// Prints: <Buffer 61 61 61 61 61></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">fill</span>(<span class="hljs-string">'aazz'</span>, <span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: <Buffer aa aa aa aa aa></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">fill</span>(<span class="hljs-string">'zz'</span>, <span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Throws an exception.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.includes(value[, byteOffset][, encoding])</code><span><a class="mark" href="#all_buffer_bufincludesvalue-byteoffset-encoding" id="all_buffer_bufincludesvalue-byteoffset-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_includes_value_byteoffset_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v5.3.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> What to search for.</li>
<li><code>byteOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where to begin searching in <code>buf</code>. If negative, then
offset is calculated from the end of <code>buf</code>. <strong>Default:</strong> <code>0</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> If <code>value</code> is a string, this is its encoding.
<strong>Default:</strong> <code>'utf8'</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 <code>value</code> was found in <code>buf</code>, <code>false</code> otherwise.</li>
</ul>
<p>Equivalent to <a href="#all_buffer_bufindexofvalue-byteoffset-encoding"><code>buf.indexOf() !== -1</code></a>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this is a buffer'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'this'</span>));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'is'</span>));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer'</span>)));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-number">97</span>));
<span class="hljs-comment">// Prints: true (97 is the decimal ASCII value for 'a')</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>)));
<span class="hljs-comment">// Prints: false</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>).<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">8</span>)));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'this'</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: false</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this is a buffer'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'this'</span>));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'is'</span>));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer'</span>)));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-number">97</span>));
<span class="hljs-comment">// Prints: true (97 is the decimal ASCII value for 'a')</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>)));
<span class="hljs-comment">// Prints: false</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>).<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">8</span>)));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'this'</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: false</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.indexOf(value[, byteOffset][, encoding])</code><span><a class="mark" href="#all_buffer_bufindexofvalue-byteoffset-encoding" id="all_buffer_bufindexofvalue-byteoffset-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_indexof_value_byteoffset_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>value</code> can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v5.7.0, v4.4.0</td>
<td><p>When <code>encoding</code> is being passed, the <code>byteOffset</code> parameter is no longer required.</p></td></tr>
<tr><td>v1.5.0</td>
<td><p><span>Added in: v1.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> What to search for.</li>
<li><code>byteOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where to begin searching in <code>buf</code>. If negative, then
offset is calculated from the end of <code>buf</code>. <strong>Default:</strong> <code>0</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> If <code>value</code> is a string, this is the encoding used to
determine the binary representation of the string that will be searched for in
<code>buf</code>. <strong>Default:</strong> <code>'utf8'</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The index of the first occurrence of <code>value</code> in <code>buf</code>, or
<code>-1</code> if <code>buf</code> does not contain <code>value</code>.</li>
</ul>
<p>If <code>value</code> is:</p>
<ul>
<li>a string, <code>value</code> is interpreted according to the character encoding in
<code>encoding</code>.</li>
<li>a <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>, <code>value</code> will be used in its entirety.
To compare a partial <code>Buffer</code>, use <a href="#all_buffer_bufsubarraystart-end"><code>buf.subarray</code></a>.</li>
<li>a number, <code>value</code> will be interpreted as an unsigned 8-bit integer
value between <code>0</code> and <code>255</code>.</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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this is a buffer'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'this'</span>));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'is'</span>));
<span class="hljs-comment">// Prints: 2</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer'</span>)));
<span class="hljs-comment">// Prints: 8</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-number">97</span>));
<span class="hljs-comment">// Prints: 8 (97 is the decimal ASCII value for 'a')</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>)));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>).<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">8</span>)));
<span class="hljs-comment">// Prints: 8</span>
<span class="hljs-keyword">const</span> utf16Buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'\u039a\u0391\u03a3\u03a3\u0395'</span>, <span class="hljs-string">'utf16le'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'\u03a3'</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 4</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'\u03a3'</span>, -<span class="hljs-number">4</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 6</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this is a buffer'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'this'</span>));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'is'</span>));
<span class="hljs-comment">// Prints: 2</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer'</span>)));
<span class="hljs-comment">// Prints: 8</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-number">97</span>));
<span class="hljs-comment">// Prints: 8 (97 is the decimal ASCII value for 'a')</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>)));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>).<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">8</span>)));
<span class="hljs-comment">// Prints: 8</span>
<span class="hljs-keyword">const</span> utf16Buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'\u039a\u0391\u03a3\u03a3\u0395'</span>, <span class="hljs-string">'utf16le'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'\u03a3'</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 4</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'\u03a3'</span>, -<span class="hljs-number">4</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 6</span></code><button class="copy-button">copy</button></pre>
<p>If <code>value</code> is not a string, number, or <code>Buffer</code>, this method will throw a
<code>TypeError</code>. If <code>value</code> is a number, it will be coerced to a valid byte value,
an integer between 0 and 255.</p>
<p>If <code>byteOffset</code> is not a number, it will be coerced to a number. If the result
of coercion is <code>NaN</code> or <code>0</code>, then the entire buffer will be searched. This
behavior matches <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf"><code>String.prototype.indexOf()</code></a>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'abcdef'</span>);
<span class="hljs-comment">// Passing a value that's a number, but not a valid byte.</span>
<span class="hljs-comment">// Prints: 2, equivalent to searching for 99 or 'c'.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-number">99.9</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-number">256</span> + <span class="hljs-number">99</span>));
<span class="hljs-comment">// Passing a byteOffset that coerces to NaN or 0.</span>
<span class="hljs-comment">// Prints: 1, searching the whole buffer.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">undefined</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, {}));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">null</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, []));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'abcdef'</span>);
<span class="hljs-comment">// Passing a value that's a number, but not a valid byte.</span>
<span class="hljs-comment">// Prints: 2, equivalent to searching for 99 or 'c'.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-number">99.9</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-number">256</span> + <span class="hljs-number">99</span>));
<span class="hljs-comment">// Passing a byteOffset that coerces to NaN or 0.</span>
<span class="hljs-comment">// Prints: 1, searching the whole buffer.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">undefined</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, {}));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">null</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, []));</code><button class="copy-button">copy</button></pre>
<p>If <code>value</code> is an empty string or empty <code>Buffer</code> and <code>byteOffset</code> is less
than <code>buf.length</code>, <code>byteOffset</code> will be returned. If <code>value</code> is empty and
<code>byteOffset</code> is at least <code>buf.length</code>, <code>buf.length</code> will be returned.</p>
<h4><code>buf.keys()</code><span><a class="mark" href="#all_buffer_bufkeys" id="all_buffer_bufkeys">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_keys"></a></h4>
<div class="api_metadata">
<span>Added in: v1.1.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li>
</ul>
<p>Creates and returns an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterator</a> of <code>buf</code> keys (indexes).</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">of</span> buf.<span class="hljs-title function_">keys</span>()) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 0</span>
<span class="hljs-comment">// 1</span>
<span class="hljs-comment">// 2</span>
<span class="hljs-comment">// 3</span>
<span class="hljs-comment">// 4</span>
<span class="hljs-comment">// 5</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">of</span> buf.<span class="hljs-title function_">keys</span>()) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 0</span>
<span class="hljs-comment">// 1</span>
<span class="hljs-comment">// 2</span>
<span class="hljs-comment">// 3</span>
<span class="hljs-comment">// 4</span>
<span class="hljs-comment">// 5</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.lastIndexOf(value[, byteOffset][, encoding])</code><span><a class="mark" href="#all_buffer_buflastindexofvalue-byteoffset-encoding" id="all_buffer_buflastindexofvalue-byteoffset-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_lastindexof_value_byteoffset_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>value</code> can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Added in: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> What to search for.</li>
<li><code>byteOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where to begin searching in <code>buf</code>. If negative, then
offset is calculated from the end of <code>buf</code>. <strong>Default:</strong>
<code>buf.length - 1</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> If <code>value</code> is a string, this is the encoding used to
determine the binary representation of the string that will be searched for in
<code>buf</code>. <strong>Default:</strong> <code>'utf8'</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The index of the last occurrence of <code>value</code> in <code>buf</code>, or
<code>-1</code> if <code>buf</code> does not contain <code>value</code>.</li>
</ul>
<p>Identical to <a href="#all_buffer_bufindexofvalue-byteoffset-encoding"><code>buf.indexOf()</code></a>, except the last occurrence of <code>value</code> is found
rather than the first occurrence.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this buffer is a buffer'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'this'</span>));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'buffer'</span>));
<span class="hljs-comment">// Prints: 17</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>)));
<span class="hljs-comment">// Prints: 17</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-number">97</span>));
<span class="hljs-comment">// Prints: 15 (97 is the decimal ASCII value for 'a')</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'yolo'</span>)));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'buffer'</span>, <span class="hljs-number">5</span>));
<span class="hljs-comment">// Prints: 5</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'buffer'</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-keyword">const</span> utf16Buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'\u039a\u0391\u03a3\u03a3\u0395'</span>, <span class="hljs-string">'utf16le'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'\u03a3'</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 6</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'\u03a3'</span>, -<span class="hljs-number">5</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 4</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this buffer is a buffer'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'this'</span>));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'buffer'</span>));
<span class="hljs-comment">// Prints: 17</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>)));
<span class="hljs-comment">// Prints: 17</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-number">97</span>));
<span class="hljs-comment">// Prints: 15 (97 is the decimal ASCII value for 'a')</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'yolo'</span>)));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'buffer'</span>, <span class="hljs-number">5</span>));
<span class="hljs-comment">// Prints: 5</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'buffer'</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-keyword">const</span> utf16Buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'\u039a\u0391\u03a3\u03a3\u0395'</span>, <span class="hljs-string">'utf16le'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'\u03a3'</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 6</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'\u03a3'</span>, -<span class="hljs-number">5</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 4</span></code><button class="copy-button">copy</button></pre>
<p>If <code>value</code> is not a string, number, or <code>Buffer</code>, this method will throw a
<code>TypeError</code>. If <code>value</code> is a number, it will be coerced to a valid byte value,
an integer between 0 and 255.</p>
<p>If <code>byteOffset</code> is not a number, it will be coerced to a number. Any arguments
that coerce to <code>NaN</code>, like <code>{}</code> or <code>undefined</code>, will search the whole buffer.
This behavior matches <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf"><code>String.prototype.lastIndexOf()</code></a>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'abcdef'</span>);
<span class="hljs-comment">// Passing a value that's a number, but not a valid byte.</span>
<span class="hljs-comment">// Prints: 2, equivalent to searching for 99 or 'c'.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-number">99.9</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-number">256</span> + <span class="hljs-number">99</span>));
<span class="hljs-comment">// Passing a byteOffset that coerces to NaN.</span>
<span class="hljs-comment">// Prints: 1, searching the whole buffer.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">undefined</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, {}));
<span class="hljs-comment">// Passing a byteOffset that coerces to 0.</span>
<span class="hljs-comment">// Prints: -1, equivalent to passing 0.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">null</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, []));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'abcdef'</span>);
<span class="hljs-comment">// Passing a value that's a number, but not a valid byte.</span>
<span class="hljs-comment">// Prints: 2, equivalent to searching for 99 or 'c'.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-number">99.9</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-number">256</span> + <span class="hljs-number">99</span>));
<span class="hljs-comment">// Passing a byteOffset that coerces to NaN.</span>
<span class="hljs-comment">// Prints: 1, searching the whole buffer.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">undefined</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, {}));
<span class="hljs-comment">// Passing a byteOffset that coerces to 0.</span>
<span class="hljs-comment">// Prints: -1, equivalent to passing 0.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">null</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, []));</code><button class="copy-button">copy</button></pre>
<p>If <code>value</code> is an empty string or empty <code>Buffer</code>, <code>byteOffset</code> will be returned.</p>
<h4><code>buf.length</code><span><a class="mark" href="#all_buffer_buflength" id="all_buffer_buflength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_length"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</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>Returns the number of bytes in <code>buf</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Create a `Buffer` and write a shorter string to it using UTF-8.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">1234</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 1234</span>
buf.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some string'</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'utf8'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 1234</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Create a `Buffer` and write a shorter string to it using UTF-8.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">1234</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 1234</span>
buf.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some string'</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'utf8'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 1234</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.parent</code><span><a class="mark" href="#all_buffer_bufparent" id="all_buffer_bufparent">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_parent"></a></h4>
<div class="api_metadata">
<span>Deprecated since: v8.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_bufbuffer"><code>buf.buffer</code></a> instead.</div><p></p>
<p>The <code>buf.parent</code> property is a deprecated alias for <code>buf.buffer</code>.</p>
<h4><code>buf.readBigInt64BE([offset])</code><span><a class="mark" href="#all_buffer_bufreadbigint64beoffset" id="all_buffer_bufreadbigint64beoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readbigint64be_offset"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.0</span>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy: <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Reads a signed, big-endian 64-bit integer from <code>buf</code> at the specified <code>offset</code>.</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed
values.</p>
<h4><code>buf.readBigInt64LE([offset])</code><span><a class="mark" href="#all_buffer_bufreadbigint64leoffset" id="all_buffer_bufreadbigint64leoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readbigint64le_offset"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.0</span>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy: <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Reads a signed, little-endian 64-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed
values.</p>
<h4><code>buf.readBigUInt64BE([offset])</code><span><a class="mark" href="#all_buffer_bufreadbiguint64beoffset" id="all_buffer_bufreadbiguint64beoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readbiguint64be_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readBigUint64BE()</code>.</p></td></tr>
<tr><td>v12.0.0, v10.20.0</td>
<td><p><span>Added in: v12.0.0, v10.20.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy: <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Reads an unsigned, big-endian 64-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>This function is also available under the <code>readBigUint64BE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readBigUInt64BE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 4294967295n</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readBigUInt64BE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 4294967295n</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readBigUInt64LE([offset])</code><span><a class="mark" href="#all_buffer_bufreadbiguint64leoffset" id="all_buffer_bufreadbiguint64leoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readbiguint64le_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readBigUint64LE()</code>.</p></td></tr>
<tr><td>v12.0.0, v10.20.0</td>
<td><p><span>Added in: v12.0.0, v10.20.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy: <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Reads an unsigned, little-endian 64-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>This function is also available under the <code>readBigUint64LE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readBigUInt64LE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 18446744069414584320n</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readBigUInt64LE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 18446744069414584320n</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readDoubleBE([offset])</code><span><a class="mark" href="#all_buffer_bufreaddoublebeoffset" id="all_buffer_bufreaddoublebeoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readdoublebe_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Reads a 64-bit, big-endian double from <code>buf</code> at the specified <code>offset</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</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-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readDoubleBE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 8.20788039913184e-304</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</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-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readDoubleBE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 8.20788039913184e-304</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readDoubleLE([offset])</code><span><a class="mark" href="#all_buffer_bufreaddoubleleoffset" id="all_buffer_bufreaddoubleleoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readdoublele_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Reads a 64-bit, little-endian double from <code>buf</code> at the specified <code>offset</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</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-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readDoubleLE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 5.447603722011605e-270</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readDoubleLE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</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-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readDoubleLE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 5.447603722011605e-270</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readDoubleLE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readFloatBE([offset])</code><span><a class="mark" href="#all_buffer_bufreadfloatbeoffset" id="all_buffer_bufreadfloatbeoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readfloatbe_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Reads a 32-bit, big-endian float from <code>buf</code> at the specified <code>offset</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</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-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readFloatBE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 2.387939260590663e-38</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</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-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readFloatBE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 2.387939260590663e-38</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readFloatLE([offset])</code><span><a class="mark" href="#all_buffer_bufreadfloatleoffset" id="all_buffer_bufreadfloatleoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readfloatle_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Reads a 32-bit, little-endian float from <code>buf</code> at the specified <code>offset</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</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-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readFloatLE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 1.539989614439558e-36</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readFloatLE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</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-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readFloatLE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 1.539989614439558e-36</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readFloatLE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readInt8([offset])</code><span><a class="mark" href="#all_buffer_bufreadint8offset" id="all_buffer_bufreadint8offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readint8_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 1</code>. <strong>Default:</strong> <code>0</code>.</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>Reads a signed 8-bit integer from <code>buf</code> at the specified <code>offset</code>.</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([-<span class="hljs-number">1</span>, <span class="hljs-number">5</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt8</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt8</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Prints: 5</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt8</span>(<span class="hljs-number">2</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([-<span class="hljs-number">1</span>, <span class="hljs-number">5</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt8</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt8</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Prints: 5</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt8</span>(<span class="hljs-number">2</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readInt16BE([offset])</code><span><a class="mark" href="#all_buffer_bufreadint16beoffset" id="all_buffer_bufreadint16beoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readint16be_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 2</code>. <strong>Default:</strong> <code>0</code>.</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>Reads a signed, big-endian 16-bit integer from <code>buf</code> at the specified <code>offset</code>.</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt16BE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 5</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt16BE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 5</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readInt16LE([offset])</code><span><a class="mark" href="#all_buffer_bufreadint16leoffset" id="all_buffer_bufreadint16leoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readint16le_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 2</code>. <strong>Default:</strong> <code>0</code>.</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>Reads a signed, little-endian 16-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt16LE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 1280</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt16LE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt16LE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 1280</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt16LE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readInt32BE([offset])</code><span><a class="mark" href="#all_buffer_bufreadint32beoffset" id="all_buffer_bufreadint32beoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readint32be_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</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>Reads a signed, big-endian 32-bit integer from <code>buf</code> at the specified <code>offset</code>.</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt32BE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 5</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt32BE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 5</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readInt32LE([offset])</code><span><a class="mark" href="#all_buffer_bufreadint32leoffset" id="all_buffer_bufreadint32leoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readint32le_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</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>Reads a signed, little-endian 32-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt32LE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 83886080</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt32LE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt32LE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 83886080</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt32LE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readIntBE(offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufreadintbeoffset-bytelength" id="all_buffer_bufreadintbeoffset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readintbe_offset_bytelength"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - byteLength</code>.</li>
<li><code>byteLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to read. Must satisfy
<code>0 < byteLength <= 6</code>.</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>Reads <code>byteLength</code> number of bytes from <code>buf</code> at the specified <code>offset</code>
and interprets the result as a big-endian, two's complement signed value
supporting up to 48 bits of accuracy.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntBE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 1234567890ab</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntBE</span>(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntBE</span>(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntBE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 1234567890ab</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntBE</span>(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntBE</span>(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readIntLE(offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufreadintleoffset-bytelength" id="all_buffer_bufreadintleoffset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readintle_offset_bytelength"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - byteLength</code>.</li>
<li><code>byteLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to read. Must satisfy
<code>0 < byteLength <= 6</code>.</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>Reads <code>byteLength</code> number of bytes from <code>buf</code> at the specified <code>offset</code>
and interprets the result as a little-endian, two's complement signed value
supporting up to 48 bits of accuracy.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntLE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: -546f87a9cbee</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntLE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: -546f87a9cbee</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUInt8([offset])</code><span><a class="mark" href="#all_buffer_bufreaduint8offset" id="all_buffer_bufreaduint8offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuint8_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUint8()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 1</code>. <strong>Default:</strong> <code>0</code>.</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>Reads an unsigned 8-bit integer from <code>buf</code> at the specified <code>offset</code>.</p>
<p>This function is also available under the <code>readUint8</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, -<span class="hljs-number">2</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt8</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt8</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Prints: 254</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt8</span>(<span class="hljs-number">2</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, -<span class="hljs-number">2</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt8</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt8</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Prints: 254</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt8</span>(<span class="hljs-number">2</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUInt16BE([offset])</code><span><a class="mark" href="#all_buffer_bufreaduint16beoffset" id="all_buffer_bufreaduint16beoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuint16be_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUint16BE()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 2</code>. <strong>Default:</strong> <code>0</code>.</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>Reads an unsigned, big-endian 16-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>This function is also available under the <code>readUint16BE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16BE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 1234</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16BE</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 3456</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16BE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 1234</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16BE</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 3456</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUInt16LE([offset])</code><span><a class="mark" href="#all_buffer_bufreaduint16leoffset" id="all_buffer_bufreaduint16leoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuint16le_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUint16LE()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 2</code>. <strong>Default:</strong> <code>0</code>.</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>Reads an unsigned, little-endian 16-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>This function is also available under the <code>readUint16LE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16LE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 3412</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16LE</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 5634</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16LE</span>(<span class="hljs-number">2</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16LE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 3412</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16LE</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 5634</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16LE</span>(<span class="hljs-number">2</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUInt32BE([offset])</code><span><a class="mark" href="#all_buffer_bufreaduint32beoffset" id="all_buffer_bufreaduint32beoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuint32be_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUint32BE()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</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>Reads an unsigned, big-endian 32-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>This function is also available under the <code>readUint32BE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt32BE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 12345678</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt32BE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 12345678</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUInt32LE([offset])</code><span><a class="mark" href="#all_buffer_bufreaduint32leoffset" id="all_buffer_bufreaduint32leoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuint32le_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUint32LE()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</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>Reads an unsigned, little-endian 32-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>This function is also available under the <code>readUint32LE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt32LE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 78563412</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt32LE</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt32LE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 78563412</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt32LE</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUIntBE(offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufreaduintbeoffset-bytelength" id="all_buffer_bufreaduintbeoffset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuintbe_offset_bytelength"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUintBE()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - byteLength</code>.</li>
<li><code>byteLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to read. Must satisfy
<code>0 < byteLength <= 6</code>.</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>Reads <code>byteLength</code> number of bytes from <code>buf</code> at the specified <code>offset</code>
and interprets the result as an unsigned big-endian integer supporting
up to 48 bits of accuracy.</p>
<p>This function is also available under the <code>readUintBE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUIntBE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 1234567890ab</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUIntBE</span>(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUIntBE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 1234567890ab</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUIntBE</span>(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUIntLE(offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufreaduintleoffset-bytelength" id="all_buffer_bufreaduintleoffset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuintle_offset_bytelength"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUintLE()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 <= offset <= buf.length - byteLength</code>.</li>
<li><code>byteLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to read. Must satisfy
<code>0 < byteLength <= 6</code>.</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>Reads <code>byteLength</code> number of bytes from <code>buf</code> at the specified <code>offset</code>
and interprets the result as an unsigned, little-endian integer supporting
up to 48 bits of accuracy.</p>
<p>This function is also available under the <code>readUintLE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUIntLE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: ab9078563412</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUIntLE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: ab9078563412</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.subarray([start[, end]])</code><span><a class="mark" href="#all_buffer_bufsubarraystart-end" id="all_buffer_bufsubarraystart-end">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_subarray_start_end"></a></h4>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where the new <code>Buffer</code> will start. <strong>Default:</strong> <code>0</code>.</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where the new <code>Buffer</code> will end (not inclusive).
<strong>Default:</strong> <a href="#all_buffer_buflength"><code>buf.length</code></a>.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Returns a new <code>Buffer</code> that references the same memory as the original, but
offset and cropped by the <code>start</code> and <code>end</code> indexes.</p>
<p>Specifying <code>end</code> greater than <a href="#all_buffer_buflength"><code>buf.length</code></a> will return the same result as
that of <code>end</code> equal to <a href="#all_buffer_buflength"><code>buf.length</code></a>.</p>
<p>This method is inherited from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray"><code>TypedArray.prototype.subarray()</code></a>.</p>
<p>Modifying the new <code>Buffer</code> slice will modify the memory in the original <code>Buffer</code>
because the allocated memory of the two objects overlap.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte</span>
<span class="hljs-comment">// from the original `Buffer`.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</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">26</span>; i++) {
<span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
buf1[i] = i + <span class="hljs-number">97</span>;
}
<span class="hljs-keyword">const</span> buf2 = buf1.<span class="hljs-title function_">subarray</span>(<span class="hljs-number">0</span>, <span class="hljs-number">3</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>, <span class="hljs-number">0</span>, buf2.<span class="hljs-property">length</span>));
<span class="hljs-comment">// Prints: abc</span>
buf1[<span class="hljs-number">0</span>] = <span class="hljs-number">33</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>, <span class="hljs-number">0</span>, buf2.<span class="hljs-property">length</span>));
<span class="hljs-comment">// Prints: !bc</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte</span>
<span class="hljs-comment">// from the original `Buffer`.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</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">26</span>; i++) {
<span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
buf1[i] = i + <span class="hljs-number">97</span>;
}
<span class="hljs-keyword">const</span> buf2 = buf1.<span class="hljs-title function_">subarray</span>(<span class="hljs-number">0</span>, <span class="hljs-number">3</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>, <span class="hljs-number">0</span>, buf2.<span class="hljs-property">length</span>));
<span class="hljs-comment">// Prints: abc</span>
buf1[<span class="hljs-number">0</span>] = <span class="hljs-number">33</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>, <span class="hljs-number">0</span>, buf2.<span class="hljs-property">length</span>));
<span class="hljs-comment">// Prints: !bc</span></code><button class="copy-button">copy</button></pre>
<p>Specifying negative indexes causes the slice to be generated relative to the
end of <code>buf</code> rather than the beginning.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">subarray</span>(-<span class="hljs-number">6</span>, -<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buffe</span>
<span class="hljs-comment">// (Equivalent to buf.subarray(0, 5).)</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">subarray</span>(-<span class="hljs-number">6</span>, -<span class="hljs-number">2</span>).<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buff</span>
<span class="hljs-comment">// (Equivalent to buf.subarray(0, 4).)</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">subarray</span>(-<span class="hljs-number">5</span>, -<span class="hljs-number">2</span>).<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: uff</span>
<span class="hljs-comment">// (Equivalent to buf.subarray(1, 4).)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">subarray</span>(-<span class="hljs-number">6</span>, -<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buffe</span>
<span class="hljs-comment">// (Equivalent to buf.subarray(0, 5).)</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">subarray</span>(-<span class="hljs-number">6</span>, -<span class="hljs-number">2</span>).<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buff</span>
<span class="hljs-comment">// (Equivalent to buf.subarray(0, 4).)</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">subarray</span>(-<span class="hljs-number">5</span>, -<span class="hljs-number">2</span>).<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: uff</span>
<span class="hljs-comment">// (Equivalent to buf.subarray(1, 4).)</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.slice([start[, end]])</code><span><a class="mark" href="#all_buffer_bufslicestart-end" id="all_buffer_bufslicestart-end">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_slice_start_end"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>The buf.slice() method has been deprecated.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>All offsets are now coerced to integers before doing any calculations with them.</p></td></tr>
<tr><td>v7.1.0, v6.9.2</td>
<td><p>Coercing the offsets to integers now handles values outside the 32-bit integer range properly.</p></td></tr>
<tr><td>v0.3.0</td>
<td><p><span>Added in: v0.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where the new <code>Buffer</code> will start. <strong>Default:</strong> <code>0</code>.</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where the new <code>Buffer</code> will end (not inclusive).
<strong>Default:</strong> <a href="#all_buffer_buflength"><code>buf.length</code></a>.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_bufsubarraystart-end"><code>buf.subarray</code></a> instead.</div><p></p>
<p>Returns a new <code>Buffer</code> that references the same memory as the original, but
offset and cropped by the <code>start</code> and <code>end</code> indexes.</p>
<p>This method is not compatible with the <code>Uint8Array.prototype.slice()</code>,
which is a superclass of <code>Buffer</code>. To copy the slice, use
<code>Uint8Array.prototype.slice()</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-keyword">const</span> copiedBuf = <span class="hljs-title class_">Uint8Array</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">slice</span>.<span class="hljs-title function_">call</span>(buf);
copiedBuf[<span class="hljs-number">0</span>]++;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(copiedBuf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: cuffer</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buffer</span>
<span class="hljs-comment">// With buf.slice(), the original buffer is modified.</span>
<span class="hljs-keyword">const</span> notReallyCopiedBuf = buf.<span class="hljs-title function_">slice</span>();
notReallyCopiedBuf[<span class="hljs-number">0</span>]++;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(notReallyCopiedBuf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: cuffer</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Also prints: cuffer (!)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-keyword">const</span> copiedBuf = <span class="hljs-title class_">Uint8Array</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">slice</span>.<span class="hljs-title function_">call</span>(buf);
copiedBuf[<span class="hljs-number">0</span>]++;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(copiedBuf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: cuffer</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buffer</span>
<span class="hljs-comment">// With buf.slice(), the original buffer is modified.</span>
<span class="hljs-keyword">const</span> notReallyCopiedBuf = buf.<span class="hljs-title function_">slice</span>();
notReallyCopiedBuf[<span class="hljs-number">0</span>]++;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(notReallyCopiedBuf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: cuffer</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Also prints: cuffer (!)</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.swap16()</code><span><a class="mark" href="#all_buffer_bufswap16" id="all_buffer_bufswap16">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_swap16"></a></h4>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> A reference to <code>buf</code>.</li>
</ul>
<p>Interprets <code>buf</code> as an array of unsigned 16-bit integers and swaps the
byte order <em>in-place</em>. Throws <a href="#all_errors_err_invalid_buffer_size"><code>ERR_INVALID_BUFFER_SIZE</code></a> if <a href="#all_buffer_buflength"><code>buf.length</code></a>
is not a multiple of 2.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>, <span class="hljs-number">0x6</span>, <span class="hljs-number">0x7</span>, <span class="hljs-number">0x8</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 01 02 03 04 05 06 07 08></span>
buf1.<span class="hljs-title function_">swap16</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 02 01 04 03 06 05 08 07></span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>]);
buf2.<span class="hljs-title function_">swap16</span>();
<span class="hljs-comment">// Throws ERR_INVALID_BUFFER_SIZE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>, <span class="hljs-number">0x6</span>, <span class="hljs-number">0x7</span>, <span class="hljs-number">0x8</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 01 02 03 04 05 06 07 08></span>
buf1.<span class="hljs-title function_">swap16</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 02 01 04 03 06 05 08 07></span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>]);
buf2.<span class="hljs-title function_">swap16</span>();
<span class="hljs-comment">// Throws ERR_INVALID_BUFFER_SIZE.</span></code><button class="copy-button">copy</button></pre>
<p>One convenient use of <code>buf.swap16()</code> is to perform a fast in-place conversion
between UTF-16 little-endian and UTF-16 big-endian:</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'This is little-endian UTF-16'</span>, <span class="hljs-string">'utf16le'</span>);
buf.<span class="hljs-title function_">swap16</span>(); <span class="hljs-comment">// Convert to big-endian UTF-16 text.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'This is little-endian UTF-16'</span>, <span class="hljs-string">'utf16le'</span>);
buf.<span class="hljs-title function_">swap16</span>(); <span class="hljs-comment">// Convert to big-endian UTF-16 text.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.swap32()</code><span><a class="mark" href="#all_buffer_bufswap32" id="all_buffer_bufswap32">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_swap32"></a></h4>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> A reference to <code>buf</code>.</li>
</ul>
<p>Interprets <code>buf</code> as an array of unsigned 32-bit integers and swaps the
byte order <em>in-place</em>. Throws <a href="#all_errors_err_invalid_buffer_size"><code>ERR_INVALID_BUFFER_SIZE</code></a> if <a href="#all_buffer_buflength"><code>buf.length</code></a>
is not a multiple of 4.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>, <span class="hljs-number">0x6</span>, <span class="hljs-number">0x7</span>, <span class="hljs-number">0x8</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 01 02 03 04 05 06 07 08></span>
buf1.<span class="hljs-title function_">swap32</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 04 03 02 01 08 07 06 05></span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>]);
buf2.<span class="hljs-title function_">swap32</span>();
<span class="hljs-comment">// Throws ERR_INVALID_BUFFER_SIZE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>, <span class="hljs-number">0x6</span>, <span class="hljs-number">0x7</span>, <span class="hljs-number">0x8</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 01 02 03 04 05 06 07 08></span>
buf1.<span class="hljs-title function_">swap32</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 04 03 02 01 08 07 06 05></span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>]);
buf2.<span class="hljs-title function_">swap32</span>();
<span class="hljs-comment">// Throws ERR_INVALID_BUFFER_SIZE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.swap64()</code><span><a class="mark" href="#all_buffer_bufswap64" id="all_buffer_bufswap64">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_swap64"></a></h4>
<div class="api_metadata">
<span>Added in: v6.3.0</span>
</div>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> A reference to <code>buf</code>.</li>
</ul>
<p>Interprets <code>buf</code> as an array of 64-bit numbers and swaps byte order <em>in-place</em>.
Throws <a href="#all_errors_err_invalid_buffer_size"><code>ERR_INVALID_BUFFER_SIZE</code></a> if <a href="#all_buffer_buflength"><code>buf.length</code></a> is not a multiple of 8.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>, <span class="hljs-number">0x6</span>, <span class="hljs-number">0x7</span>, <span class="hljs-number">0x8</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 01 02 03 04 05 06 07 08></span>
buf1.<span class="hljs-title function_">swap64</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 08 07 06 05 04 03 02 01></span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>]);
buf2.<span class="hljs-title function_">swap64</span>();
<span class="hljs-comment">// Throws ERR_INVALID_BUFFER_SIZE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>, <span class="hljs-number">0x6</span>, <span class="hljs-number">0x7</span>, <span class="hljs-number">0x8</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 01 02 03 04 05 06 07 08></span>
buf1.<span class="hljs-title function_">swap64</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: <Buffer 08 07 06 05 04 03 02 01></span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>]);
buf2.<span class="hljs-title function_">swap64</span>();
<span class="hljs-comment">// Throws ERR_INVALID_BUFFER_SIZE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.toJSON()</code><span><a class="mark" href="#all_buffer_buftojson" id="all_buffer_buftojson">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_tojson"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.2</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns a JSON representation of <code>buf</code>. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify"><code>JSON.stringify()</code></a> implicitly calls
this function when stringifying a <code>Buffer</code> instance.</p>
<p><code>Buffer.from()</code> accepts objects in the format returned from this method.
In particular, <code>Buffer.from(buf.toJSON())</code> works like <code>Buffer.from(buf)</code>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>]);
<span class="hljs-keyword">const</span> json = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(buf);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(json);
<span class="hljs-comment">// Prints: {"type":"Buffer","data":[1,2,3,4,5]}</span>
<span class="hljs-keyword">const</span> copy = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(json, <span class="hljs-function">(<span class="hljs-params">key, value</span>) =></span> {
<span class="hljs-keyword">return</span> value && value.<span class="hljs-property">type</span> === <span class="hljs-string">'Buffer'</span> ?
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(value) :
value;
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(copy);
<span class="hljs-comment">// Prints: <Buffer 01 02 03 04 05></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>]);
<span class="hljs-keyword">const</span> json = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(buf);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(json);
<span class="hljs-comment">// Prints: {"type":"Buffer","data":[1,2,3,4,5]}</span>
<span class="hljs-keyword">const</span> copy = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(json, <span class="hljs-function">(<span class="hljs-params">key, value</span>) =></span> {
<span class="hljs-keyword">return</span> value && value.<span class="hljs-property">type</span> === <span class="hljs-string">'Buffer'</span> ?
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(value) :
value;
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(copy);
<span class="hljs-comment">// Prints: <Buffer 01 02 03 04 05></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.toString([encoding[, start[, end]]])</code><span><a class="mark" href="#all_buffer_buftostringencoding-start-end" id="all_buffer_buftostringencoding-start-end">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_tostring_encoding_start_end"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</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 character encoding to use. <strong>Default:</strong> <code>'utf8'</code>.</li>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The byte offset to start decoding at. <strong>Default:</strong> <code>0</code>.</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The byte offset to stop decoding at (not inclusive).
<strong>Default:</strong> <a href="#all_buffer_buflength"><code>buf.length</code></a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Decodes <code>buf</code> to a string according to the specified character encoding in
<code>encoding</code>. <code>start</code> and <code>end</code> may be passed to decode only a subset of <code>buf</code>.</p>
<p>If <code>encoding</code> is <code>'utf8'</code> and a byte sequence in the input is not valid UTF-8,
then each invalid byte is replaced with the replacement character <code>U+FFFD</code>.</p>
<p>The maximum length of a string instance (in UTF-16 code units) is available
as <a href="#all_buffer_bufferconstantsmax_string_length"><code>buffer.constants.MAX_STRING_LENGTH</code></a>.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</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">26</span>; i++) {
<span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
buf1[i] = i + <span class="hljs-number">97</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: abcdefghijklmnopqrstuvwxyz</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>));
<span class="hljs-comment">// Prints: abcde</span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'tést'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: 74c3a97374</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">3</span>));
<span class="hljs-comment">// Prints: té</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-literal">undefined</span>, <span class="hljs-number">0</span>, <span class="hljs-number">3</span>));
<span class="hljs-comment">// Prints: té</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</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">26</span>; i++) {
<span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
buf1[i] = i + <span class="hljs-number">97</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: abcdefghijklmnopqrstuvwxyz</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>));
<span class="hljs-comment">// Prints: abcde</span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'tést'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: 74c3a97374</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">3</span>));
<span class="hljs-comment">// Prints: té</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-literal">undefined</span>, <span class="hljs-number">0</span>, <span class="hljs-number">3</span>));
<span class="hljs-comment">// Prints: té</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.values()</code><span><a class="mark" href="#all_buffer_bufvalues" id="all_buffer_bufvalues">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_values"></a></h4>
<div class="api_metadata">
<span>Added in: v1.1.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li>
</ul>
<p>Creates and returns an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterator</a> for <code>buf</code> values (bytes). This function is
called automatically when a <code>Buffer</code> is used in a <code>for..of</code> statement.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> buf.<span class="hljs-title function_">values</span>()) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 98</span>
<span class="hljs-comment">// 117</span>
<span class="hljs-comment">// 102</span>
<span class="hljs-comment">// 102</span>
<span class="hljs-comment">// 101</span>
<span class="hljs-comment">// 114</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> buf) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 98</span>
<span class="hljs-comment">// 117</span>
<span class="hljs-comment">// 102</span>
<span class="hljs-comment">// 102</span>
<span class="hljs-comment">// 101</span>
<span class="hljs-comment">// 114</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> buf.<span class="hljs-title function_">values</span>()) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 98</span>
<span class="hljs-comment">// 117</span>
<span class="hljs-comment">// 102</span>
<span class="hljs-comment">// 102</span>
<span class="hljs-comment">// 101</span>
<span class="hljs-comment">// 114</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> buf) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 98</span>
<span class="hljs-comment">// 117</span>
<span class="hljs-comment">// 102</span>
<span class="hljs-comment">// 102</span>
<span class="hljs-comment">// 101</span>
<span class="hljs-comment">// 114</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.write(string[, offset[, length]][, encoding])</code><span><a class="mark" href="#all_buffer_bufwritestring-offset-length-encoding" id="all_buffer_bufwritestring-offset-length-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_write_string_offset_length_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> String to write to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write <code>string</code>.
<strong>Default:</strong> <code>0</code>.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Maximum number of bytes to write (written bytes will not
exceed <code>buf.length - offset</code>). <strong>Default:</strong> <code>buf.length - offset</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 <code>string</code>. <strong>Default:</strong> <code>'utf8'</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes written.</li>
</ul>
<p>Writes <code>string</code> to <code>buf</code> at <code>offset</code> according to the character encoding in
<code>encoding</code>. The <code>length</code> parameter is the number of bytes to write. If <code>buf</code> did
not contain enough space to fit the entire string, only part of <code>string</code> will be
written. However, partially encoded characters will not be written.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">256</span>);
<span class="hljs-keyword">const</span> len = buf.<span class="hljs-title function_">write</span>(<span class="hljs-string">'\u00bd + \u00bc = \u00be'</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${len}</span> bytes: <span class="hljs-subst">${buf.toString(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, len)}</span>`</span>);
<span class="hljs-comment">// Prints: 12 bytes: ½ + ¼ = ¾</span>
<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> length = buffer.<span class="hljs-title function_">write</span>(<span class="hljs-string">'abcd'</span>, <span class="hljs-number">8</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${length}</span> bytes: <span class="hljs-subst">${buffer.toString(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">8</span>, <span class="hljs-number">10</span>)}</span>`</span>);
<span class="hljs-comment">// Prints: 2 bytes : ab</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">256</span>);
<span class="hljs-keyword">const</span> len = buf.<span class="hljs-title function_">write</span>(<span class="hljs-string">'\u00bd + \u00bc = \u00be'</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${len}</span> bytes: <span class="hljs-subst">${buf.toString(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, len)}</span>`</span>);
<span class="hljs-comment">// Prints: 12 bytes: ½ + ¼ = ¾</span>
<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> length = buffer.<span class="hljs-title function_">write</span>(<span class="hljs-string">'abcd'</span>, <span class="hljs-number">8</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${length}</span> bytes: <span class="hljs-subst">${buffer.toString(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">8</span>, <span class="hljs-number">10</span>)}</span>`</span>);
<span class="hljs-comment">// Prints: 2 bytes : ab</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeBigInt64BE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritebigint64bevalue-offset" id="all_buffer_bufwritebigint64bevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writebigint64be_value_offset"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy: <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as big-endian.</p>
<p><code>value</code> is interpreted and written as a two's complement signed integer.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);
buf.<span class="hljs-title function_">writeBigInt64BE</span>(<span class="hljs-number">0x0102030405060708n</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 01 02 03 04 05 06 07 08></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);
buf.<span class="hljs-title function_">writeBigInt64BE</span>(<span class="hljs-number">0x0102030405060708n</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 01 02 03 04 05 06 07 08></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeBigInt64LE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritebigint64levalue-offset" id="all_buffer_bufwritebigint64levalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writebigint64le_value_offset"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy: <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as little-endian.</p>
<p><code>value</code> is interpreted and written as a two's complement signed integer.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);
buf.<span class="hljs-title function_">writeBigInt64LE</span>(<span class="hljs-number">0x0102030405060708n</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 08 07 06 05 04 03 02 01></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);
buf.<span class="hljs-title function_">writeBigInt64LE</span>(<span class="hljs-number">0x0102030405060708n</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 08 07 06 05 04 03 02 01></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeBigUInt64BE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritebiguint64bevalue-offset" id="all_buffer_bufwritebiguint64bevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writebiguint64be_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeBigUint64BE()</code>.</p></td></tr>
<tr><td>v12.0.0, v10.20.0</td>
<td><p><span>Added in: v12.0.0, v10.20.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy: <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as big-endian.</p>
<p>This function is also available under the <code>writeBigUint64BE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);
buf.<span class="hljs-title function_">writeBigUInt64BE</span>(<span class="hljs-number">0xdecafafecacefaden</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer de ca fa fe ca ce fa de></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);
buf.<span class="hljs-title function_">writeBigUInt64BE</span>(<span class="hljs-number">0xdecafafecacefaden</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer de ca fa fe ca ce fa de></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeBigUInt64LE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritebiguint64levalue-offset" id="all_buffer_bufwritebiguint64levalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writebiguint64le_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeBigUint64LE()</code>.</p></td></tr>
<tr><td>v12.0.0, v10.20.0</td>
<td><p><span>Added in: v12.0.0, v10.20.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy: <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as little-endian</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);
buf.<span class="hljs-title function_">writeBigUInt64LE</span>(<span class="hljs-number">0xdecafafecacefaden</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer de fa ce ca fe fa ca de></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);
buf.<span class="hljs-title function_">writeBigUInt64LE</span>(<span class="hljs-number">0xdecafafecacefaden</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer de fa ce ca fe fa ca de></span></code><button class="copy-button">copy</button></pre>
<p>This function is also available under the <code>writeBigUint64LE</code> alias.</p>
<h4><code>buf.writeDoubleBE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritedoublebevalue-offset" id="all_buffer_bufwritedoublebevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writedoublebe_value_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</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>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as big-endian. The <code>value</code>
must be a JavaScript number. Behavior is undefined when <code>value</code> is anything
other than a JavaScript number.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);
buf.<span class="hljs-title function_">writeDoubleBE</span>(<span class="hljs-number">123.456</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 40 5e dd 2f 1a 9f be 77></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);
buf.<span class="hljs-title function_">writeDoubleBE</span>(<span class="hljs-number">123.456</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 40 5e dd 2f 1a 9f be 77></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeDoubleLE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritedoublelevalue-offset" id="all_buffer_bufwritedoublelevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writedoublele_value_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</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>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as little-endian. The <code>value</code>
must be a JavaScript number. Behavior is undefined when <code>value</code> is anything
other than a JavaScript number.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);
buf.<span class="hljs-title function_">writeDoubleLE</span>(<span class="hljs-number">123.456</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);
buf.<span class="hljs-title function_">writeDoubleLE</span>(<span class="hljs-number">123.456</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeFloatBE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritefloatbevalue-offset" id="all_buffer_bufwritefloatbevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writefloatbe_value_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</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>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as big-endian. Behavior is
undefined when <code>value</code> is anything other than a JavaScript number.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeFloatBE</span>(<span class="hljs-number">0xcafebabe</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 4f 4a fe bb></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeFloatBE</span>(<span class="hljs-number">0xcafebabe</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 4f 4a fe bb></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeFloatLE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritefloatlevalue-offset" id="all_buffer_bufwritefloatlevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writefloatle_value_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</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>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as little-endian. Behavior is
undefined when <code>value</code> is anything other than a JavaScript number.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeFloatLE</span>(<span class="hljs-number">0xcafebabe</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer bb fe 4a 4f></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeFloatLE</span>(<span class="hljs-number">0xcafebabe</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer bb fe 4a 4f></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeInt8(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteint8value-offset" id="all_buffer_bufwriteint8value-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeint8_value_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 1</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code>. <code>value</code> must be a valid
signed 8-bit integer. Behavior is undefined when <code>value</code> is anything other than
a signed 8-bit integer.</p>
<p><code>value</code> is interpreted and written as a two's complement signed integer.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">2</span>);
buf.<span class="hljs-title function_">writeInt8</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeInt8</span>(-<span class="hljs-number">2</span>, <span class="hljs-number">1</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 02 fe></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">2</span>);
buf.<span class="hljs-title function_">writeInt8</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeInt8</span>(-<span class="hljs-number">2</span>, <span class="hljs-number">1</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 02 fe></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeInt16BE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteint16bevalue-offset" id="all_buffer_bufwriteint16bevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeint16be_value_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 2</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as big-endian. The <code>value</code>
must be a valid signed 16-bit integer. Behavior is undefined when <code>value</code> is
anything other than a signed 16-bit integer.</p>
<p>The <code>value</code> is interpreted and written as a two's complement signed integer.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">2</span>);
buf.<span class="hljs-title function_">writeInt16BE</span>(<span class="hljs-number">0x0102</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 01 02></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">2</span>);
buf.<span class="hljs-title function_">writeInt16BE</span>(<span class="hljs-number">0x0102</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 01 02></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeInt16LE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteint16levalue-offset" id="all_buffer_bufwriteint16levalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeint16le_value_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 2</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as little-endian. The <code>value</code>
must be a valid signed 16-bit integer. Behavior is undefined when <code>value</code> is
anything other than a signed 16-bit integer.</p>
<p>The <code>value</code> is interpreted and written as a two's complement signed integer.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">2</span>);
buf.<span class="hljs-title function_">writeInt16LE</span>(<span class="hljs-number">0x0304</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 04 03></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">2</span>);
buf.<span class="hljs-title function_">writeInt16LE</span>(<span class="hljs-number">0x0304</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 04 03></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeInt32BE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteint32bevalue-offset" id="all_buffer_bufwriteint32bevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeint32be_value_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as big-endian. The <code>value</code>
must be a valid signed 32-bit integer. Behavior is undefined when <code>value</code> is
anything other than a signed 32-bit integer.</p>
<p>The <code>value</code> is interpreted and written as a two's complement signed integer.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeInt32BE</span>(<span class="hljs-number">0x01020304</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 01 02 03 04></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeInt32BE</span>(<span class="hljs-number">0x01020304</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 01 02 03 04></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeInt32LE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteint32levalue-offset" id="all_buffer_bufwriteint32levalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeint32le_value_offset"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as little-endian. The <code>value</code>
must be a valid signed 32-bit integer. Behavior is undefined when <code>value</code> is
anything other than a signed 32-bit integer.</p>
<p>The <code>value</code> is interpreted and written as a two's complement signed integer.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeInt32LE</span>(<span class="hljs-number">0x05060708</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 08 07 06 05></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeInt32LE</span>(<span class="hljs-number">0x05060708</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 08 07 06 05></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeIntBE(value, offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufwriteintbevalue-offset-bytelength" id="all_buffer_bufwriteintbevalue-offset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeintbe_value_offset_bytelength"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</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>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - byteLength</code>.</li>
<li><code>byteLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to write. Must satisfy
<code>0 < byteLength <= 6</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>byteLength</code> bytes of <code>value</code> to <code>buf</code> at the specified <code>offset</code>
as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when
<code>value</code> is anything other than a signed integer.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);
buf.<span class="hljs-title function_">writeIntBE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 12 34 56 78 90 ab></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);
buf.<span class="hljs-title function_">writeIntBE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 12 34 56 78 90 ab></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeIntLE(value, offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufwriteintlevalue-offset-bytelength" id="all_buffer_bufwriteintlevalue-offset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeintle_value_offset_bytelength"></a></h4>
<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>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</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>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - byteLength</code>.</li>
<li><code>byteLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to write. Must satisfy
<code>0 < byteLength <= 6</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>byteLength</code> bytes of <code>value</code> to <code>buf</code> at the specified <code>offset</code>
as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
when <code>value</code> is anything other than a signed integer.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);
buf.<span class="hljs-title function_">writeIntLE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer ab 90 78 56 34 12></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);
buf.<span class="hljs-title function_">writeIntLE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer ab 90 78 56 34 12></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUInt8(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteuint8value-offset" id="all_buffer_bufwriteuint8value-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuint8_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUint8()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 1</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code>. <code>value</code> must be a
valid unsigned 8-bit integer. Behavior is undefined when <code>value</code> is anything
other than an unsigned 8-bit integer.</p>
<p>This function is also available under the <code>writeUint8</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x3</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x4</span>, <span class="hljs-number">1</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x23</span>, <span class="hljs-number">2</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x42</span>, <span class="hljs-number">3</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 03 04 23 42></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x3</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x4</span>, <span class="hljs-number">1</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x23</span>, <span class="hljs-number">2</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x42</span>, <span class="hljs-number">3</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 03 04 23 42></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUInt16BE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteuint16bevalue-offset" id="all_buffer_bufwriteuint16bevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuint16be_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUint16BE()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 2</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as big-endian. The <code>value</code>
must be a valid unsigned 16-bit integer. Behavior is undefined when <code>value</code>
is anything other than an unsigned 16-bit integer.</p>
<p>This function is also available under the <code>writeUint16BE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeUInt16BE</span>(<span class="hljs-number">0xdead</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeUInt16BE</span>(<span class="hljs-number">0xbeef</span>, <span class="hljs-number">2</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer de ad be ef></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeUInt16BE</span>(<span class="hljs-number">0xdead</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeUInt16BE</span>(<span class="hljs-number">0xbeef</span>, <span class="hljs-number">2</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer de ad be ef></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUInt16LE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteuint16levalue-offset" id="all_buffer_bufwriteuint16levalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuint16le_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUint16LE()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 2</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as little-endian. The <code>value</code>
must be a valid unsigned 16-bit integer. Behavior is undefined when <code>value</code> is
anything other than an unsigned 16-bit integer.</p>
<p>This function is also available under the <code>writeUint16LE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeUInt16LE</span>(<span class="hljs-number">0xdead</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeUInt16LE</span>(<span class="hljs-number">0xbeef</span>, <span class="hljs-number">2</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer ad de ef be></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeUInt16LE</span>(<span class="hljs-number">0xdead</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeUInt16LE</span>(<span class="hljs-number">0xbeef</span>, <span class="hljs-number">2</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer ad de ef be></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUInt32BE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteuint32bevalue-offset" id="all_buffer_bufwriteuint32bevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuint32be_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUint32BE()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as big-endian. The <code>value</code>
must be a valid unsigned 32-bit integer. Behavior is undefined when <code>value</code>
is anything other than an unsigned 32-bit integer.</p>
<p>This function is also available under the <code>writeUint32BE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeUInt32BE</span>(<span class="hljs-number">0xfeedface</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer fe ed fa ce></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeUInt32BE</span>(<span class="hljs-number">0xfeedface</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer fe ed fa ce></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUInt32LE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteuint32levalue-offset" id="all_buffer_bufwriteuint32levalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuint32le_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUint32LE()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> as little-endian. The <code>value</code>
must be a valid unsigned 32-bit integer. Behavior is undefined when <code>value</code> is
anything other than an unsigned 32-bit integer.</p>
<p>This function is also available under the <code>writeUint32LE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeUInt32LE</span>(<span class="hljs-number">0xfeedface</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer ce fa ed fe></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);
buf.<span class="hljs-title function_">writeUInt32LE</span>(<span class="hljs-number">0xfeedface</span>, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer ce fa ed fe></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUIntBE(value, offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufwriteuintbevalue-offset-bytelength" id="all_buffer_bufwriteuintbevalue-offset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuintbe_value_offset_bytelength"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUintBE()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - byteLength</code>.</li>
<li><code>byteLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to write. Must satisfy
<code>0 < byteLength <= 6</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>byteLength</code> bytes of <code>value</code> to <code>buf</code> at the specified <code>offset</code>
as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined
when <code>value</code> is anything other than an unsigned integer.</p>
<p>This function is also available under the <code>writeUintBE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);
buf.<span class="hljs-title function_">writeUIntBE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 12 34 56 78 90 ab></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);
buf.<span class="hljs-title function_">writeUIntBE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer 12 34 56 78 90 ab></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUIntLE(value, offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufwriteuintlevalue-offset-bytelength" id="all_buffer_bufwriteuintlevalue-offset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuintle_value_offset_bytelength"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUintLE()</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 <= offset <= buf.length - byteLength</code>.</li>
<li><code>byteLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to write. Must satisfy
<code>0 < byteLength <= 6</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>byteLength</code> bytes of <code>value</code> to <code>buf</code> at the specified <code>offset</code>
as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
when <code>value</code> is anything other than an unsigned integer.</p>
<p>This function is also available under the <code>writeUintLE</code> alias.</p>
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);
buf.<span class="hljs-title function_">writeUIntLE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer ab 90 78 56 34 12></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);
buf.<span class="hljs-title function_">writeUIntLE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: <Buffer ab 90 78 56 34 12></span></code><button class="copy-button">copy</button></pre>
<h4><code>new Buffer(array)</code><span><a class="mark" href="#all_buffer_new-bufferarray" id="all_buffer_new-bufferarray">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_array"></a></h4>
<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>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr>
<tr><td>v7.2.1</td>
<td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Calling this constructor emits a deprecation warning now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Deprecated since: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_static-method-bufferfromarray"><code>Buffer.from(array)</code></a> instead.</div><p></p>
<ul>
<li><code>array</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a> An array of bytes to copy from.</li>
</ul>
<p>See <a href="#all_buffer_static-method-bufferfromarray"><code>Buffer.from(array)</code></a>.</p>
<h4><code>new Buffer(arrayBuffer[, byteOffset[, length]])</code><span><a class="mark" href="#all_buffer_new-bufferarraybuffer-byteoffset-length" id="all_buffer_new-bufferarraybuffer-byteoffset-length">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_arraybuffer_byteoffset_length"></a></h4>
<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>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr>
<tr><td>v7.2.1</td>
<td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Calling this constructor emits a deprecation warning now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>byteOffset</code> and <code>length</code> parameters are supported now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Deprecated since: v6.0.0</span></p></td></tr>
<tr><td>v3.0.0</td>
<td><p><span>Added in: v3.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use
<a href="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a>
instead.</div><p></p>
<ul>
<li><code>arrayBuffer</code> <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/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> An <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> or the <code>.buffer</code> property of a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>.</li>
<li><code>byteOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Index of first byte to expose. <strong>Default:</strong> <code>0</code>.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to expose.
<strong>Default:</strong> <code>arrayBuffer.byteLength - byteOffset</code>.</li>
</ul>
<p>See
<a href="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a>.</p>
<h4><code>new Buffer(buffer)</code><span><a class="mark" href="#all_buffer_new-bufferbuffer" id="all_buffer_new-bufferbuffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_buffer"></a></h4>
<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>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr>
<tr><td>v7.2.1</td>
<td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Calling this constructor emits a deprecation warning now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Deprecated since: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_static-method-bufferfrombuffer"><code>Buffer.from(buffer)</code></a> instead.</div><p></p>
<ul>
<li><code>buffer</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> An existing <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> from
which to copy data.</li>
</ul>
<p>See <a href="#all_buffer_static-method-bufferfrombuffer"><code>Buffer.from(buffer)</code></a>.</p>
<h4><code>new Buffer(size)</code><span><a class="mark" href="#all_buffer_new-buffersize" id="all_buffer_new-buffersize">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_size"></a></h4>
<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>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>new Buffer(size)</code> will return zero-filled memory by default.</p></td></tr>
<tr><td>v7.2.1</td>
<td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Calling this constructor emits a deprecation warning now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Deprecated since: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc()</code></a> instead (also see
<a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a>).</div><p></p>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The desired length of the new <code>Buffer</code>.</li>
</ul>
<p>See <a href="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc()</code></a> and <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a>. This variant of the
constructor is equivalent to <a href="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc()</code></a>.</p>
<h4><code>new Buffer(string[, encoding])</code><span><a class="mark" href="#all_buffer_new-bufferstring-encoding" id="all_buffer_new-bufferstring-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_string_encoding"></a></h4>
<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>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr>
<tr><td>v7.2.1</td>
<td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Calling this constructor emits a deprecation warning now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Deprecated since: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated:
Use <a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string[, encoding])</code></a> instead.</div><p></p>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> String to encode.</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 of <code>string</code>. <strong>Default:</strong> <code>'utf8'</code>.</li>
</ul>
<p>See <a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string[, encoding])</code></a>.</p>
</section><section><h3>Class: <code>File</code><span><a class="mark" href="#all_buffer_class-file" id="all_buffer_class-file">#</a></span><a aria-hidden="true" class="legacy" id="buffer_class_file"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p><span>Added in: v19.2.0, v18.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Extends: <a href="#all_buffer_class-blob" class="type"><Blob></a></li>
</ul>
<p>A <a href="https://developer.mozilla.org/en-US/docs/Web/API/File"><code>File</code></a> provides information about files.</p>
<h4><code>new buffer.File(sources, fileName[, options])</code><span><a class="mark" href="#all_buffer_new-bufferfilesources-filename-options" id="all_buffer_new-bufferfilesources-filename-options">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_file_sources_filename_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.2.0, v18.13.0</span>
</div>
<ul>
<li><code>sources</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer[]></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="#all_buffer_class-blob" class="type"><Blob[]></a> | <a href="#all_buffer_class-file" class="type"><File[]></a>
An array of string, <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/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="#all_buffer_class-file" class="type"><File></a>, or <a href="#all_buffer_class-blob" class="type"><Blob></a>
objects, or any mix of such objects, that will be stored within the <code>File</code>.</li>
<li><code>fileName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the file.</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>endings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> One of either <code>'transparent'</code> or <code>'native'</code>. When set
to <code>'native'</code>, line endings in string source parts will be converted to
the platform native line-ending as specified by <code>require('node:os').EOL</code>.</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The File content-type.</li>
<li><code>lastModified</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The last modified date of the file.
<strong>Default:</strong> <code>Date.now()</code>.</li>
</ul>
</li>
</ul>
<h4><code>file.name</code><span><a class="mark" href="#all_buffer_filename" id="all_buffer_filename">#</a></span><a aria-hidden="true" class="legacy" id="buffer_file_name"></a></h4>
<div class="api_metadata">
<span>Added in: v19.2.0, v18.13.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The name of the <code>File</code>.</p>
<h4><code>file.lastModified</code><span><a class="mark" href="#all_buffer_filelastmodified" id="all_buffer_filelastmodified">#</a></span><a aria-hidden="true" class="legacy" id="buffer_file_lastmodified"></a></h4>
<div class="api_metadata">
<span>Added in: v19.2.0, v18.13.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The last modified date of the <code>File</code>.</p>
</section><section><h3><code>node:buffer</code> module APIs<span><a class="mark" href="#all_buffer_nodebuffer-module-apis" id="all_buffer_nodebuffer-module-apis">#</a></span><a aria-hidden="true" class="legacy" id="buffer_node_buffer_module_apis"></a></h3>
<p>While, the <code>Buffer</code> object is available as a global, there are additional
<code>Buffer</code>-related APIs that are available only via the <code>node:buffer</code> module
accessed using <code>require('node:buffer')</code>.</p>
<h4><code>buffer.atob(data)</code><span><a class="mark" href="#all_buffer_bufferatobdata" id="all_buffer_bufferatobdata">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_atob_data"></a></h4>
<div class="api_metadata">
<span>Added in: v15.13.0, v14.17.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy. Use <code>Buffer.from(data, 'base64')</code> instead.</div><p></p>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The Base64-encoded input string.</li>
</ul>
<p>Decodes a string of Base64-encoded data into bytes, and encodes those bytes
into a string using Latin-1 (ISO-8859-1).</p>
<p>The <code>data</code> may be any JavaScript-value that can be coerced into a string.</p>
<p><strong>This function is only provided for compatibility with legacy web platform APIs
and should never be used in new code, because they use strings to represent
binary data and predate the introduction of typed arrays in JavaScript.
For code running using Node.js APIs, converting between base64-encoded strings
and binary data should be performed using <code>Buffer.from(str, 'base64')</code> and
<code>buf.toString('base64')</code>.</strong></p>
<h4><code>buffer.btoa(data)</code><span><a class="mark" href="#all_buffer_bufferbtoadata" id="all_buffer_bufferbtoadata">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_btoa_data"></a></h4>
<div class="api_metadata">
<span>Added in: v15.13.0, v14.17.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy. Use <code>buf.toString('base64')</code> instead.</div><p></p>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> An ASCII (Latin1) string.</li>
</ul>
<p>Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes
into a string using Base64.</p>
<p>The <code>data</code> may be any JavaScript-value that can be coerced into a string.</p>
<p><strong>This function is only provided for compatibility with legacy web platform APIs
and should never be used in new code, because they use strings to represent
binary data and predate the introduction of typed arrays in JavaScript.
For code running using Node.js APIs, converting between base64-encoded strings
and binary data should be performed using <code>Buffer.from(str, 'base64')</code> and
<code>buf.toString('base64')</code>.</strong></p>
<h4><code>buffer.isAscii(input)</code><span><a class="mark" href="#all_buffer_bufferisasciiinput" id="all_buffer_bufferisasciiinput">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_isascii_input"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li>input <a href="#all_buffer_class-buffer" class="type"><Buffer></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/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> The input to validate.</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>This function returns <code>true</code> if <code>input</code> contains only valid ASCII-encoded data,
including the case in which <code>input</code> is empty.</p>
<p>Throws if the <code>input</code> is a detached array buffer.</p>
<h4><code>buffer.isUtf8(input)</code><span><a class="mark" href="#all_buffer_bufferisutf8input" id="all_buffer_bufferisutf8input">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_isutf8_input"></a></h4>
<div class="api_metadata">
<span>Added in: v19.4.0, v18.14.0</span>
</div>
<ul>
<li>input <a href="#all_buffer_class-buffer" class="type"><Buffer></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/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> The input to validate.</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>This function returns <code>true</code> if <code>input</code> contains only valid UTF-8-encoded data,
including the case in which <code>input</code> is empty.</p>
<p>Throws if the <code>input</code> is a detached array buffer.</p>
<h4><code>buffer.INSPECT_MAX_BYTES</code><span><a class="mark" href="#all_buffer_bufferinspect_max_bytes" id="all_buffer_bufferinspect_max_bytes">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_inspect_max_bytes"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>50</code></li>
</ul>
<p>Returns the maximum number of bytes that will be returned when
<code>buf.inspect()</code> is called. This can be overridden by user modules. See
<a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> for more details on <code>buf.inspect()</code> behavior.</p>
<h4><code>buffer.kMaxLength</code><span><a class="mark" href="#all_buffer_bufferkmaxlength" id="all_buffer_bufferkmaxlength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_kmaxlength"></a></h4>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The largest size allowed for a single <code>Buffer</code> instance.</li>
</ul>
<p>An alias for <a href="#all_buffer_bufferconstantsmax_length"><code>buffer.constants.MAX_LENGTH</code></a>.</p>
<h4><code>buffer.kStringMaxLength</code><span><a class="mark" href="#all_buffer_bufferkstringmaxlength" id="all_buffer_bufferkstringmaxlength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_kstringmaxlength"></a></h4>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The largest length allowed for a single <code>string</code> instance.</li>
</ul>
<p>An alias for <a href="#all_buffer_bufferconstantsmax_string_length"><code>buffer.constants.MAX_STRING_LENGTH</code></a>.</p>
<h4><code>buffer.resolveObjectURL(id)</code><span><a class="mark" href="#all_buffer_bufferresolveobjecturlid" id="all_buffer_bufferresolveobjecturlid">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_resolveobjecturl_id"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A <code>'blob:nodedata:...</code> URL string returned by a prior call to
<code>URL.createObjectURL()</code>.</li>
<li>Returns: <a href="#all_buffer_class-blob" class="type"><Blob></a></li>
</ul>
<p>Resolves a <code>'blob:nodedata:...'</code> an associated <a href="#all_buffer_class-blob" class="type"><Blob></a> object registered using
a prior call to <code>URL.createObjectURL()</code>.</p>
<h4><code>buffer.transcode(source, fromEnc, toEnc)</code><span><a class="mark" href="#all_buffer_buffertranscodesource-fromenc-toenc" id="all_buffer_buffertranscodesource-fromenc-toenc">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_transcode_source_fromenc_toenc"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>source</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v7.1.0</td>
<td><p><span>Added in: v7.1.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>source</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> A <code>Buffer</code> or <code>Uint8Array</code> instance.</li>
<li><code>fromEnc</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The current encoding.</li>
<li><code>toEnc</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> To target encoding.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Re-encodes the given <code>Buffer</code> or <code>Uint8Array</code> instance from one character
encoding to another. Returns a new <code>Buffer</code> instance.</p>
<p>Throws if the <code>fromEnc</code> or <code>toEnc</code> specify invalid character encodings or if
conversion from <code>fromEnc</code> to <code>toEnc</code> is not permitted.</p>
<p>Encodings supported by <code>buffer.transcode()</code> are: <code>'ascii'</code>, <code>'utf8'</code>,
<code>'utf16le'</code>, <code>'ucs2'</code>, <code>'latin1'</code>, and <code>'binary'</code>.</p>
<p>The transcoding process will use substitution characters if a given byte
sequence cannot be adequately represented in the target encoding. For instance:</p>
<pre class="with-53-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_">Buffer</span>, transcode } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> newBuf = <span class="hljs-title function_">transcode</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'€'</span>), <span class="hljs-string">'utf8'</span>, <span class="hljs-string">'ascii'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(newBuf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>));
<span class="hljs-comment">// Prints: '?'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span>, transcode } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> newBuf = <span class="hljs-title function_">transcode</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'€'</span>), <span class="hljs-string">'utf8'</span>, <span class="hljs-string">'ascii'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(newBuf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>));
<span class="hljs-comment">// Prints: '?'</span></code><button class="copy-button">copy</button></pre>
<p>Because the Euro (<code>€</code>) sign is not representable in US-ASCII, it is replaced
with <code>?</code> in the transcoded <code>Buffer</code>.</p>
<h4>Class: <code>SlowBuffer</code><span><a class="mark" href="#all_buffer_class-slowbuffer" id="all_buffer_class-slowbuffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_class_slowbuffer"></a></h4>
<div class="api_metadata">
<span>Deprecated since: v6.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow()</code></a> instead.</div><p></p>
<p>See <a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow()</code></a>. This was never a class in the sense that
the constructor always returned a <code>Buffer</code> instance, rather than a <code>SlowBuffer</code>
instance.</p>
<h5><code>new SlowBuffer(size)</code><span><a class="mark" href="#all_buffer_new-slowbuffersize" id="all_buffer_new-slowbuffersize">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_slowbuffer_size"></a></h5>
<div class="api_metadata">
<span>Deprecated since: v6.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow()</code></a> instead.</div><p></p>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The desired length of the new <code>SlowBuffer</code>.</li>
</ul>
<p>See <a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow()</code></a>.</p>
<h4>Buffer constants<span><a class="mark" href="#all_buffer_buffer-constants" id="all_buffer_buffer-constants">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_constants"></a></h4>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
</div>
<h5><code>buffer.constants.MAX_LENGTH</code><span><a class="mark" href="#all_buffer_bufferconstantsmax_length" id="all_buffer_bufferconstantsmax_length">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_constants_max_length"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Value is changed to 2<sup>32</sup> on 64-bit architectures.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Value is changed from 2<sup>31</sup> - 1 to 2<sup>32</sup> - 1 on 64-bit architectures.</p></td></tr>
<tr><td>v8.2.0</td>
<td><p><span>Added in: v8.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The largest size allowed for a single <code>Buffer</code> instance.</li>
</ul>
<p>On 32-bit architectures, this value currently is 2<sup>30</sup> - 1 (about 1
GiB).</p>
<p>On 64-bit architectures, this value currently is 2<sup>32</sup> (about 4 GiB).</p>
<p>It reflects <a href="https://v8.github.io/api/head/classv8_1_1TypedArray.html#a54a48f4373da0850663c4393d843b9b0"><code>v8::TypedArray::kMaxLength</code></a> under the hood.</p>
<p>This value is also available as <a href="#all_buffer_bufferkmaxlength"><code>buffer.kMaxLength</code></a>.</p>
<h5><code>buffer.constants.MAX_STRING_LENGTH</code><span><a class="mark" href="#all_buffer_bufferconstantsmax_string_length" id="all_buffer_bufferconstantsmax_string_length">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_constants_max_string_length"></a></h5>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The largest length allowed for a single <code>string</code> instance.</li>
</ul>
<p>Represents the largest <code>length</code> that a <code>string</code> primitive can have, counted
in UTF-16 code units.</p>
<p>This value may depend on the JS engine that is being used.</p>
</section><section><h3><code>Buffer.from()</code>, <code>Buffer.alloc()</code>, and <code>Buffer.allocUnsafe()</code><span><a class="mark" href="#all_buffer_bufferfrom-bufferalloc-and-bufferallocunsafe" id="all_buffer_bufferfrom-bufferalloc-and-bufferallocunsafe">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_from_buffer_alloc_and_buffer_allocunsafe"></a></h3>
<p>In versions of Node.js prior to 6.0.0, <code>Buffer</code> instances were created using the
<code>Buffer</code> constructor function, which allocates the returned <code>Buffer</code>
differently based on what arguments are provided:</p>
<ul>
<li>Passing a number as the first argument to <code>Buffer()</code> (e.g. <code>new Buffer(10)</code>)
allocates a new <code>Buffer</code> object of the specified size. Prior to Node.js 8.0.0,
the memory allocated for such <code>Buffer</code> instances is <em>not</em> initialized and
<em>can contain sensitive data</em>. Such <code>Buffer</code> instances <em>must</em> be subsequently
initialized by using either <a href="#all_buffer_buffillvalue-offset-end-encoding"><code>buf.fill(0)</code></a> or by writing to the
entire <code>Buffer</code> before reading data from the <code>Buffer</code>.
While this behavior is <em>intentional</em> to improve performance,
development experience has demonstrated that a more explicit distinction is
required between creating a fast-but-uninitialized <code>Buffer</code> versus creating a
slower-but-safer <code>Buffer</code>. Since Node.js 8.0.0, <code>Buffer(num)</code> and <code>new Buffer(num)</code> return a <code>Buffer</code> with initialized memory.</li>
<li>Passing a string, array, or <code>Buffer</code> as the first argument copies the
passed object's data into the <code>Buffer</code>.</li>
<li>Passing an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> or a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> returns a <code>Buffer</code>
that shares allocated memory with the given array buffer.</li>
</ul>
<p>Because the behavior of <code>new Buffer()</code> is different depending on the type of the
first argument, security and reliability issues can be inadvertently introduced
into applications when argument validation or <code>Buffer</code> initialization is not
performed.</p>
<p>For example, if an attacker can cause an application to receive a number where
a string is expected, the application may call <code>new Buffer(100)</code>
instead of <code>new Buffer("100")</code>, leading it to allocate a 100 byte buffer instead
of allocating a 3 byte buffer with content <code>"100"</code>. This is commonly possible
using JSON API calls. Since JSON distinguishes between numeric and string types,
it allows injection of numbers where a naively written application that does not
validate its input sufficiently might expect to always receive a string.
Before Node.js 8.0.0, the 100 byte buffer might contain
arbitrary pre-existing in-memory data, so may be used to expose in-memory
secrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot
occur because the data is zero-filled. However, other attacks are still
possible, such as causing very large buffers to be allocated by the server,
leading to performance degradation or crashing on memory exhaustion.</p>
<p>To make the creation of <code>Buffer</code> instances more reliable and less error-prone,
the various forms of the <code>new Buffer()</code> constructor have been <strong>deprecated</strong>
and replaced by separate <code>Buffer.from()</code>, <a href="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc()</code></a>, and
<a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> methods.</p>
<p><em>Developers should migrate all existing uses of the <code>new Buffer()</code> constructors
to one of these new APIs.</em></p>
<ul>
<li><a href="#all_buffer_static-method-bufferfromarray"><code>Buffer.from(array)</code></a> returns a new <code>Buffer</code> that <em>contains a copy</em> of the
provided octets.</li>
<li><a href="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a>
returns a new <code>Buffer</code> that <em>shares the same allocated memory</em> as the given
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>.</li>
<li><a href="#all_buffer_static-method-bufferfrombuffer"><code>Buffer.from(buffer)</code></a> returns a new <code>Buffer</code> that <em>contains a copy</em> of the
contents of the given <code>Buffer</code>.</li>
<li><a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string[, encoding])</code></a> returns a new
<code>Buffer</code> that <em>contains a copy</em> of the provided string.</li>
<li><a href="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc(size[, fill[, encoding]])</code></a> returns a new
initialized <code>Buffer</code> of the specified size. This method is slower than
<a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe(size)</code></a> but guarantees that newly
created <code>Buffer</code> instances never contain old data that is potentially
sensitive. A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</li>
<li><a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe(size)</code></a> and
<a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow(size)</code></a> each return a
new uninitialized <code>Buffer</code> of the specified <code>size</code>. Because the <code>Buffer</code> is
uninitialized, the allocated segment of memory might contain old data that is
potentially sensitive.</li>
</ul>
<p><code>Buffer</code> instances returned by <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a>, <a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string)</code></a>,
<a href="#all_buffer_static-method-bufferconcatlist-totallength"><code>Buffer.concat()</code></a> and <a href="#all_buffer_static-method-bufferfromarray"><code>Buffer.from(array)</code></a> <em>may</em> be allocated off a shared
internal memory pool if <code>size</code> is less than or equal to half <a href="#all_buffer_class-property-bufferpoolsize"><code>Buffer.poolSize</code></a>.
Instances returned by <a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow()</code></a> <em>never</em> use the shared internal
memory pool.</p>
<h4>The <code>--zero-fill-buffers</code> command-line option<span><a class="mark" href="#all_buffer_the---zero-fill-buffers-command-line-option" id="all_buffer_the---zero-fill-buffers-command-line-option">#</a></span><a aria-hidden="true" class="legacy" id="buffer_the_zero_fill_buffers_command_line_option"></a></h4>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<p>Node.js can be started using the <code>--zero-fill-buffers</code> command-line option to
cause all newly-allocated <code>Buffer</code> instances to be zero-filled upon creation by
default. Without the option, buffers created with <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a>,
<a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow()</code></a>, and <code>new SlowBuffer(size)</code> are not zero-filled.
Use of this flag can have a measurable negative impact on performance. Use the
<code>--zero-fill-buffers</code> option only when necessary to enforce that newly allocated
<code>Buffer</code> instances cannot contain old data that is potentially sensitive.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --zero-fill-buffers</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">Buffer.allocUnsafe(5);</span>
<Buffer 00 00 00 00 00></code> <button class="copy-button">copy</button></pre>
<h4>What makes <code>Buffer.allocUnsafe()</code> and <code>Buffer.allocUnsafeSlow()</code> "unsafe"?<span><a class="mark" href="#all_buffer_what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe" id="all_buffer_what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe">#</a></span><a aria-hidden="true" class="legacy" id="buffer_what_makes_buffer_allocunsafe_and_buffer_allocunsafeslow_unsafe"></a></h4>
<p>When calling <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> and <a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow()</code></a>, the
segment of allocated memory is <em>uninitialized</em> (it is not zeroed-out). While
this design makes the allocation of memory quite fast, the allocated segment of
memory might contain old data that is potentially sensitive. Using a <code>Buffer</code>
created by <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> without <em>completely</em> overwriting the
memory can allow this old data to be leaked when the <code>Buffer</code> memory is read.</p>
<p>While there are clear performance advantages to using
<a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a>, extra care <em>must</em> be taken in order to avoid
introducing security vulnerabilities into an application.</p></section>
</section>
<section><h2>C++ addons<span><a class="mark" href="#all_addons_c-addons" id="all_addons_c-addons">#</a></span><a aria-hidden="true" class="legacy" id="addons_c_addons"></a></h2>
<p><em>Addons</em> are dynamically-linked shared objects written in C++. The
<a href="#all_modules_requireid"><code>require()</code></a> function can load addons as ordinary Node.js modules.
Addons provide an interface between JavaScript and C/C++ libraries.</p>
<p>There are three options for implementing addons:</p>
<ul>
<li>Node-API</li>
<li><code>nan</code> (<a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a>)</li>
<li>direct use of internal V8, libuv, and Node.js libraries</li>
</ul>
<p>Unless there is a need for direct access to functionality which is not<br>
exposed by Node-API, use Node-API.
Refer to <a href="n-api.html">C/C++ addons with Node-API</a> for more information on
Node-API.</p>
<p>When not using Node-API, implementing addons becomes more complex, requiring<br>
knowledge of multiple components and APIs:</p>
<ul>
<li>
<p><a href="https://v8.dev/">V8</a>: the C++ library Node.js uses to provide the
JavaScript implementation. It provides the mechanisms for creating objects,
calling functions, etc. The V8's API is documented mostly in the
<code>v8.h</code> header file (<code>deps/v8/include/v8.h</code> in the Node.js source
tree), and is also available <a href="https://v8docs.nodesource.com/">online</a>.</p>
</li>
<li>
<p><a href="https://github.com/libuv/libuv">libuv</a>: The C library that implements the Node.js event loop, its worker
threads and all of the asynchronous behaviors of the platform. It also
serves as a cross-platform abstraction library, giving easy, POSIX-like
access across all major operating systems to many common system tasks, such
as interacting with the file system, sockets, timers, and system events. libuv
also provides a threading abstraction similar to POSIX threads for
more sophisticated asynchronous addons that need to move beyond the
standard event loop. Addon authors should
avoid blocking the event loop with I/O or other time-intensive tasks by
offloading work via libuv to non-blocking system operations, worker threads,
or a custom use of libuv threads.</p>
</li>
<li>
<p>Internal Node.js libraries: Node.js itself exports C++ APIs that addons can
use, the most important of which is the <code>node::ObjectWrap</code> class.</p>
</li>
<li>
<p>Other statically linked libraries (including OpenSSL): These
other libraries are located in the <code>deps/</code> directory in the Node.js source
tree. Only the libuv, OpenSSL, V8, and zlib symbols are purposefully
re-exported by Node.js and may be used to various extents by addons. See
<a href="#all_addons_linking-to-libraries-included-with-nodejs">Linking to libraries included with Node.js</a> for additional information.</p>
</li>
</ul>
<p>All of the following examples are available for <a href="https://github.com/nodejs/node-addon-examples">download</a> and may
be used as the starting-point for an addon.</p>
<section><h3>Hello world<span><a class="mark" href="#all_addons_hello-world" id="all_addons_hello-world">#</a></span><a aria-hidden="true" class="legacy" id="addons_hello_world"></a></h3>
<p>This "Hello world" example is a simple addon, written in C++, that is the
equivalent of the following JavaScript code:</p>
<pre><code class="language-js"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-property">hello</span> = <span class="hljs-function">() =></span> <span class="hljs-string">'world'</span>;</code> <button class="copy-button">copy</button></pre>
<p>First, create the file <code>hello.cc</code>:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// hello.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::NewStringType;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Method</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(
isolate, <span class="hljs-string">"world"</span>, NewStringType::kNormal).<span class="hljs-built_in">ToLocalChecked</span>());
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Initialize</span><span class="hljs-params">(Local<Object> exports)</span> </span>{
<span class="hljs-built_in">NODE_SET_METHOD</span>(exports, <span class="hljs-string">"hello"</span>, Method);
}
<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Initialize)
} <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>All Node.js addons must export an initialization function following
the pattern:</p>
<pre><code class="language-cpp"><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Initialize</span><span class="hljs-params">(Local<Object> exports)</span></span>;
<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Initialize)</code> <button class="copy-button">copy</button></pre>
<p>There is no semi-colon after <code>NODE_MODULE</code> as it's not a function (see
<code>node.h</code>).</p>
<p>The <code>module_name</code> must match the filename of the final binary (excluding
the <code>.node</code> suffix).</p>
<p>In the <code>hello.cc</code> example, then, the initialization function is <code>Initialize</code>
and the addon module name is <code>addon</code>.</p>
<p>When building addons with <code>node-gyp</code>, using the macro <code>NODE_GYP_MODULE_NAME</code> as
the first parameter of <code>NODE_MODULE()</code> will ensure that the name of the final
binary will be passed to <code>NODE_MODULE()</code>.</p>
<p>Addons defined with <code>NODE_MODULE()</code> can not be loaded in multiple contexts or
multiple threads at the same time.</p>
<h4>Context-aware addons<span><a class="mark" href="#all_addons_context-aware-addons" id="all_addons_context-aware-addons">#</a></span><a aria-hidden="true" class="legacy" id="addons_context_aware_addons"></a></h4>
<p>There are environments in which Node.js addons may need to be loaded multiple
times in multiple contexts. For example, the <a href="https://electronjs.org/">Electron</a> runtime runs multiple
instances of Node.js in a single process. Each instance will have its own
<code>require()</code> cache, and thus each instance will need a native addon to behave
correctly when loaded via <code>require()</code>. This means that the addon
must support multiple initializations.</p>
<p>A context-aware addon can be constructed by using the macro
<code>NODE_MODULE_INITIALIZER</code>, which expands to the name of a function which Node.js
will expect to find when it loads an addon. An addon can thus be initialized as
in the following example:</p>
<pre><code class="language-cpp"><span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> v8;
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function">NODE_MODULE_EXPORT <span class="hljs-type">void</span>
<span class="hljs-title">NODE_MODULE_INITIALIZER</span><span class="hljs-params">(Local<Object> exports,
Local<Value> <span class="hljs-keyword">module</span>,
Local<Context> context)</span> </span>{
<span class="hljs-comment">/* Perform addon initialization steps here. */</span>
}</code> <button class="copy-button">copy</button></pre>
<p>Another option is to use the macro <code>NODE_MODULE_INIT()</code>, which will also
construct a context-aware addon. Unlike <code>NODE_MODULE()</code>, which is used to
construct an addon around a given addon initializer function,
<code>NODE_MODULE_INIT()</code> serves as the declaration of such an initializer to be
followed by a function body.</p>
<p>The following three variables may be used inside the function body following an
invocation of <code>NODE_MODULE_INIT()</code>:</p>
<ul>
<li><code>Local<Object> exports</code>,</li>
<li><code>Local<Value> module</code>, and</li>
<li><code>Local<Context> context</code></li>
</ul>
<p>Building a context-aware addon requires careful management of global static data
to ensure stability and correctness. Since the addon may be loaded multiple
times, potentially even from different threads, any global static data stored
in the addon must be properly protected, and must not contain any persistent
references to JavaScript objects. The reason for this is that JavaScript
objects are only valid in one context, and will likely cause a crash when
accessed from the wrong context or from a different thread than the one on which
they were created.</p>
<p>The context-aware addon can be structured to avoid global static data by
performing the following steps:</p>
<ul>
<li>Define a class which will hold per-addon-instance data and which has a static
member of the form
<pre><code class="language-cpp"><span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">DeleteInstance</span><span class="hljs-params">(<span class="hljs-type">void</span>* data)</span> </span>{
<span class="hljs-comment">// Cast `data` to an instance of the class and delete it.</span>
}</code> <button class="copy-button">copy</button></pre>
</li>
<li>Heap-allocate an instance of this class in the addon initializer. This can be
accomplished using the <code>new</code> keyword.</li>
<li>Call <code>node::AddEnvironmentCleanupHook()</code>, passing it the above-created
instance and a pointer to <code>DeleteInstance()</code>. This will ensure the instance is
deleted when the environment is torn down.</li>
<li>Store the instance of the class in a <code>v8::External</code>, and</li>
<li>Pass the <code>v8::External</code> to all methods exposed to JavaScript by passing it
to <code>v8::FunctionTemplate::New()</code> or <code>v8::Function::New()</code> which creates the
native-backed JavaScript functions. The third parameter of
<code>v8::FunctionTemplate::New()</code> or <code>v8::Function::New()</code> accepts the
<code>v8::External</code> and makes it available in the native callback using the
<code>v8::FunctionCallbackInfo::Data()</code> method.</li>
</ul>
<p>This will ensure that the per-addon-instance data reaches each binding that can
be called from JavaScript. The per-addon-instance data must also be passed into
any asynchronous callbacks the addon may create.</p>
<p>The following example illustrates the implementation of a context-aware addon:</p>
<pre><code class="language-cpp"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> v8;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">AddonData</span> {
<span class="hljs-keyword">public</span>:
<span class="hljs-function"><span class="hljs-keyword">explicit</span> <span class="hljs-title">AddonData</span><span class="hljs-params">(Isolate* isolate)</span>:
call_count(<span class="hljs-number">0</span>) {</span>
<span class="hljs-comment">// Ensure this per-addon-instance data is deleted at environment cleanup.</span>
node::<span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, DeleteInstance, <span class="hljs-keyword">this</span>);
}
<span class="hljs-comment">// Per-addon data.</span>
<span class="hljs-type">int</span> call_count;
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">DeleteInstance</span><span class="hljs-params">(<span class="hljs-type">void</span>* data)</span> </span>{
<span class="hljs-keyword">delete</span> <span class="hljs-built_in">static_cast</span><AddonData*>(data);
}
};
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">Method</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo<v8::Value>& info)</span> </span>{
<span class="hljs-comment">// Retrieve the per-addon-instance data.</span>
AddonData* data =
<span class="hljs-built_in">reinterpret_cast</span><AddonData*>(info.<span class="hljs-built_in">Data</span>().<span class="hljs-built_in">As</span><External>()-><span class="hljs-built_in">Value</span>());
data->call_count++;
info.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>((<span class="hljs-type">double</span>)data->call_count);
}
<span class="hljs-comment">// Initialize this addon to be context-aware.</span>
<span class="hljs-built_in">NODE_MODULE_INIT</span>(<span class="hljs-comment">/* exports, module, context */</span>) {
Isolate* isolate = context-><span class="hljs-built_in">GetIsolate</span>();
<span class="hljs-comment">// Create a new instance of `AddonData` for this instance of the addon and</span>
<span class="hljs-comment">// tie its life cycle to that of the Node.js environment.</span>
AddonData* data = <span class="hljs-keyword">new</span> <span class="hljs-built_in">AddonData</span>(isolate);
<span class="hljs-comment">// Wrap the data in a `v8::External` so we can pass it to the method we</span>
<span class="hljs-comment">// expose.</span>
Local<External> external = External::<span class="hljs-built_in">New</span>(isolate, data);
<span class="hljs-comment">// Expose the method `Method` to JavaScript, and make sure it receives the</span>
<span class="hljs-comment">// per-addon-instance data we created above by passing `external` as the</span>
<span class="hljs-comment">// third parameter to the `FunctionTemplate` constructor.</span>
exports-><span class="hljs-built_in">Set</span>(context,
String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, <span class="hljs-string">"method"</span>).<span class="hljs-built_in">ToLocalChecked</span>(),
FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, Method, external)
-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>()).<span class="hljs-built_in">FromJust</span>();
}</code> <button class="copy-button">copy</button></pre>
<h5>Worker support<span><a class="mark" href="#all_addons_worker-support" id="all_addons_worker-support">#</a></span><a aria-hidden="true" class="legacy" id="addons_worker_support"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.8.0, v12.19.0</td>
<td><p>Cleanup hooks may now be asynchronous.</p></td></tr>
</tbody></table>
</details>
</div>
<p>In order to be loaded from multiple Node.js environments,
such as a main thread and a Worker thread, an add-on needs to either:</p>
<ul>
<li>Be an Node-API addon, or</li>
<li>Be declared as context-aware using <code>NODE_MODULE_INIT()</code> as described above</li>
</ul>
<p>In order to support <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads, addons need to clean up any resources
they may have allocated when such a thread exits. This can be achieved through
the usage of the <code>AddEnvironmentCleanupHook()</code> function:</p>
<pre><code class="language-cpp"><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">AddEnvironmentCleanupHook</span><span class="hljs-params">(v8::Isolate* isolate,
<span class="hljs-type">void</span> (*fun)(<span class="hljs-type">void</span>* arg),
<span class="hljs-type">void</span>* arg)</span></span>;</code> <button class="copy-button">copy</button></pre>
<p>This function adds a hook that will run before a given Node.js instance shuts
down. If necessary, such hooks can be removed before they are run using
<code>RemoveEnvironmentCleanupHook()</code>, which has the same signature. Callbacks are
run in last-in first-out order.</p>
<p>If necessary, there is an additional pair of <code>AddEnvironmentCleanupHook()</code>
and <code>RemoveEnvironmentCleanupHook()</code> overloads, where the cleanup hook takes a
callback function. This can be used for shutting down asynchronous resources,
such as any libuv handles registered by the addon.</p>
<p>The following <code>addon.cc</code> uses <code>AddEnvironmentCleanupHook</code>:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><assert.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><stdlib.h></span></span>
<span class="hljs-keyword">using</span> node::AddEnvironmentCleanupHook;
<span class="hljs-keyword">using</span> v8::HandleScope;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-comment">// Note: In a real-world application, do not rely on static/global data.</span>
<span class="hljs-type">static</span> <span class="hljs-type">char</span> cookie[] = <span class="hljs-string">"yum yum"</span>;
<span class="hljs-type">static</span> <span class="hljs-type">int</span> cleanup_cb1_called = <span class="hljs-number">0</span>;
<span class="hljs-type">static</span> <span class="hljs-type">int</span> cleanup_cb2_called = <span class="hljs-number">0</span>;
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">cleanup_cb1</span><span class="hljs-params">(<span class="hljs-type">void</span>* arg)</span> </span>{
Isolate* isolate = <span class="hljs-built_in">static_cast</span><Isolate*>(arg);
<span class="hljs-function">HandleScope <span class="hljs-title">scope</span><span class="hljs-params">(isolate)</span></span>;
Local<Object> obj = Object::<span class="hljs-built_in">New</span>(isolate);
<span class="hljs-built_in">assert</span>(!obj.<span class="hljs-built_in">IsEmpty</span>()); <span class="hljs-comment">// assert VM is still alive</span>
<span class="hljs-built_in">assert</span>(obj-><span class="hljs-built_in">IsObject</span>());
cleanup_cb1_called++;
}
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">cleanup_cb2</span><span class="hljs-params">(<span class="hljs-type">void</span>* arg)</span> </span>{
<span class="hljs-built_in">assert</span>(arg == <span class="hljs-built_in">static_cast</span><<span class="hljs-type">void</span>*>(cookie));
cleanup_cb2_called++;
}
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">sanity_check</span><span class="hljs-params">(<span class="hljs-type">void</span>*)</span> </span>{
<span class="hljs-built_in">assert</span>(cleanup_cb1_called == <span class="hljs-number">1</span>);
<span class="hljs-built_in">assert</span>(cleanup_cb2_called == <span class="hljs-number">1</span>);
}
<span class="hljs-comment">// Initialize this addon to be context-aware.</span>
<span class="hljs-built_in">NODE_MODULE_INIT</span>(<span class="hljs-comment">/* exports, module, context */</span>) {
Isolate* isolate = context-><span class="hljs-built_in">GetIsolate</span>();
<span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, sanity_check, <span class="hljs-literal">nullptr</span>);
<span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, cleanup_cb2, cookie);
<span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, cleanup_cb1, isolate);
}</code> <button class="copy-button">copy</button></pre>
<p>Test in JavaScript by running:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);</code> <button class="copy-button">copy</button></pre>
<h4>Building<span><a class="mark" href="#all_addons_building" id="all_addons_building">#</a></span><a aria-hidden="true" class="legacy" id="addons_building"></a></h4>
<p>Once the source code has been written, it must be compiled into the binary
<code>addon.node</code> file. To do so, create a file called <code>binding.gyp</code> in the
top-level of the project describing the build configuration of the module
using a JSON-like format. This file is used by <a href="https://github.com/nodejs/node-gyp">node-gyp</a>, a tool written
specifically to compile Node.js addons.</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"targets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"target_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"addon"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> <span class="hljs-string">"hello.cc"</span> <span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>A version of the <code>node-gyp</code> utility is bundled and distributed with
Node.js as part of <code>npm</code>. This version is not made directly available for
developers to use and is intended only to support the ability to use the
<code>npm install</code> command to compile and install addons. Developers who wish to
use <code>node-gyp</code> directly can install it using the command
<code>npm install -g node-gyp</code>. See the <code>node-gyp</code> <a href="https://github.com/nodejs/node-gyp#installation">installation instructions</a> for
more information, including platform-specific requirements.</p>
<p>Once the <code>binding.gyp</code> file has been created, use <code>node-gyp configure</code> to
generate the appropriate project build files for the current platform. This
will generate either a <code>Makefile</code> (on Unix platforms) or a <code>vcxproj</code> file
(on Windows) in the <code>build/</code> directory.</p>
<p>Next, invoke the <code>node-gyp build</code> command to generate the compiled <code>addon.node</code>
file. This will be put into the <code>build/Release/</code> directory.</p>
<p>When using <code>npm install</code> to install a Node.js addon, npm uses its own bundled
version of <code>node-gyp</code> to perform this same set of actions, generating a
compiled version of the addon for the user's platform on demand.</p>
<p>Once built, the binary addon can be used from within Node.js by pointing
<a href="#all_modules_requireid"><code>require()</code></a> to the built <code>addon.node</code> module:</p>
<pre><code class="language-js"><span class="hljs-comment">// hello.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(addon.<span class="hljs-title function_">hello</span>());
<span class="hljs-comment">// Prints: 'world'</span></code> <button class="copy-button">copy</button></pre>
<p>Because the exact path to the compiled addon binary can vary depending on how
it is compiled (i.e. sometimes it may be in <code>./build/Debug/</code>), addons can use
the <a href="https://github.com/TooTallNate/node-bindings">bindings</a> package to load the compiled module.</p>
<p>While the <code>bindings</code> package implementation is more sophisticated in how it
locates addon modules, it is essentially using a <code>try…catch</code> pattern similar to:</p>
<pre><code class="language-js"><span class="hljs-keyword">try</span> {
<span class="hljs-keyword">return</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon.node'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-keyword">return</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Debug/addon.node'</span>);
}</code> <button class="copy-button">copy</button></pre>
<h4>Linking to libraries included with Node.js<span><a class="mark" href="#all_addons_linking-to-libraries-included-with-nodejs" id="all_addons_linking-to-libraries-included-with-nodejs">#</a></span><a aria-hidden="true" class="legacy" id="addons_linking_to_libraries_included_with_node_js"></a></h4>
<p>Node.js uses statically linked libraries such as V8, libuv, and OpenSSL. All
addons are required to link to V8 and may link to any of the other dependencies
as well. Typically, this is as simple as including the appropriate
<code>#include <...></code> statements (e.g. <code>#include <v8.h></code>) and <code>node-gyp</code> will locate
the appropriate headers automatically. However, there are a few caveats to be
aware of:</p>
<ul>
<li>
<p>When <code>node-gyp</code> runs, it will detect the specific release version of Node.js
and download either the full source tarball or just the headers. If the full
source is downloaded, addons will have complete access to the full set of
Node.js dependencies. However, if only the Node.js headers are downloaded,
then only the symbols exported by Node.js will be available.</p>
</li>
<li>
<p><code>node-gyp</code> can be run using the <code>--nodedir</code> flag pointing at a local Node.js
source image. Using this option, the addon will have access to the full set of
dependencies.</p>
</li>
</ul>
<h4>Loading addons using <code>require()</code><span><a class="mark" href="#all_addons_loading-addons-using-require" id="all_addons_loading-addons-using-require">#</a></span><a aria-hidden="true" class="legacy" id="addons_loading_addons_using_require"></a></h4>
<p>The filename extension of the compiled addon binary is <code>.node</code> (as opposed
to <code>.dll</code> or <code>.so</code>). The <a href="#all_modules_requireid"><code>require()</code></a> function is written to look for
files with the <code>.node</code> file extension and initialize those as dynamically-linked
libraries.</p>
<p>When calling <a href="#all_modules_requireid"><code>require()</code></a>, the <code>.node</code> extension can usually be
omitted and Node.js will still find and initialize the addon. One caveat,
however, is that Node.js will first attempt to locate and load modules or
JavaScript files that happen to share the same base name. For instance, if
there is a file <code>addon.js</code> in the same directory as the binary <code>addon.node</code>,
then <a href="#all_modules_requireid"><code>require('addon')</code></a> will give precedence to the <code>addon.js</code> file
and load it instead.</p>
</section><section><h3>Native abstractions for Node.js<span><a class="mark" href="#all_addons_native-abstractions-for-nodejs" id="all_addons_native-abstractions-for-nodejs">#</a></span><a aria-hidden="true" class="legacy" id="addons_native_abstractions_for_node_js"></a></h3>
<p>Each of the examples illustrated in this document directly use the
Node.js and V8 APIs for implementing addons. The V8 API can, and has, changed
dramatically from one V8 release to the next (and one major Node.js release to
the next). With each change, addons may need to be updated and recompiled in
order to continue functioning. The Node.js release schedule is designed to
minimize the frequency and impact of such changes but there is little that
Node.js can do to ensure stability of the V8 APIs.</p>
<p>The <a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a> (or <code>nan</code>) provide a set of tools that
addon developers are recommended to use to keep compatibility between past and
future releases of V8 and Node.js. See the <code>nan</code> <a href="https://github.com/nodejs/nan/tree/HEAD/examples/">examples</a> for an
illustration of how it can be used.</p>
</section><section><h3>Node-API<span><a class="mark" href="#all_addons_node-api" id="all_addons_node-api">#</a></span><a aria-hidden="true" class="legacy" id="addons_node_api"></a></h3>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Node-API is an API for building native addons. It is independent from
the underlying JavaScript runtime (e.g. V8) and is maintained as part of
Node.js itself. This API will be Application Binary Interface (ABI) stable
across versions of Node.js. It is intended to insulate addons from
changes in the underlying JavaScript engine and allow modules
compiled for one version to run on later versions of Node.js without
recompilation. Addons are built/packaged with the same approach/tools
outlined in this document (node-gyp, etc.). The only difference is the
set of APIs that are used by the native code. Instead of using the V8
or <a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a> APIs, the functions available
in the Node-API are used.</p>
<p>Creating and maintaining an addon that benefits from the ABI stability
provided by Node-API carries with it certain
<a href="#all_n-api_implications-of-abi-stability">implementation considerations</a>.</p>
<p>To use Node-API in the above "Hello world" example, replace the content of
<code>hello.cc</code> with the following. All other instructions remain the same.</p>
<pre><code class="language-cpp"><span class="hljs-comment">// hello.cc using Node-API</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_api.h></span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-function">napi_value <span class="hljs-title">Method</span><span class="hljs-params">(napi_env env, napi_callback_info args)</span> </span>{
napi_value greeting;
napi_status status;
status = <span class="hljs-built_in">napi_create_string_utf8</span>(env, <span class="hljs-string">"world"</span>, NAPI_AUTO_LENGTH, &greeting);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">nullptr</span>;
<span class="hljs-keyword">return</span> greeting;
}
<span class="hljs-function">napi_value <span class="hljs-title">init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> </span>{
napi_status status;
napi_value fn;
status = <span class="hljs-built_in">napi_create_function</span>(env, <span class="hljs-literal">nullptr</span>, <span class="hljs-number">0</span>, Method, <span class="hljs-literal">nullptr</span>, &fn);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">nullptr</span>;
status = <span class="hljs-built_in">napi_set_named_property</span>(env, exports, <span class="hljs-string">"hello"</span>, fn);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">nullptr</span>;
<span class="hljs-keyword">return</span> exports;
}
<span class="hljs-built_in">NAPI_MODULE</span>(NODE_GYP_MODULE_NAME, init)
} <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>The functions available and how to use them are documented in
<a href="n-api.html">C/C++ addons with Node-API</a>.</p>
</section><section><h3>Addon examples<span><a class="mark" href="#all_addons_addon-examples" id="all_addons_addon-examples">#</a></span><a aria-hidden="true" class="legacy" id="addons_addon_examples"></a></h3>
<p>Following are some example addons intended to help developers get started. The
examples use the V8 APIs. Refer to the online <a href="https://v8docs.nodesource.com/">V8 reference</a>
for help with the various V8 calls, and V8's <a href="https://v8.dev/docs/embed">Embedder's Guide</a> for an
explanation of several concepts used such as handles, scopes, function
templates, etc.</p>
<p>Each of these examples using the following <code>binding.gyp</code> file:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"targets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"target_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"addon"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> <span class="hljs-string">"addon.cc"</span> <span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>In cases where there is more than one <code>.cc</code> file, simply add the additional
filename to the <code>sources</code> array:</p>
<pre><code class="language-json"><span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-string">"addon.cc"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"myexample.cc"</span><span class="hljs-punctuation">]</span></code> <button class="copy-button">copy</button></pre>
<p>Once the <code>binding.gyp</code> file is ready, the example addons can be configured and
built using <code>node-gyp</code>:</p>
<pre><code class="language-bash">node-gyp configure build</code> <button class="copy-button">copy</button></pre>
<h4>Function arguments<span><a class="mark" href="#all_addons_function-arguments" id="all_addons_function-arguments">#</a></span><a aria-hidden="true" class="legacy" id="addons_function_arguments"></a></h4>
<p>Addons will typically expose objects and functions that can be accessed from
JavaScript running within Node.js. When functions are invoked from JavaScript,
the input arguments and return value must be mapped to and from the C/C++
code.</p>
<p>The following example illustrates how to read function arguments passed from
JavaScript and how to return a result:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">using</span> v8::Exception;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Number;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;
<span class="hljs-comment">// This is the implementation of the "add" method</span>
<span class="hljs-comment">// Input arguments are passed using the</span>
<span class="hljs-comment">// const FunctionCallbackInfo<Value>& args struct</span>
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Add</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
<span class="hljs-comment">// Check the number of arguments passed.</span>
<span class="hljs-keyword">if</span> (args.<span class="hljs-built_in">Length</span>() < <span class="hljs-number">2</span>) {
<span class="hljs-comment">// Throw an Error that is passed back to JavaScript</span>
isolate-><span class="hljs-built_in">ThrowException</span>(Exception::<span class="hljs-built_in">TypeError</span>(
String::<span class="hljs-built_in">NewFromUtf8</span>(isolate,
<span class="hljs-string">"Wrong number of arguments"</span>).<span class="hljs-built_in">ToLocalChecked</span>()));
<span class="hljs-keyword">return</span>;
}
<span class="hljs-comment">// Check the argument types</span>
<span class="hljs-keyword">if</span> (!args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">IsNumber</span>() || !args[<span class="hljs-number">1</span>]-><span class="hljs-built_in">IsNumber</span>()) {
isolate-><span class="hljs-built_in">ThrowException</span>(Exception::<span class="hljs-built_in">TypeError</span>(
String::<span class="hljs-built_in">NewFromUtf8</span>(isolate,
<span class="hljs-string">"Wrong arguments"</span>).<span class="hljs-built_in">ToLocalChecked</span>()));
<span class="hljs-keyword">return</span>;
}
<span class="hljs-comment">// Perform the operation</span>
<span class="hljs-type">double</span> value =
args[<span class="hljs-number">0</span>].<span class="hljs-built_in">As</span><Number>()-><span class="hljs-built_in">Value</span>() + args[<span class="hljs-number">1</span>].<span class="hljs-built_in">As</span><Number>()-><span class="hljs-built_in">Value</span>();
Local<Number> num = Number::<span class="hljs-built_in">New</span>(isolate, value);
<span class="hljs-comment">// Set the return value (using the passed in</span>
<span class="hljs-comment">// FunctionCallbackInfo<Value>&)</span>
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(num);
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(Local<Object> exports)</span> </span>{
<span class="hljs-built_in">NODE_SET_METHOD</span>(exports, <span class="hljs-string">"add"</span>, Add);
}
<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Init)
} <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>Once compiled, the example addon can be required and used from within Node.js:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This should be eight:'</span>, addon.<span class="hljs-title function_">add</span>(<span class="hljs-number">3</span>, <span class="hljs-number">5</span>));</code> <button class="copy-button">copy</button></pre>
<h4>Callbacks<span><a class="mark" href="#all_addons_callbacks" id="all_addons_callbacks">#</a></span><a aria-hidden="true" class="legacy" id="addons_callbacks"></a></h4>
<p>It is common practice within addons to pass JavaScript functions to a C++
function and execute them from there. The following example illustrates how
to invoke such callbacks:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::Function;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Null;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">RunCallback</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
Local<Function> cb = Local<Function>::<span class="hljs-built_in">Cast</span>(args[<span class="hljs-number">0</span>]);
<span class="hljs-type">const</span> <span class="hljs-type">unsigned</span> argc = <span class="hljs-number">1</span>;
Local<Value> argv[argc] = {
String::<span class="hljs-built_in">NewFromUtf8</span>(isolate,
<span class="hljs-string">"hello world"</span>).<span class="hljs-built_in">ToLocalChecked</span>() };
cb-><span class="hljs-built_in">Call</span>(context, <span class="hljs-built_in">Null</span>(isolate), argc, argv).<span class="hljs-built_in">ToLocalChecked</span>();
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(Local<Object> exports, Local<Object> <span class="hljs-keyword">module</span>)</span> </span>{
<span class="hljs-built_in">NODE_SET_METHOD</span>(<span class="hljs-keyword">module</span>, <span class="hljs-string">"exports"</span>, RunCallback);
}
<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Init)
} <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>This example uses a two-argument form of <code>Init()</code> that receives the full
<code>module</code> object as the second argument. This allows the addon to completely
overwrite <code>exports</code> with a single function instead of adding the function as a
property of <code>exports</code>.</p>
<p>To test it, run the following JavaScript:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);
<span class="hljs-title function_">addon</span>(<span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg);
<span class="hljs-comment">// Prints: 'hello world'</span>
});</code> <button class="copy-button">copy</button></pre>
<p>In this example, the callback function is invoked synchronously.</p>
<h4>Object factory<span><a class="mark" href="#all_addons_object-factory" id="all_addons_object-factory">#</a></span><a aria-hidden="true" class="legacy" id="addons_object_factory"></a></h4>
<p>Addons can create and return new objects from within a C++ function as
illustrated in the following example. An object is created and returned with a
property <code>msg</code> that echoes the string passed to <code>createObject()</code>:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">CreateObject</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
Local<Object> obj = Object::<span class="hljs-built_in">New</span>(isolate);
obj-><span class="hljs-built_in">Set</span>(context,
String::<span class="hljs-built_in">NewFromUtf8</span>(isolate,
<span class="hljs-string">"msg"</span>).<span class="hljs-built_in">ToLocalChecked</span>(),
args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">ToString</span>(context).<span class="hljs-built_in">ToLocalChecked</span>())
.<span class="hljs-built_in">FromJust</span>();
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(obj);
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(Local<Object> exports, Local<Object> <span class="hljs-keyword">module</span>)</span> </span>{
<span class="hljs-built_in">NODE_SET_METHOD</span>(<span class="hljs-keyword">module</span>, <span class="hljs-string">"exports"</span>, CreateObject);
}
<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Init)
} <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>To test it in JavaScript:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);
<span class="hljs-keyword">const</span> obj1 = <span class="hljs-title function_">addon</span>(<span class="hljs-string">'hello'</span>);
<span class="hljs-keyword">const</span> obj2 = <span class="hljs-title function_">addon</span>(<span class="hljs-string">'world'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj1.<span class="hljs-property">msg</span>, obj2.<span class="hljs-property">msg</span>);
<span class="hljs-comment">// Prints: 'hello world'</span></code> <button class="copy-button">copy</button></pre>
<h4>Function factory<span><a class="mark" href="#all_addons_function-factory" id="all_addons_function-factory">#</a></span><a aria-hidden="true" class="legacy" id="addons_function_factory"></a></h4>
<p>Another common scenario is creating JavaScript functions that wrap C++
functions and returning those back to JavaScript:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::Function;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::FunctionTemplate;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyFunction</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(
isolate, <span class="hljs-string">"hello world"</span>).<span class="hljs-built_in">ToLocalChecked</span>());
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">CreateFunction</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
Local<FunctionTemplate> tpl = FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, MyFunction);
Local<Function> fn = tpl-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>();
<span class="hljs-comment">// omit this to make it anonymous</span>
fn-><span class="hljs-built_in">SetName</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(
isolate, <span class="hljs-string">"theFunction"</span>).<span class="hljs-built_in">ToLocalChecked</span>());
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(fn);
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(Local<Object> exports, Local<Object> <span class="hljs-keyword">module</span>)</span> </span>{
<span class="hljs-built_in">NODE_SET_METHOD</span>(<span class="hljs-keyword">module</span>, <span class="hljs-string">"exports"</span>, CreateFunction);
}
<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Init)
} <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>To test:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);
<span class="hljs-keyword">const</span> fn = <span class="hljs-title function_">addon</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">fn</span>());
<span class="hljs-comment">// Prints: 'hello world'</span></code> <button class="copy-button">copy</button></pre>
<h4>Wrapping C++ objects<span><a class="mark" href="#all_addons_wrapping-c-objects" id="all_addons_wrapping-c-objects">#</a></span><a aria-hidden="true" class="legacy" id="addons_wrapping_c_objects"></a></h4>
<p>It is also possible to wrap C++ objects/classes in a way that allows new
instances to be created using the JavaScript <code>new</code> operator:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">InitAll</span><span class="hljs-params">(Local<Object> exports)</span> </span>{
MyObject::<span class="hljs-built_in">Init</span>(exports);
}
<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, InitAll)
} <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>Then, in <code>myobject.h</code>, the wrapper class inherits from <code>node::ObjectWrap</code>:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// myobject.h</span>
<span class="hljs-meta">#<span class="hljs-keyword">ifndef</span> MYOBJECT_H</span>
<span class="hljs-meta">#<span class="hljs-keyword">define</span> MYOBJECT_H</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_object_wrap.h></span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyObject</span> : <span class="hljs-keyword">public</span> node::ObjectWrap {
<span class="hljs-keyword">public</span>:
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(v8::Local<v8::Object> exports)</span></span>;
<span class="hljs-keyword">private</span>:
<span class="hljs-function"><span class="hljs-keyword">explicit</span> <span class="hljs-title">MyObject</span><span class="hljs-params">(<span class="hljs-type">double</span> value = <span class="hljs-number">0</span>)</span></span>;
~<span class="hljs-built_in">MyObject</span>();
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">New</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>;
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">PlusOne</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>;
<span class="hljs-type">double</span> value_;
};
} <span class="hljs-comment">// namespace demo</span>
<span class="hljs-meta">#<span class="hljs-keyword">endif</span></span></code> <button class="copy-button">copy</button></pre>
<p>In <code>myobject.cc</code>, implement the various methods that are to be exposed.
In the following code, the method <code>plusOne()</code> is exposed by adding it to the
constructor's prototype:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// myobject.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::Function;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::FunctionTemplate;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Number;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::ObjectTemplate;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;
MyObject::<span class="hljs-built_in">MyObject</span>(<span class="hljs-type">double</span> value) : <span class="hljs-built_in">value_</span>(value) {
}
MyObject::~<span class="hljs-built_in">MyObject</span>() {
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::Init</span><span class="hljs-params">(Local<Object> exports)</span> </span>{
Isolate* isolate = exports-><span class="hljs-built_in">GetIsolate</span>();
Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
Local<ObjectTemplate> addon_data_tpl = ObjectTemplate::<span class="hljs-built_in">New</span>(isolate);
addon_data_tpl-><span class="hljs-built_in">SetInternalFieldCount</span>(<span class="hljs-number">1</span>); <span class="hljs-comment">// 1 field for the MyObject::New()</span>
Local<Object> addon_data =
addon_data_tpl-><span class="hljs-built_in">NewInstance</span>(context).<span class="hljs-built_in">ToLocalChecked</span>();
<span class="hljs-comment">// Prepare constructor template</span>
Local<FunctionTemplate> tpl = FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, New, addon_data);
tpl-><span class="hljs-built_in">SetClassName</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, <span class="hljs-string">"MyObject"</span>).<span class="hljs-built_in">ToLocalChecked</span>());
tpl-><span class="hljs-built_in">InstanceTemplate</span>()-><span class="hljs-built_in">SetInternalFieldCount</span>(<span class="hljs-number">1</span>);
<span class="hljs-comment">// Prototype</span>
<span class="hljs-built_in">NODE_SET_PROTOTYPE_METHOD</span>(tpl, <span class="hljs-string">"plusOne"</span>, PlusOne);
Local<Function> constructor = tpl-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>();
addon_data-><span class="hljs-built_in">SetInternalField</span>(<span class="hljs-number">0</span>, constructor);
exports-><span class="hljs-built_in">Set</span>(context, String::<span class="hljs-built_in">NewFromUtf8</span>(
isolate, <span class="hljs-string">"MyObject"</span>).<span class="hljs-built_in">ToLocalChecked</span>(),
constructor).<span class="hljs-built_in">FromJust</span>();
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::New</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
<span class="hljs-keyword">if</span> (args.<span class="hljs-built_in">IsConstructCall</span>()) {
<span class="hljs-comment">// Invoked as constructor: `new MyObject(...)`</span>
<span class="hljs-type">double</span> value = args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">IsUndefined</span>() ?
<span class="hljs-number">0</span> : args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">NumberValue</span>(context).<span class="hljs-built_in">FromMaybe</span>(<span class="hljs-number">0</span>);
MyObject* obj = <span class="hljs-keyword">new</span> <span class="hljs-built_in">MyObject</span>(value);
obj-><span class="hljs-built_in">Wrap</span>(args.<span class="hljs-built_in">This</span>());
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(args.<span class="hljs-built_in">This</span>());
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Invoked as plain function `MyObject(...)`, turn into construct call.</span>
<span class="hljs-type">const</span> <span class="hljs-type">int</span> argc = <span class="hljs-number">1</span>;
Local<Value> argv[argc] = { args[<span class="hljs-number">0</span>] };
Local<Function> cons =
args.<span class="hljs-built_in">Data</span>().<span class="hljs-built_in">As</span><Object>()-><span class="hljs-built_in">GetInternalField</span>(<span class="hljs-number">0</span>)
.<span class="hljs-built_in">As</span><Value>().<span class="hljs-built_in">As</span><Function>();
Local<Object> result =
cons-><span class="hljs-built_in">NewInstance</span>(context, argc, argv).<span class="hljs-built_in">ToLocalChecked</span>();
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(result);
}
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::PlusOne</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
MyObject* obj = ObjectWrap::<span class="hljs-built_in">Unwrap</span><MyObject>(args.<span class="hljs-built_in">This</span>());
obj->value_ += <span class="hljs-number">1</span>;
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(Number::<span class="hljs-built_in">New</span>(isolate, obj->value_));
}
} <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>To build this example, the <code>myobject.cc</code> file must be added to the
<code>binding.gyp</code>:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"targets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"target_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"addon"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-string">"addon.cc"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"myobject.cc"</span>
<span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Test it with:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);
<span class="hljs-keyword">const</span> obj = <span class="hljs-keyword">new</span> addon.<span class="hljs-title class_">MyObject</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 11</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 12</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 13</span></code> <button class="copy-button">copy</button></pre>
<p>The destructor for a wrapper object will run when the object is
garbage-collected. For destructor testing, there are command-line flags that
can be used to make it possible to force garbage collection. These flags are
provided by the underlying V8 JavaScript engine. They are subject to change
or removal at any time. They are not documented by Node.js or V8, and they
should never be used outside of testing.</p>
<p>During shutdown of the process or worker threads destructors are not called
by the JS engine. Therefore it's the responsibility of the user to track
these objects and ensure proper destruction to avoid resource leaks.</p>
<h4>Factory of wrapped objects<span><a class="mark" href="#all_addons_factory-of-wrapped-objects" id="all_addons_factory-of-wrapped-objects">#</a></span><a aria-hidden="true" class="legacy" id="addons_factory_of_wrapped_objects"></a></h4>
<p>Alternatively, it is possible to use a factory pattern to avoid explicitly
creating object instances using the JavaScript <code>new</code> operator:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> obj = addon.<span class="hljs-title function_">createObject</span>();
<span class="hljs-comment">// instead of:</span>
<span class="hljs-comment">// const obj = new addon.Object();</span></code> <button class="copy-button">copy</button></pre>
<p>First, the <code>createObject()</code> method is implemented in <code>addon.cc</code>:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">CreateObject</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
MyObject::<span class="hljs-built_in">NewInstance</span>(args);
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">InitAll</span><span class="hljs-params">(Local<Object> exports, Local<Object> <span class="hljs-keyword">module</span>)</span> </span>{
MyObject::<span class="hljs-built_in">Init</span>(exports-><span class="hljs-built_in">GetIsolate</span>());
<span class="hljs-built_in">NODE_SET_METHOD</span>(<span class="hljs-keyword">module</span>, <span class="hljs-string">"exports"</span>, CreateObject);
}
<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, InitAll)
} <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>In <code>myobject.h</code>, the static method <code>NewInstance()</code> is added to handle
instantiating the object. This method takes the place of using <code>new</code> in
JavaScript:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// myobject.h</span>
<span class="hljs-meta">#<span class="hljs-keyword">ifndef</span> MYOBJECT_H</span>
<span class="hljs-meta">#<span class="hljs-keyword">define</span> MYOBJECT_H</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_object_wrap.h></span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyObject</span> : <span class="hljs-keyword">public</span> node::ObjectWrap {
<span class="hljs-keyword">public</span>:
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(v8::Isolate* isolate)</span></span>;
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">NewInstance</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>;
<span class="hljs-keyword">private</span>:
<span class="hljs-function"><span class="hljs-keyword">explicit</span> <span class="hljs-title">MyObject</span><span class="hljs-params">(<span class="hljs-type">double</span> value = <span class="hljs-number">0</span>)</span></span>;
~<span class="hljs-built_in">MyObject</span>();
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">New</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>;
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">PlusOne</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>;
<span class="hljs-type">static</span> v8::Global<v8::Function> constructor;
<span class="hljs-type">double</span> value_;
};
} <span class="hljs-comment">// namespace demo</span>
<span class="hljs-meta">#<span class="hljs-keyword">endif</span></span></code> <button class="copy-button">copy</button></pre>
<p>The implementation in <code>myobject.cc</code> is similar to the previous example:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// myobject.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">using</span> node::AddEnvironmentCleanupHook;
<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::Function;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::FunctionTemplate;
<span class="hljs-keyword">using</span> v8::Global;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Number;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;
<span class="hljs-comment">// Warning! This is not thread-safe, this addon cannot be used for worker</span>
<span class="hljs-comment">// threads.</span>
Global<Function> MyObject::constructor;
MyObject::<span class="hljs-built_in">MyObject</span>(<span class="hljs-type">double</span> value) : <span class="hljs-built_in">value_</span>(value) {
}
MyObject::~<span class="hljs-built_in">MyObject</span>() {
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::Init</span><span class="hljs-params">(Isolate* isolate)</span> </span>{
<span class="hljs-comment">// Prepare constructor template</span>
Local<FunctionTemplate> tpl = FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, New);
tpl-><span class="hljs-built_in">SetClassName</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, <span class="hljs-string">"MyObject"</span>).<span class="hljs-built_in">ToLocalChecked</span>());
tpl-><span class="hljs-built_in">InstanceTemplate</span>()-><span class="hljs-built_in">SetInternalFieldCount</span>(<span class="hljs-number">1</span>);
<span class="hljs-comment">// Prototype</span>
<span class="hljs-built_in">NODE_SET_PROTOTYPE_METHOD</span>(tpl, <span class="hljs-string">"plusOne"</span>, PlusOne);
Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
constructor.<span class="hljs-built_in">Reset</span>(isolate, tpl-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>());
<span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, [](<span class="hljs-type">void</span>*) {
constructor.<span class="hljs-built_in">Reset</span>();
}, <span class="hljs-literal">nullptr</span>);
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::New</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
<span class="hljs-keyword">if</span> (args.<span class="hljs-built_in">IsConstructCall</span>()) {
<span class="hljs-comment">// Invoked as constructor: `new MyObject(...)`</span>
<span class="hljs-type">double</span> value = args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">IsUndefined</span>() ?
<span class="hljs-number">0</span> : args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">NumberValue</span>(context).<span class="hljs-built_in">FromMaybe</span>(<span class="hljs-number">0</span>);
MyObject* obj = <span class="hljs-keyword">new</span> <span class="hljs-built_in">MyObject</span>(value);
obj-><span class="hljs-built_in">Wrap</span>(args.<span class="hljs-built_in">This</span>());
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(args.<span class="hljs-built_in">This</span>());
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Invoked as plain function `MyObject(...)`, turn into construct call.</span>
<span class="hljs-type">const</span> <span class="hljs-type">int</span> argc = <span class="hljs-number">1</span>;
Local<Value> argv[argc] = { args[<span class="hljs-number">0</span>] };
Local<Function> cons = Local<Function>::<span class="hljs-built_in">New</span>(isolate, constructor);
Local<Object> instance =
cons-><span class="hljs-built_in">NewInstance</span>(context, argc, argv).<span class="hljs-built_in">ToLocalChecked</span>();
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(instance);
}
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::NewInstance</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
<span class="hljs-type">const</span> <span class="hljs-type">unsigned</span> argc = <span class="hljs-number">1</span>;
Local<Value> argv[argc] = { args[<span class="hljs-number">0</span>] };
Local<Function> cons = Local<Function>::<span class="hljs-built_in">New</span>(isolate, constructor);
Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
Local<Object> instance =
cons-><span class="hljs-built_in">NewInstance</span>(context, argc, argv).<span class="hljs-built_in">ToLocalChecked</span>();
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(instance);
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::PlusOne</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
MyObject* obj = ObjectWrap::<span class="hljs-built_in">Unwrap</span><MyObject>(args.<span class="hljs-built_in">This</span>());
obj->value_ += <span class="hljs-number">1</span>;
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(Number::<span class="hljs-built_in">New</span>(isolate, obj->value_));
}
} <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>Once again, to build this example, the <code>myobject.cc</code> file must be added to the
<code>binding.gyp</code>:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"targets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"target_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"addon"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-string">"addon.cc"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"myobject.cc"</span>
<span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Test it with:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> createObject = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);
<span class="hljs-keyword">const</span> obj = <span class="hljs-title function_">createObject</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 11</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 12</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 13</span>
<span class="hljs-keyword">const</span> obj2 = <span class="hljs-title function_">createObject</span>(<span class="hljs-number">20</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj2.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 21</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj2.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 22</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj2.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 23</span></code> <button class="copy-button">copy</button></pre>
<h4>Passing wrapped objects around<span><a class="mark" href="#all_addons_passing-wrapped-objects-around" id="all_addons_passing-wrapped-objects-around">#</a></span><a aria-hidden="true" class="legacy" id="addons_passing_wrapped_objects_around"></a></h4>
<p>In addition to wrapping and returning C++ objects, it is possible to pass
wrapped objects around by unwrapping them with the Node.js helper function
<code>node::ObjectWrap::Unwrap</code>. The following examples shows a function <code>add()</code>
that can take two <code>MyObject</code> objects as input arguments:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_object_wrap.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Number;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">CreateObject</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
MyObject::<span class="hljs-built_in">NewInstance</span>(args);
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Add</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
MyObject* obj1 = node::ObjectWrap::<span class="hljs-built_in">Unwrap</span><MyObject>(
args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">ToObject</span>(context).<span class="hljs-built_in">ToLocalChecked</span>());
MyObject* obj2 = node::ObjectWrap::<span class="hljs-built_in">Unwrap</span><MyObject>(
args[<span class="hljs-number">1</span>]-><span class="hljs-built_in">ToObject</span>(context).<span class="hljs-built_in">ToLocalChecked</span>());
<span class="hljs-type">double</span> sum = obj1-><span class="hljs-built_in">value</span>() + obj2-><span class="hljs-built_in">value</span>();
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(Number::<span class="hljs-built_in">New</span>(isolate, sum));
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">InitAll</span><span class="hljs-params">(Local<Object> exports)</span> </span>{
MyObject::<span class="hljs-built_in">Init</span>(exports-><span class="hljs-built_in">GetIsolate</span>());
<span class="hljs-built_in">NODE_SET_METHOD</span>(exports, <span class="hljs-string">"createObject"</span>, CreateObject);
<span class="hljs-built_in">NODE_SET_METHOD</span>(exports, <span class="hljs-string">"add"</span>, Add);
}
<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, InitAll)
} <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>In <code>myobject.h</code>, a new public method is added to allow access to private values
after unwrapping the object.</p>
<pre><code class="language-cpp"><span class="hljs-comment">// myobject.h</span>
<span class="hljs-meta">#<span class="hljs-keyword">ifndef</span> MYOBJECT_H</span>
<span class="hljs-meta">#<span class="hljs-keyword">define</span> MYOBJECT_H</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_object_wrap.h></span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyObject</span> : <span class="hljs-keyword">public</span> node::ObjectWrap {
<span class="hljs-keyword">public</span>:
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(v8::Isolate* isolate)</span></span>;
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">NewInstance</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">inline</span> <span class="hljs-type">double</span> <span class="hljs-title">value</span><span class="hljs-params">()</span> <span class="hljs-type">const</span> </span>{ <span class="hljs-keyword">return</span> value_; }
<span class="hljs-keyword">private</span>:
<span class="hljs-function"><span class="hljs-keyword">explicit</span> <span class="hljs-title">MyObject</span><span class="hljs-params">(<span class="hljs-type">double</span> value = <span class="hljs-number">0</span>)</span></span>;
~<span class="hljs-built_in">MyObject</span>();
<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">New</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo<v8::Value>& args)</span></span>;
<span class="hljs-type">static</span> v8::Global<v8::Function> constructor;
<span class="hljs-type">double</span> value_;
};
} <span class="hljs-comment">// namespace demo</span>
<span class="hljs-meta">#<span class="hljs-keyword">endif</span></span></code> <button class="copy-button">copy</button></pre>
<p>The implementation of <code>myobject.cc</code> remains similar to the previous version:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// myobject.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span>
<span class="hljs-keyword">namespace</span> demo {
<span class="hljs-keyword">using</span> node::AddEnvironmentCleanupHook;
<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::Function;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::FunctionTemplate;
<span class="hljs-keyword">using</span> v8::Global;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;
<span class="hljs-comment">// Warning! This is not thread-safe, this addon cannot be used for worker</span>
<span class="hljs-comment">// threads.</span>
Global<Function> MyObject::constructor;
MyObject::<span class="hljs-built_in">MyObject</span>(<span class="hljs-type">double</span> value) : <span class="hljs-built_in">value_</span>(value) {
}
MyObject::~<span class="hljs-built_in">MyObject</span>() {
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::Init</span><span class="hljs-params">(Isolate* isolate)</span> </span>{
<span class="hljs-comment">// Prepare constructor template</span>
Local<FunctionTemplate> tpl = FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, New);
tpl-><span class="hljs-built_in">SetClassName</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, <span class="hljs-string">"MyObject"</span>).<span class="hljs-built_in">ToLocalChecked</span>());
tpl-><span class="hljs-built_in">InstanceTemplate</span>()-><span class="hljs-built_in">SetInternalFieldCount</span>(<span class="hljs-number">1</span>);
Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
constructor.<span class="hljs-built_in">Reset</span>(isolate, tpl-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>());
<span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, [](<span class="hljs-type">void</span>*) {
constructor.<span class="hljs-built_in">Reset</span>();
}, <span class="hljs-literal">nullptr</span>);
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::New</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
<span class="hljs-keyword">if</span> (args.<span class="hljs-built_in">IsConstructCall</span>()) {
<span class="hljs-comment">// Invoked as constructor: `new MyObject(...)`</span>
<span class="hljs-type">double</span> value = args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">IsUndefined</span>() ?
<span class="hljs-number">0</span> : args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">NumberValue</span>(context).<span class="hljs-built_in">FromMaybe</span>(<span class="hljs-number">0</span>);
MyObject* obj = <span class="hljs-keyword">new</span> <span class="hljs-built_in">MyObject</span>(value);
obj-><span class="hljs-built_in">Wrap</span>(args.<span class="hljs-built_in">This</span>());
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(args.<span class="hljs-built_in">This</span>());
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Invoked as plain function `MyObject(...)`, turn into construct call.</span>
<span class="hljs-type">const</span> <span class="hljs-type">int</span> argc = <span class="hljs-number">1</span>;
Local<Value> argv[argc] = { args[<span class="hljs-number">0</span>] };
Local<Function> cons = Local<Function>::<span class="hljs-built_in">New</span>(isolate, constructor);
Local<Object> instance =
cons-><span class="hljs-built_in">NewInstance</span>(context, argc, argv).<span class="hljs-built_in">ToLocalChecked</span>();
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(instance);
}
}
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::NewInstance</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo<Value>& args)</span> </span>{
Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
<span class="hljs-type">const</span> <span class="hljs-type">unsigned</span> argc = <span class="hljs-number">1</span>;
Local<Value> argv[argc] = { args[<span class="hljs-number">0</span>] };
Local<Function> cons = Local<Function>::<span class="hljs-built_in">New</span>(isolate, constructor);
Local<Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
Local<Object> instance =
cons-><span class="hljs-built_in">NewInstance</span>(context, argc, argv).<span class="hljs-built_in">ToLocalChecked</span>();
args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(instance);
}
} <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>Test it with:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);
<span class="hljs-keyword">const</span> obj1 = addon.<span class="hljs-title function_">createObject</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> obj2 = addon.<span class="hljs-title function_">createObject</span>(<span class="hljs-number">20</span>);
<span class="hljs-keyword">const</span> result = addon.<span class="hljs-title function_">add</span>(obj1, obj2);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
<span class="hljs-comment">// Prints: 30</span></code> <button class="copy-button">copy</button></pre></section>
</section>
<section><h2>Node-API<span><a class="mark" href="#all_n-api_node-api" id="all_n-api_node-api">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Node-API (formerly N-API) is an API for building native Addons. It is
independent from the underlying JavaScript runtime (for example, V8) and is
maintained as part of Node.js itself. This API will be Application Binary
Interface (ABI) stable across versions of Node.js. It is intended to insulate
addons from changes in the underlying JavaScript engine and allow modules
compiled for one major version to run on later major versions of Node.js without
recompilation. The <a href="https://nodejs.org/en/docs/guides/abi-stability/">ABI Stability</a> guide provides a more in-depth explanation.</p>
<p>Addons are built/packaged with the same approach/tools outlined in the section
titled <a href="addons.html">C++ Addons</a>. The only difference is the set of APIs that are used by
the native code. Instead of using the V8 or <a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a>
APIs, the functions available in Node-API are used.</p>
<p>APIs exposed by Node-API are generally used to create and manipulate
JavaScript values. Concepts and operations generally map to ideas specified
in the ECMA-262 Language Specification. The APIs have the following
properties:</p>
<ul>
<li>All Node-API calls return a status code of type <code>napi_status</code>. This
status indicates whether the API call succeeded or failed.</li>
<li>The API's return value is passed via an out parameter.</li>
<li>All JavaScript values are abstracted behind an opaque type named
<code>napi_value</code>.</li>
<li>In case of an error status code, additional information can be obtained
using <code>napi_get_last_error_info</code>. More information can be found in the error
handling section <a href="#all_n-api_error-handling">Error handling</a>.</li>
</ul>
<p>Node-API is a C API that ensures ABI stability across Node.js versions
and different compiler levels. A C++ API can be easier to use.
To support using C++, the project maintains a
C++ wrapper module called <a href="https://github.com/nodejs/node-addon-api"><code>node-addon-api</code></a>.
This wrapper provides an inlinable C++ API. Binaries built
with <code>node-addon-api</code> will depend on the symbols for the Node-API C-based
functions exported by Node.js. <code>node-addon-api</code> is a more
efficient way to write code that calls Node-API. Take, for example, the
following <code>node-addon-api</code> code. The first section shows the
<code>node-addon-api</code> code and the second section shows what actually gets
used in the addon.</p>
<pre><code class="language-cpp">Object obj = Object::<span class="hljs-built_in">New</span>(env);
obj[<span class="hljs-string">"foo"</span>] = String::<span class="hljs-built_in">New</span>(env, <span class="hljs-string">"bar"</span>);</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-cpp">napi_status status;
napi_value object, string;
status = <span class="hljs-built_in">napi_create_object</span>(env, &object);
<span class="hljs-keyword">if</span> (status != napi_ok) {
<span class="hljs-built_in">napi_throw_error</span>(env, ...);
<span class="hljs-keyword">return</span>;
}
status = <span class="hljs-built_in">napi_create_string_utf8</span>(env, <span class="hljs-string">"bar"</span>, NAPI_AUTO_LENGTH, &string);
<span class="hljs-keyword">if</span> (status != napi_ok) {
<span class="hljs-built_in">napi_throw_error</span>(env, ...);
<span class="hljs-keyword">return</span>;
}
status = <span class="hljs-built_in">napi_set_named_property</span>(env, object, <span class="hljs-string">"foo"</span>, string);
<span class="hljs-keyword">if</span> (status != napi_ok) {
<span class="hljs-built_in">napi_throw_error</span>(env, ...);
<span class="hljs-keyword">return</span>;
}</code> <button class="copy-button">copy</button></pre>
<p>The end result is that the addon only uses the exported C APIs. As a result,
it still gets the benefits of the ABI stability provided by the C API.</p>
<p>When using <code>node-addon-api</code> instead of the C APIs, start with the API <a href="https://github.com/nodejs/node-addon-api#api-documentation">docs</a>
for <code>node-addon-api</code>.</p>
<p>The <a href="https://nodejs.github.io/node-addon-examples/">Node-API Resource</a> offers
an excellent orientation and tips for developers just getting started with
Node-API and <code>node-addon-api</code>. Additional media resources can be found on the
<a href="https://github.com/nodejs/abi-stable-node/blob/HEAD/node-api-media.md">Node-API Media</a> page.</p>
<section><h3>Implications of ABI stability<span><a class="mark" href="#all_n-api_implications-of-abi-stability" id="all_n-api_implications-of-abi-stability">#</a></span><a aria-hidden="true" class="legacy" id="n_api_implications_of_abi_stability"></a></h3>
<p>Although Node-API provides an ABI stability guarantee, other parts of Node.js do
not, and any external libraries used from the addon may not. In particular,
none of the following APIs provide an ABI stability guarantee across major
versions:</p>
<ul>
<li>
<p>the Node.js C++ APIs available via any of</p>
<pre><code class="language-cpp"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_buffer.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_version.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_object_wrap.h></span></span></code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>the libuv APIs which are also included with Node.js and available via</p>
<pre><code class="language-cpp"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><uv.h></span></span></code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>the V8 API available via</p>
<pre><code class="language-cpp"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><v8.h></span></span></code> <button class="copy-button">copy</button></pre>
</li>
</ul>
<p>Thus, for an addon to remain ABI-compatible across Node.js major versions, it
must use Node-API exclusively by restricting itself to using</p>
<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_api.h></span></span></code> <button class="copy-button">copy</button></pre>
<p>and by checking, for all external libraries that it uses, that the external
library makes ABI stability guarantees similar to Node-API.</p>
</section><section><h3>Building<span><a class="mark" href="#all_n-api_building" id="all_n-api_building">#</a></span><a aria-hidden="true" class="legacy" id="n_api_building"></a></h3>
<p>Unlike modules written in JavaScript, developing and deploying Node.js
native addons using Node-API requires an additional set of tools. Besides the
basic tools required to develop for Node.js, the native addon developer
requires a toolchain that can compile C and C++ code into a binary. In
addition, depending upon how the native addon is deployed, the <em>user</em> of
the native addon will also need to have a C/C++ toolchain installed.</p>
<p>For Linux developers, the necessary C/C++ toolchain packages are readily
available. <a href="https://gcc.gnu.org">GCC</a> is widely used in the Node.js community to build and
test across a variety of platforms. For many developers, the <a href="https://llvm.org">LLVM</a>
compiler infrastructure is also a good choice.</p>
<p>For Mac developers, <a href="https://developer.apple.com/xcode/">Xcode</a> offers all the required compiler tools.
However, it is not necessary to install the entire Xcode IDE. The following
command installs the necessary toolchain:</p>
<pre><code class="language-bash">xcode-select --install</code> <button class="copy-button">copy</button></pre>
<p>For Windows developers, <a href="https://visualstudio.microsoft.com">Visual Studio</a> offers all the required compiler
tools. However, it is not necessary to install the entire Visual Studio
IDE. The following command installs the necessary toolchain:</p>
<pre><code class="language-bash">npm install --global windows-build-tools</code> <button class="copy-button">copy</button></pre>
<p>The sections below describe the additional tools available for developing
and deploying Node.js native addons.</p>
<h4>Build tools<span><a class="mark" href="#all_n-api_build-tools" id="all_n-api_build-tools">#</a></span><a aria-hidden="true" class="legacy" id="n_api_build_tools"></a></h4>
<p>Both the tools listed here require that <em>users</em> of the native
addon have a C/C++ toolchain installed in order to successfully install
the native addon.</p>
<h5>node-gyp<span><a class="mark" href="#all_n-api_node-gyp" id="all_n-api_node-gyp">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_gyp"></a></h5>
<p><a href="https://github.com/nodejs/node-gyp">node-gyp</a> is a build system based on the <a href="https://github.com/nodejs/gyp-next">gyp-next</a> fork of
Google's <a href="https://gyp.gsrc.io">GYP</a> tool and comes bundled with npm. GYP, and therefore node-gyp,
requires that Python be installed.</p>
<p>Historically, node-gyp has been the tool of choice for building native
addons. It has widespread adoption and documentation. However, some
developers have run into limitations in node-gyp.</p>
<h5>CMake.js<span><a class="mark" href="#all_n-api_cmakejs" id="all_n-api_cmakejs">#</a></span><a aria-hidden="true" class="legacy" id="n_api_cmake_js"></a></h5>
<p><a href="https://github.com/cmake-js/cmake-js">CMake.js</a> is an alternative build system based on <a href="https://cmake.org">CMake</a>.</p>
<p>CMake.js is a good choice for projects that already use CMake or for
developers affected by limitations in node-gyp. <a href="https://github.com/nodejs/node-addon-examples/tree/main/src/8-tooling/build_with_cmake"><code>build_with_cmake</code></a> is an
example of a CMake-based native addon project.</p>
<h4>Uploading precompiled binaries<span><a class="mark" href="#all_n-api_uploading-precompiled-binaries" id="all_n-api_uploading-precompiled-binaries">#</a></span><a aria-hidden="true" class="legacy" id="n_api_uploading_precompiled_binaries"></a></h4>
<p>The three tools listed here permit native addon developers and maintainers
to create and upload binaries to public or private servers. These tools are
typically integrated with CI/CD build systems like <a href="https://travis-ci.org">Travis CI</a> and
<a href="https://www.appveyor.com">AppVeyor</a> to build and upload binaries for a variety of platforms and
architectures. These binaries are then available for download by users who
do not need to have a C/C++ toolchain installed.</p>
<h5>node-pre-gyp<span><a class="mark" href="#all_n-api_node-pre-gyp" id="all_n-api_node-pre-gyp">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_pre_gyp"></a></h5>
<p><a href="https://github.com/mapbox/node-pre-gyp">node-pre-gyp</a> is a tool based on node-gyp that adds the ability to
upload binaries to a server of the developer's choice. node-pre-gyp has
particularly good support for uploading binaries to Amazon S3.</p>
<h5>prebuild<span><a class="mark" href="#all_n-api_prebuild" id="all_n-api_prebuild">#</a></span><a aria-hidden="true" class="legacy" id="n_api_prebuild"></a></h5>
<p><a href="https://github.com/prebuild/prebuild">prebuild</a> is a tool that supports builds using either node-gyp or
CMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild
uploads binaries only to <a href="https://help.github.com/en/github/administering-a-repository/about-releases">GitHub releases</a>. prebuild is a good choice for
GitHub projects using CMake.js.</p>
<h5>prebuildify<span><a class="mark" href="#all_n-api_prebuildify" id="all_n-api_prebuildify">#</a></span><a aria-hidden="true" class="legacy" id="n_api_prebuildify"></a></h5>
<p><a href="https://github.com/prebuild/prebuildify">prebuildify</a> is a tool based on node-gyp. The advantage of prebuildify is
that the built binaries are bundled with the native addon when it's
uploaded to npm. The binaries are downloaded from npm and are immediately
available to the module user when the native addon is installed.</p>
</section><section><h3>Usage<span><a class="mark" href="#all_n-api_usage" id="all_n-api_usage">#</a></span><a aria-hidden="true" class="legacy" id="n_api_usage"></a></h3>
<p>In order to use the Node-API functions, include the file <a href="https://github.com/nodejs/node/blob/HEAD/src/node_api.h"><code>node_api.h</code></a> which
is located in the src directory in the node development tree:</p>
<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_api.h></span></span></code> <button class="copy-button">copy</button></pre>
<p>This will opt into the default <code>NAPI_VERSION</code> for the given release of Node.js.
In order to ensure compatibility with specific versions of Node-API, the version
can be specified explicitly when including the header:</p>
<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> NAPI_VERSION 3</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_api.h></span></span></code> <button class="copy-button">copy</button></pre>
<p>This restricts the Node-API surface to just the functionality that was available
in the specified (and earlier) versions.</p>
<p>Some of the Node-API surface is experimental and requires explicit opt-in:</p>
<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> NAPI_EXPERIMENTAL</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_api.h></span></span></code> <button class="copy-button">copy</button></pre>
<p>In this case the entire API surface, including any experimental APIs, will be
available to the module code.</p>
<p>Occasionally, experimental features are introduced that affect already-released
and stable APIs. These features can be disabled by an opt-out:</p>
<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> NAPI_EXPERIMENTAL</span>
<span class="hljs-meta">#<span class="hljs-keyword">define</span> NODE_API_EXPERIMENTAL_<span class="hljs-string"><FEATURE_NAME></span>_OPT_OUT</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_api.h></span></span></code> <button class="copy-button">copy</button></pre>
<p>where <code><FEATURE_NAME></code> is the name of an experimental feature that affects both
experimental and stable APIs.</p>
</section><section><h3>Node-API version matrix<span><a class="mark" href="#all_n-api_node-api-version-matrix" id="all_n-api_node-api-version-matrix">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_version_matrix"></a></h3>
<p>Up until version 9, Node-API versions were additive and versioned
independently from Node.js. This meant that any version was
an extension to the previous version in that it had all of
the APIs from the previous version with some additions. Each
Node.js version only supported a single Node-API version.
For example v18.15.0 supports only Node-API version 8. ABI stability was
achieved because 8 was a strict superset of all previous versions.</p>
<p>As of version 9, while Node-API versions continue to be versioned
independently an add-on that ran with Node-API version 9 may need
code updates to run with Node-API version 10. ABI stability
is maintained, however, because Node.js versions that support
Node-API versions higher than 8 will support all versions
between 8 and the highest version they support and will default
to providing the version 8 APIs unless an add-on opts into a
higher Node-API version. This approach provides the flexibility
of better optimizing existing Node-API functions while
maintaining ABI stability. Existing add-ons can continue to run without
recompilation using an earlier version of Node-API. If an add-on
needs functionality from a newer Node-API version, changes to existing
code and recompilation will be needed to use those new functions anyway.</p>
<p>In versions of Node.js that support Node-API version 9 and later, defining
<code>NAPI_VERSION=X</code> and using the existing add-on initialization macros
will bake in the requested Node-API version that will be used at runtime
into the add-on. If <code>NAPI_VERSION</code> is not set it will default to 8.</p>
<p>This table may not be up to date in older streams, the most up to date
information is in the latest API documentation in:
<a href="https://nodejs.org/docs/latest/api/n-api.html#node-api-version-matrix">Node-API version matrix</a></p>
<!-- For accessibility purposes, this table needs row headers. That means we
can't do it in markdown. Hence, the raw HTML. -->
<table>
<tbody><tr>
<th>Node-API version</th>
<th scope="col">Supported In</th>
</tr>
<tr>
<th scope="row">9</th>
<td>v18.17.0+, 20.3.0+, 21.0.0 and all later versions</td>
</tr>
<tr>
<th scope="row">8</th>
<td>v12.22.0+, v14.17.0+, v15.12.0+, 16.0.0 and all later versions</td>
</tr>
<tr>
<th scope="row">7</th>
<td>v10.23.0+, v12.19.0+, v14.12.0+, 15.0.0 and all later versions</td>
</tr>
<tr>
<th scope="row">6</th>
<td>v10.20.0+, v12.17.0+, 14.0.0 and all later versions</td>
</tr>
<tr>
<th scope="row">5</th>
<td>v10.17.0+, v12.11.0+, 13.0.0 and all later versions</td>
</tr>
<tr>
<th scope="row">4</th>
<td>v10.16.0+, v11.8.0+, 12.0.0 and all later versions</td>
</tr>
<tr>
<th scope="row">3</th>
<td>v6.14.2*, 8.11.2+, v9.11.0+*, 10.0.0 and all later versions</td>
</tr>
<tr>
<th scope="row">2</th>
<td>v8.10.0+*, v9.3.0+*, 10.0.0 and all later versions</td>
</tr>
<tr>
<th scope="row">1</th>
<td>v8.6.0+**, v9.0.0+*, 10.0.0 and all later versions</td>
</tr>
</tbody></table>
<p>* Node-API was experimental.</p>
<p>** Node.js 8.0.0 included Node-API as experimental. It was released as
Node-API version 1 but continued to evolve until Node.js 8.6.0. The API is
different in versions prior to Node.js 8.6.0. We recommend Node-API version 3 or
later.</p>
<p>Each API documented for Node-API will have a header named <code>added in:</code>, and APIs
which are stable will have the additional header <code>Node-API version:</code>.
APIs are directly usable when using a Node.js version which supports
the Node-API version shown in <code>Node-API version:</code> or higher.
When using a Node.js version that does not support the
<code>Node-API version:</code> listed or if there is no <code>Node-API version:</code> listed,
then the API will only be available if
<code>#define NAPI_EXPERIMENTAL</code> precedes the inclusion of <code>node_api.h</code>
or <code>js_native_api.h</code>. If an API appears not to be available on
a version of Node.js which is later than the one shown in <code>added in:</code> then
this is most likely the reason for the apparent absence.</p>
<p>The Node-APIs associated strictly with accessing ECMAScript features from native
code can be found separately in <code>js_native_api.h</code> and <code>js_native_api_types.h</code>.
The APIs defined in these headers are included in <code>node_api.h</code> and
<code>node_api_types.h</code>. The headers are structured in this way in order to allow
implementations of Node-API outside of Node.js. For those implementations the
Node.js specific APIs may not be applicable.</p>
<p>The Node.js-specific parts of an addon can be separated from the code that
exposes the actual functionality to the JavaScript environment so that the
latter may be used with multiple implementations of Node-API. In the example
below, <code>addon.c</code> and <code>addon.h</code> refer only to <code>js_native_api.h</code>. This ensures
that <code>addon.c</code> can be reused to compile against either the Node.js
implementation of Node-API or any implementation of Node-API outside of Node.js.</p>
<p><code>addon_node.c</code> is a separate file that contains the Node.js specific entry point
to the addon and which instantiates the addon by calling into <code>addon.c</code> when the
addon is loaded into a Node.js environment.</p>
<pre><code class="language-c"><span class="hljs-comment">// addon.h</span>
<span class="hljs-meta">#<span class="hljs-keyword">ifndef</span> _ADDON_H_</span>
<span class="hljs-meta">#<span class="hljs-keyword">define</span> _ADDON_H_</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><js_native_api.h></span></span>
napi_value <span class="hljs-title function_">create_addon</span><span class="hljs-params">(napi_env env)</span>;
<span class="hljs-meta">#<span class="hljs-keyword">endif</span> <span class="hljs-comment">// _ADDON_H_</span></span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-c"><span class="hljs-comment">// addon.c</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"addon.h"</span></span>
<span class="hljs-meta">#<span class="hljs-keyword">define</span> NODE_API_CALL(env, call) \
do { \
napi_status status = (call); \
<span class="hljs-keyword">if</span> (status != napi_ok) { \
const napi_extended_error_info* error_info = NULL; \
napi_get_last_error_info((env), &error_info); \
const char* err_message = error_info->error_message; \
bool is_pending; \
napi_is_exception_pending((env), &is_pending); \
<span class="hljs-comment">/* If an exception is already pending, don't rethrow it */</span> \
<span class="hljs-keyword">if</span> (!is_pending) { \
const char* message = (err_message == NULL) \
? <span class="hljs-string">"empty error message"</span> \
: err_message; \
napi_throw_error((env), NULL, message); \
} \
return NULL; \
} \
} while(0)</span>
<span class="hljs-type">static</span> napi_value
<span class="hljs-title function_">DoSomethingUseful</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
<span class="hljs-comment">// Do something useful.</span>
<span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
}
napi_value <span class="hljs-title function_">create_addon</span><span class="hljs-params">(napi_env env)</span> {
napi_value result;
NODE_API_CALL(env, napi_create_object(env, &result));
napi_value exported_function;
NODE_API_CALL(env, napi_create_function(env,
<span class="hljs-string">"doSomethingUseful"</span>,
NAPI_AUTO_LENGTH,
DoSomethingUseful,
<span class="hljs-literal">NULL</span>,
&exported_function));
NODE_API_CALL(env, napi_set_named_property(env,
result,
<span class="hljs-string">"doSomethingUseful"</span>,
exported_function));
<span class="hljs-keyword">return</span> result;
}</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-c"><span class="hljs-comment">// addon_node.c</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><node_api.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"addon.h"</span></span>
NAPI_MODULE_INIT(<span class="hljs-comment">/* napi_env env, napi_value exports */</span>) {
<span class="hljs-comment">// This function body is expected to return a `napi_value`.</span>
<span class="hljs-comment">// The variables `napi_env env` and `napi_value exports` may be used within</span>
<span class="hljs-comment">// the body, as they are provided by the definition of `NAPI_MODULE_INIT()`.</span>
<span class="hljs-keyword">return</span> create_addon(env);
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Environment life cycle APIs<span><a class="mark" href="#all_n-api_environment-life-cycle-apis" id="all_n-api_environment-life-cycle-apis">#</a></span><a aria-hidden="true" class="legacy" id="n_api_environment_life_cycle_apis"></a></h3>
<p><a href="https://tc39.es/ecma262/#sec-agents">Section 8.7</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a> defines the concept
of an "Agent" as a self-contained environment in which JavaScript code runs.
Multiple such Agents may be started and terminated either concurrently or in
sequence by the process.</p>
<p>A Node.js environment corresponds to an ECMAScript Agent. In the main process,
an environment is created at startup, and additional environments can be created
on separate threads to serve as <a href="https://nodejs.org/api/worker_threads.html">worker threads</a>. When Node.js is embedded in
another application, the main thread of the application may also construct and
destroy a Node.js environment multiple times during the life cycle of the
application process such that each Node.js environment created by the
application may, in turn, during its life cycle create and destroy additional
environments as worker threads.</p>
<p>From the perspective of a native addon this means that the bindings it provides
may be called multiple times, from multiple contexts, and even concurrently from
multiple threads.</p>
<p>Native addons may need to allocate global state which they use during
their life cycle of an Node.js environment such that the state can be
unique to each instance of the addon.</p>
<p>To this end, Node-API provides a way to associate data such that its life cycle
is tied to the life cycle of a Node.js environment.</p>
<h4><code>napi_set_instance_data</code><span><a class="mark" href="#all_n-api_napi_set_instance_data" id="all_n-api_napi_set_instance_data">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_set_instance_data"></a></h4>
<div class="api_metadata">
<span>Added in: v12.8.0, v10.20.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_set_instance_data</span><span class="hljs-params">(node_api_basic_env env,
<span class="hljs-type">void</span>* data,
napi_finalize finalize_cb,
<span class="hljs-type">void</span>* finalize_hint)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] data</code>: The data item to make available to bindings of this instance.</li>
<li><code>[in] finalize_cb</code>: The function to call when the environment is being torn
down. The function receives <code>data</code> so that it might free it.
<a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
collection.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API associates <code>data</code> with the currently running Node.js environment. <code>data</code>
can later be retrieved using <code>napi_get_instance_data()</code>. Any existing data
associated with the currently running Node.js environment which was set by means
of a previous call to <code>napi_set_instance_data()</code> will be overwritten. If a
<code>finalize_cb</code> was provided by the previous call, it will not be called.</p>
<h4><code>napi_get_instance_data</code><span><a class="mark" href="#all_n-api_napi_get_instance_data" id="all_n-api_napi_get_instance_data">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_instance_data"></a></h4>
<div class="api_metadata">
<span>Added in: v12.8.0, v10.20.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_instance_data</span><span class="hljs-params">(node_api_basic_env env,
<span class="hljs-type">void</span>** data)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[out] data</code>: The data item that was previously associated with the currently
running Node.js environment by a call to <code>napi_set_instance_data()</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API retrieves data that was previously associated with the currently
running Node.js environment via <code>napi_set_instance_data()</code>. If no data is set,
the call will succeed and <code>data</code> will be set to <code>NULL</code>.</p>
</section><section><h3>Basic Node-API data types<span><a class="mark" href="#all_n-api_basic-node-api-data-types" id="all_n-api_basic-node-api-data-types">#</a></span><a aria-hidden="true" class="legacy" id="n_api_basic_node_api_data_types"></a></h3>
<p>Node-API exposes the following fundamental data types as abstractions that are
consumed by the various APIs. These APIs should be treated as opaque,
introspectable only with other Node-API calls.</p>
<h4><code>napi_status</code><span><a class="mark" href="#all_n-api_napi_status" id="all_n-api_napi_status">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_status"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>Integral status code indicating the success or failure of a Node-API call.
Currently, the following status codes are supported.</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
napi_ok,
napi_invalid_arg,
napi_object_expected,
napi_string_expected,
napi_name_expected,
napi_function_expected,
napi_number_expected,
napi_boolean_expected,
napi_array_expected,
napi_generic_failure,
napi_pending_exception,
napi_cancelled,
napi_escape_called_twice,
napi_handle_scope_mismatch,
napi_callback_scope_mismatch,
napi_queue_full,
napi_closing,
napi_bigint_expected,
napi_date_expected,
napi_arraybuffer_expected,
napi_detachable_arraybuffer_expected,
napi_would_deadlock, <span class="hljs-comment">/* unused */</span>
napi_no_external_buffers_allowed,
napi_cannot_run_js
} napi_status;</code> <button class="copy-button">copy</button></pre>
<p>If additional information is required upon an API returning a failed status,
it can be obtained by calling <code>napi_get_last_error_info</code>.</p>
<h4><code>napi_extended_error_info</code><span><a class="mark" href="#all_n-api_napi_extended_error_info" id="all_n-api_napi_extended_error_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_extended_error_info"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* error_message;
<span class="hljs-type">void</span>* engine_reserved;
<span class="hljs-type">uint32_t</span> engine_error_code;
napi_status error_code;
} napi_extended_error_info;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>error_message</code>: UTF8-encoded string containing a VM-neutral description of
the error.</li>
<li><code>engine_reserved</code>: Reserved for VM-specific error details. This is currently
not implemented for any VM.</li>
<li><code>engine_error_code</code>: VM-specific error code. This is currently
not implemented for any VM.</li>
<li><code>error_code</code>: The Node-API status code that originated with the last error.</li>
</ul>
<p>See the <a href="#all_n-api_error-handling">Error handling</a> section for additional information.</p>
<h4><code>napi_env</code><span><a class="mark" href="#all_n-api_napi_env" id="all_n-api_napi_env">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_env"></a></h4>
<p><code>napi_env</code> is used to represent a context that the underlying Node-API
implementation can use to persist VM-specific state. This structure is passed
to native functions when they're invoked, and it must be passed back when
making Node-API calls. Specifically, the same <code>napi_env</code> that was passed in when
the initial native function was called must be passed to any subsequent
nested Node-API calls. Caching the <code>napi_env</code> for the purpose of general reuse,
and passing the <code>napi_env</code> between instances of the same addon running on
different <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads is not allowed. The <code>napi_env</code> becomes invalid
when an instance of a native addon is unloaded. Notification of this event is
delivered through the callbacks given to <a href="#all_n-api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a> and
<a href="#all_n-api_napi_set_instance_data"><code>napi_set_instance_data</code></a>.</p>
<h4><code>node_api_basic_env</code><span><a class="mark" href="#all_n-api_node_api_basic_env" id="all_n-api_node_api_basic_env">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_basic_env"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>This variant of <code>napi_env</code> is passed to synchronous finalizers
(<a href="#all_n-api_node_api_basic_finalize"><code>node_api_basic_finalize</code></a>). There is a subset of Node-APIs which accept
a parameter of type <code>node_api_basic_env</code> as their first argument. These APIs do
not access the state of the JavaScript engine and are thus safe to call from
synchronous finalizers. Passing a parameter of type <code>napi_env</code> to these APIs is
allowed, however, passing a parameter of type <code>node_api_basic_env</code> to APIs that
access the JavaScript engine state is not allowed. Attempting to do so without
a cast will produce a compiler warning or an error when add-ons are compiled
with flags which cause them to emit warnings and/or errors when incorrect
pointer types are passed into a function. Calling such APIs from a synchronous
finalizer will ultimately result in the termination of the application.</p>
<h4><code>napi_value</code><span><a class="mark" href="#all_n-api_napi_value" id="all_n-api_napi_value">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_value"></a></h4>
<p>This is an opaque pointer that is used to represent a JavaScript value.</p>
<h4><code>napi_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_threadsafe_function" id="all_n-api_napi_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_threadsafe_function"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<p>This is an opaque pointer that represents a JavaScript function which can be
called asynchronously from multiple threads via
<code>napi_call_threadsafe_function()</code>.</p>
<h4><code>napi_threadsafe_function_release_mode</code><span><a class="mark" href="#all_n-api_napi_threadsafe_function_release_mode" id="all_n-api_napi_threadsafe_function_release_mode">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_threadsafe_function_release_mode"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<p>A value to be given to <code>napi_release_threadsafe_function()</code> to indicate whether
the thread-safe function is to be closed immediately (<code>napi_tsfn_abort</code>) or
merely released (<code>napi_tsfn_release</code>) and thus available for subsequent use via
<code>napi_acquire_threadsafe_function()</code> and <code>napi_call_threadsafe_function()</code>.</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
napi_tsfn_release,
napi_tsfn_abort
} napi_threadsafe_function_release_mode;</code> <button class="copy-button">copy</button></pre>
<h4><code>napi_threadsafe_function_call_mode</code><span><a class="mark" href="#all_n-api_napi_threadsafe_function_call_mode" id="all_n-api_napi_threadsafe_function_call_mode">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_threadsafe_function_call_mode"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<p>A value to be given to <code>napi_call_threadsafe_function()</code> to indicate whether
the call should block whenever the queue associated with the thread-safe
function is full.</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
napi_tsfn_nonblocking,
napi_tsfn_blocking
} napi_threadsafe_function_call_mode;</code> <button class="copy-button">copy</button></pre>
<h4>Node-API memory management types<span><a class="mark" href="#all_n-api_node-api-memory-management-types" id="all_n-api_node-api-memory-management-types">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_memory_management_types"></a></h4>
<h5><code>napi_handle_scope</code><span><a class="mark" href="#all_n-api_napi_handle_scope" id="all_n-api_napi_handle_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_handle_scope"></a></h5>
<p>This is an abstraction used to control and modify the lifetime of objects
created within a particular scope. In general, Node-API values are created
within the context of a handle scope. When a native method is called from
JavaScript, a default handle scope will exist. If the user does not explicitly
create a new handle scope, Node-API values will be created in the default handle
scope. For any invocations of code outside the execution of a native method
(for instance, during a libuv callback invocation), the module is required to
create a scope before invoking any functions that can result in the creation
of JavaScript values.</p>
<p>Handle scopes are created using <a href="#all_n-api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and are destroyed
using <a href="#all_n-api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a>. Closing the scope can indicate to the GC
that all <code>napi_value</code>s created during the lifetime of the handle scope are no
longer referenced from the current stack frame.</p>
<p>For more details, review the <a href="#all_n-api_object-lifetime-management">Object lifetime management</a>.</p>
<h5><code>napi_escapable_handle_scope</code><span><a class="mark" href="#all_n-api_napi_escapable_handle_scope" id="all_n-api_napi_escapable_handle_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_escapable_handle_scope"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>Escapable handle scopes are a special type of handle scope to return values
created within a particular handle scope to a parent scope.</p>
<h5><code>napi_ref</code><span><a class="mark" href="#all_n-api_napi_ref" id="all_n-api_napi_ref">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_ref"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>This is the abstraction to use to reference a <code>napi_value</code>. This allows for
users to manage the lifetimes of JavaScript values, including defining their
minimum lifetimes explicitly.</p>
<p>For more details, review the <a href="#all_n-api_object-lifetime-management">Object lifetime management</a>.</p>
<h5><code>napi_type_tag</code><span><a class="mark" href="#all_n-api_napi_type_tag" id="all_n-api_napi_type_tag">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_type_tag"></a></h5>
<div class="api_metadata">
<span>Added in: v14.8.0, v12.19.0</span>
<span>N-API version: 8</span>
</div>
<p>A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID
with which JavaScript objects or <a href="#all_n-api_napi_create_external">externals</a> can be "tagged" in order to
ensure that they are of a certain type. This is a stronger check than
<a href="#all_n-api_napi_instanceof"><code>napi_instanceof</code></a>, because the latter can report a false positive if the
object's prototype has been manipulated. Type-tagging is most useful in
conjunction with <a href="#all_n-api_napi_wrap"><code>napi_wrap</code></a> because it ensures that the pointer retrieved
from a wrapped object can be safely cast to the native type corresponding to the
type tag that had been previously applied to the JavaScript object.</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
<span class="hljs-type">uint64_t</span> lower;
<span class="hljs-type">uint64_t</span> upper;
} napi_type_tag;</code> <button class="copy-button">copy</button></pre>
<h5><code>napi_async_cleanup_hook_handle</code><span><a class="mark" href="#all_n-api_napi_async_cleanup_hook_handle" id="all_n-api_napi_async_cleanup_hook_handle">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_async_cleanup_hook_handle"></a></h5>
<div class="api_metadata">
<span>Added in: v14.10.0, v12.19.0</span>
</div>
<p>An opaque value returned by <a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>. It must be passed
to <a href="#all_n-api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a> when the chain of asynchronous cleanup
events completes.</p>
<h4>Node-API callback types<span><a class="mark" href="#all_n-api_node-api-callback-types" id="all_n-api_node-api-callback-types">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_callback_types"></a></h4>
<h5><code>napi_callback_info</code><span><a class="mark" href="#all_n-api_napi_callback_info" id="all_n-api_napi_callback_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_callback_info"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>Opaque datatype that is passed to a callback function. It can be used for
getting additional information about the context in which the callback was
invoked.</p>
<h5><code>napi_callback</code><span><a class="mark" href="#all_n-api_napi_callback" id="all_n-api_napi_callback">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>Function pointer type for user-provided native functions which are to be
exposed to JavaScript via Node-API. Callback functions should satisfy the
following signature:</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">napi_value</span> <span class="hljs-params">(*napi_callback)</span><span class="hljs-params">(napi_env, napi_callback_info)</span>;</code> <button class="copy-button">copy</button></pre>
<p>Unless for reasons discussed in <a href="#all_n-api_object-lifetime-management">Object Lifetime Management</a>, creating a
handle and/or callback scope inside a <code>napi_callback</code> is not necessary.</p>
<h5><code>node_api_basic_finalize</code><span><a class="mark" href="#all_n-api_node_api_basic_finalize" id="all_n-api_node_api_basic_finalize">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_basic_finalize"></a></h5>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Function pointer type for add-on provided functions that allow the user to be
notified when externally-owned data is ready to be cleaned up because the
object it was associated with has been garbage-collected. The user must provide
a function satisfying the following signature which would get called upon the
object's collection. Currently, <code>node_api_basic_finalize</code> can be used for
finding out when objects that have external data are collected.</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*node_api_basic_finalize)</span><span class="hljs-params">(node_api_basic_env env,
<span class="hljs-type">void</span>* finalize_data,
<span class="hljs-type">void</span>* finalize_hint)</span>;</code> <button class="copy-button">copy</button></pre>
<p>Unless for reasons discussed in <a href="#all_n-api_object-lifetime-management">Object Lifetime Management</a>, creating a
handle and/or callback scope inside the function body is not necessary.</p>
<p>Since these functions may be called while the JavaScript engine is in a state
where it cannot execute JavaScript code, only Node-APIs which accept a
<code>node_api_basic_env</code> as their first parameter may be called.
<a href="#all_n-api_node_api_post_finalizer"><code>node_api_post_finalizer</code></a> can be used to schedule Node-API calls that
require access to the JavaScript engine's state to run after the current
garbage collection cycle has completed.</p>
<p>In the case of <a href="#all_n-api_node_api_create_external_string_latin1"><code>node_api_create_external_string_latin1</code></a> and
<a href="#all_n-api_node_api_create_external_string_utf16"><code>node_api_create_external_string_utf16</code></a> the <code>env</code> parameter may be null,
because external strings can be collected during the latter part of environment
shutdown.</p>
<p>Change History:</p>
<ul>
<li>
<p>experimental (<code>NAPI_EXPERIMENTAL</code>):</p>
<p>Only Node-API calls that accept a <code>node_api_basic_env</code> as their first
parameter may be called, otherwise the application will be terminated with an
appropriate error message. This feature can be turned off by defining
<code>NODE_API_EXPERIMENTAL_BASIC_ENV_OPT_OUT</code>.</p>
</li>
</ul>
<h5><code>napi_finalize</code><span><a class="mark" href="#all_n-api_napi_finalize" id="all_n-api_napi_finalize">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_finalize"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>Function pointer type for add-on provided function that allow the user to
schedule a group of calls to Node-APIs in response to a garbage collection
event, after the garbage collection cycle has completed. These function
pointers can be used with <a href="#all_n-api_node_api_post_finalizer"><code>node_api_post_finalizer</code></a>.</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_finalize)</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">void</span>* finalize_data,
<span class="hljs-type">void</span>* finalize_hint)</span>;</code> <button class="copy-button">copy</button></pre>
<p>Change History:</p>
<ul>
<li>
<p>experimental (<code>NAPI_EXPERIMENTAL</code> is defined):</p>
<p>A function of this type may no longer be used as a finalizer, except with
<a href="#all_n-api_node_api_post_finalizer"><code>node_api_post_finalizer</code></a>. <a href="#all_n-api_node_api_basic_finalize"><code>node_api_basic_finalize</code></a> must be used
instead. This feature can be turned off by defining
<code>NODE_API_EXPERIMENTAL_BASIC_ENV_OPT_OUT</code>.</p>
</li>
</ul>
<h5><code>napi_async_execute_callback</code><span><a class="mark" href="#all_n-api_napi_async_execute_callback" id="all_n-api_napi_async_execute_callback">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_async_execute_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>Function pointer used with functions that support asynchronous
operations. Callback functions must satisfy the following signature:</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_execute_callback)</span><span class="hljs-params">(napi_env env, <span class="hljs-type">void</span>* data)</span>;</code> <button class="copy-button">copy</button></pre>
<p>Implementations of this function must avoid making Node-API calls that execute
JavaScript or interact with JavaScript objects. Node-API calls should be in the
<code>napi_async_complete_callback</code> instead. Do not use the <code>napi_env</code> parameter as
it will likely result in execution of JavaScript.</p>
<h5><code>napi_async_complete_callback</code><span><a class="mark" href="#all_n-api_napi_async_complete_callback" id="all_n-api_napi_async_complete_callback">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_async_complete_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>Function pointer used with functions that support asynchronous
operations. Callback functions must satisfy the following signature:</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_complete_callback)</span><span class="hljs-params">(napi_env env,
napi_status status,
<span class="hljs-type">void</span>* data)</span>;</code> <button class="copy-button">copy</button></pre>
<p>Unless for reasons discussed in <a href="#all_n-api_object-lifetime-management">Object Lifetime Management</a>, creating a
handle and/or callback scope inside the function body is not necessary.</p>
<h5><code>napi_threadsafe_function_call_js</code><span><a class="mark" href="#all_n-api_napi_threadsafe_function_call_js" id="all_n-api_napi_threadsafe_function_call_js">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_threadsafe_function_call_js"></a></h5>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<p>Function pointer used with asynchronous thread-safe function calls. The callback
will be called on the main thread. Its purpose is to use a data item arriving
via the queue from one of the secondary threads to construct the parameters
necessary for a call into JavaScript, usually via <code>napi_call_function</code>, and then
make the call into JavaScript.</p>
<p>The data arriving from the secondary thread via the queue is given in the <code>data</code>
parameter and the JavaScript function to call is given in the <code>js_callback</code>
parameter.</p>
<p>Node-API sets up the environment prior to calling this callback, so it is
sufficient to call the JavaScript function via <code>napi_call_function</code> rather than
via <code>napi_make_callback</code>.</p>
<p>Callback functions must satisfy the following signature:</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_threadsafe_function_call_js)</span><span class="hljs-params">(napi_env env,
napi_value js_callback,
<span class="hljs-type">void</span>* context,
<span class="hljs-type">void</span>* data)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment to use for API calls, or <code>NULL</code> if the thread-safe
function is being torn down and <code>data</code> may need to be freed.</li>
<li><code>[in] js_callback</code>: The JavaScript function to call, or <code>NULL</code> if the
thread-safe function is being torn down and <code>data</code> may need to be freed. It
may also be <code>NULL</code> if the thread-safe function was created without
<code>js_callback</code>.</li>
<li><code>[in] context</code>: The optional data with which the thread-safe function was
created.</li>
<li><code>[in] data</code>: Data created by the secondary thread. It is the responsibility of
the callback to convert this native data to JavaScript values (with Node-API
functions) that can be passed as parameters when <code>js_callback</code> is invoked.
This pointer is managed entirely by the threads and this callback. Thus this
callback should free the data.</li>
</ul>
<p>Unless for reasons discussed in <a href="#all_n-api_object-lifetime-management">Object Lifetime Management</a>, creating a
handle and/or callback scope inside the function body is not necessary.</p>
<h5><code>napi_cleanup_hook</code><span><a class="mark" href="#all_n-api_napi_cleanup_hook" id="all_n-api_napi_cleanup_hook">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_cleanup_hook"></a></h5>
<div class="api_metadata">
<span>Added in: v19.2.0, v18.13.0</span>
<span>N-API version: 3</span>
</div>
<p>Function pointer used with <a href="#all_n-api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a>. It will be called
when the environment is being torn down.</p>
<p>Callback functions must satisfy the following signature:</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_cleanup_hook)</span><span class="hljs-params">(<span class="hljs-type">void</span>* data)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] data</code>: The data that was passed to <a href="#all_n-api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a>.</li>
</ul>
<h5><code>napi_async_cleanup_hook</code><span><a class="mark" href="#all_n-api_napi_async_cleanup_hook" id="all_n-api_napi_async_cleanup_hook">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_async_cleanup_hook"></a></h5>
<div class="api_metadata">
<span>Added in: v14.10.0, v12.19.0</span>
</div>
<p>Function pointer used with <a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>. It will be called
when the environment is being torn down.</p>
<p>Callback functions must satisfy the following signature:</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_cleanup_hook)</span><span class="hljs-params">(napi_async_cleanup_hook_handle handle,
<span class="hljs-type">void</span>* data)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] handle</code>: The handle that must be passed to
<a href="#all_n-api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a> after completion of the asynchronous
cleanup.</li>
<li><code>[in] data</code>: The data that was passed to <a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>.</li>
</ul>
<p>The body of the function should initiate the asynchronous cleanup actions at the
end of which <code>handle</code> must be passed in a call to
<a href="#all_n-api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a>.</p>
</section><section><h3>Error handling<span><a class="mark" href="#all_n-api_error-handling" id="all_n-api_error-handling">#</a></span><a aria-hidden="true" class="legacy" id="n_api_error_handling"></a></h3>
<p>Node-API uses both return values and JavaScript exceptions for error handling.
The following sections explain the approach for each case.</p>
<h4>Return values<span><a class="mark" href="#all_n-api_return-values" id="all_n-api_return-values">#</a></span><a aria-hidden="true" class="legacy" id="n_api_return_values"></a></h4>
<p>All of the Node-API functions share the same error handling pattern. The
return type of all API functions is <code>napi_status</code>.</p>
<p>The return value will be <code>napi_ok</code> if the request was successful and
no uncaught JavaScript exception was thrown. If an error occurred AND
an exception was thrown, the <code>napi_status</code> value for the error
will be returned. If an exception was thrown, and no error occurred,
<code>napi_pending_exception</code> will be returned.</p>
<p>In cases where a return value other than <code>napi_ok</code> or
<code>napi_pending_exception</code> is returned, <a href="#all_n-api_napi_is_exception_pending"><code>napi_is_exception_pending</code></a>
must be called to check if an exception is pending.
See the section on exceptions for more details.</p>
<p>The full set of possible <code>napi_status</code> values is defined
in <code>napi_api_types.h</code>.</p>
<p>The <code>napi_status</code> return value provides a VM-independent representation of
the error which occurred. In some cases it is useful to be able to get
more detailed information, including a string representing the error as well as
VM (engine)-specific information.</p>
<p>In order to retrieve this information <a href="#all_n-api_napi_get_last_error_info"><code>napi_get_last_error_info</code></a>
is provided which returns a <code>napi_extended_error_info</code> structure.
The format of the <code>napi_extended_error_info</code> structure is as follows:</p>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">napi_extended_error_info</span> {</span>
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* error_message;
<span class="hljs-type">void</span>* engine_reserved;
<span class="hljs-type">uint32_t</span> engine_error_code;
napi_status error_code;
};</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>error_message</code>: Textual representation of the error that occurred.</li>
<li><code>engine_reserved</code>: Opaque handle reserved for engine use only.</li>
<li><code>engine_error_code</code>: VM specific error code.</li>
<li><code>error_code</code>: Node-API status code for the last error.</li>
</ul>
<p><a href="#all_n-api_napi_get_last_error_info"><code>napi_get_last_error_info</code></a> returns the information for the last
Node-API call that was made.</p>
<p>Do not rely on the content or format of any of the extended information as it
is not subject to SemVer and may change at any time. It is intended only for
logging purposes.</p>
<h5><code>napi_get_last_error_info</code><span><a class="mark" href="#all_n-api_napi_get_last_error_info" id="all_n-api_napi_get_last_error_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_last_error_info"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status
<span class="hljs-title function_">napi_get_last_error_info</span><span class="hljs-params">(node_api_basic_env env,
<span class="hljs-type">const</span> napi_extended_error_info** result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: The <code>napi_extended_error_info</code> structure with more
information about the error.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API retrieves a <code>napi_extended_error_info</code> structure with information
about the last error that occurred.</p>
<p>The content of the <code>napi_extended_error_info</code> returned is only valid up until
a Node-API function is called on the same <code>env</code>. This includes a call to
<code>napi_is_exception_pending</code> so it may often be necessary to make a copy
of the information so that it can be used later. The pointer returned
in <code>error_message</code> points to a statically-defined string so it is safe to use
that pointer if you have copied it out of the <code>error_message</code> field (which will
be overwritten) before another Node-API function was called.</p>
<p>Do not rely on the content or format of any of the extended information as it
is not subject to SemVer and may change at any time. It is intended only for
logging purposes.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h4>Exceptions<span><a class="mark" href="#all_n-api_exceptions" id="all_n-api_exceptions">#</a></span><a aria-hidden="true" class="legacy" id="n_api_exceptions"></a></h4>
<p>Any Node-API function call may result in a pending JavaScript exception. This is
the case for any of the API functions, even those that may not cause the
execution of JavaScript.</p>
<p>If the <code>napi_status</code> returned by a function is <code>napi_ok</code> then no
exception is pending and no additional action is required. If the
<code>napi_status</code> returned is anything other than <code>napi_ok</code> or
<code>napi_pending_exception</code>, in order to try to recover and continue
instead of simply returning immediately, <a href="#all_n-api_napi_is_exception_pending"><code>napi_is_exception_pending</code></a>
must be called in order to determine if an exception is pending or not.</p>
<p>In many cases when a Node-API function is called and an exception is
already pending, the function will return immediately with a
<code>napi_status</code> of <code>napi_pending_exception</code>. However, this is not the case
for all functions. Node-API allows a subset of the functions to be
called to allow for some minimal cleanup before returning to JavaScript.
In that case, <code>napi_status</code> will reflect the status for the function. It
will not reflect previous pending exceptions. To avoid confusion, check
the error status after every function call.</p>
<p>When an exception is pending one of two approaches can be employed.</p>
<p>The first approach is to do any appropriate cleanup and then return so that
execution will return to JavaScript. As part of the transition back to
JavaScript, the exception will be thrown at the point in the JavaScript
code where the native method was invoked. The behavior of most Node-API calls
is unspecified while an exception is pending, and many will simply return
<code>napi_pending_exception</code>, so do as little as possible and then return to
JavaScript where the exception can be handled.</p>
<p>The second approach is to try to handle the exception. There will be cases
where the native code can catch the exception, take the appropriate action,
and then continue. This is only recommended in specific cases
where it is known that the exception can be safely handled. In these
cases <a href="#all_n-api_napi_get_and_clear_last_exception"><code>napi_get_and_clear_last_exception</code></a> can be used to get and
clear the exception. On success, result will contain the handle to
the last JavaScript <code>Object</code> thrown. If it is determined, after
retrieving the exception, the exception cannot be handled after all
it can be re-thrown it with <a href="#all_n-api_napi_throw"><code>napi_throw</code></a> where error is the
JavaScript value to be thrown.</p>
<p>The following utility functions are also available in case native code
needs to throw an exception or determine if a <code>napi_value</code> is an instance
of a JavaScript <code>Error</code> object: <a href="#all_n-api_napi_throw_error"><code>napi_throw_error</code></a>,
<a href="#all_n-api_napi_throw_type_error"><code>napi_throw_type_error</code></a>, <a href="#all_n-api_napi_throw_range_error"><code>napi_throw_range_error</code></a>, <a href="#all_n-api_node_api_throw_syntax_error"><code>node_api_throw_syntax_error</code></a> and <a href="#all_n-api_napi_is_error"><code>napi_is_error</code></a>.</p>
<p>The following utility functions are also available in case native
code needs to create an <code>Error</code> object: <a href="#all_n-api_napi_create_error"><code>napi_create_error</code></a>,
<a href="#all_n-api_napi_create_type_error"><code>napi_create_type_error</code></a>, <a href="#all_n-api_napi_create_range_error"><code>napi_create_range_error</code></a> and <a href="#all_n-api_node_api_create_syntax_error"><code>node_api_create_syntax_error</code></a>,
where result is the <code>napi_value</code> that refers to the newly created
JavaScript <code>Error</code> object.</p>
<p>The Node.js project is adding error codes to all of the errors
generated internally. The goal is for applications to use these
error codes for all error checking. The associated error messages
will remain, but will only be meant to be used for logging and
display with the expectation that the message can change without
SemVer applying. In order to support this model with Node-API, both
in internal functionality and for module specific functionality
(as its good practice), the <code>throw_</code> and <code>create_</code> functions
take an optional code parameter which is the string for the code
to be added to the error object. If the optional parameter is <code>NULL</code>
then no code will be associated with the error. If a code is provided,
the name associated with the error is also updated to be:</p>
<pre><code class="language-text">originalName [code]</code> <button class="copy-button">copy</button></pre>
<p>where <code>originalName</code> is the original name associated with the error
and <code>code</code> is the code that was provided. For example, if the code
is <code>'ERR_ERROR_1'</code> and a <code>TypeError</code> is being created the name will be:</p>
<pre><code class="language-text">TypeError [ERR_ERROR_1]</code> <button class="copy-button">copy</button></pre>
<h5><code>napi_throw</code><span><a class="mark" href="#all_n-api_napi_throw" id="all_n-api_napi_throw">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_throw"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_throw</span><span class="hljs-params">(napi_env env, napi_value error)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] error</code>: The JavaScript value to be thrown.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API throws the JavaScript value provided.</p>
<h5><code>napi_throw_error</code><span><a class="mark" href="#all_n-api_napi_throw_error" id="all_n-api_napi_throw_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_throw_error"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_throw_error</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* code,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* msg)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional error code to be set on the error.</li>
<li><code>[in] msg</code>: C string representing the text to be associated with the error.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API throws a JavaScript <code>Error</code> with the text provided.</p>
<h5><code>napi_throw_type_error</code><span><a class="mark" href="#all_n-api_napi_throw_type_error" id="all_n-api_napi_throw_type_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_throw_type_error"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_throw_type_error</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* code,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* msg)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional error code to be set on the error.</li>
<li><code>[in] msg</code>: C string representing the text to be associated with the error.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API throws a JavaScript <code>TypeError</code> with the text provided.</p>
<h5><code>napi_throw_range_error</code><span><a class="mark" href="#all_n-api_napi_throw_range_error" id="all_n-api_napi_throw_range_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_throw_range_error"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_throw_range_error</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* code,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* msg)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional error code to be set on the error.</li>
<li><code>[in] msg</code>: C string representing the text to be associated with the error.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API throws a JavaScript <code>RangeError</code> with the text provided.</p>
<h5><code>node_api_throw_syntax_error</code><span><a class="mark" href="#all_n-api_node_api_throw_syntax_error" id="all_n-api_node_api_throw_syntax_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_throw_syntax_error"></a></h5>
<div class="api_metadata">
<span>Added in: v17.2.0, v16.14.0</span>
<span>N-API version: 9</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">node_api_throw_syntax_error</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* code,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* msg)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional error code to be set on the error.</li>
<li><code>[in] msg</code>: C string representing the text to be associated with the error.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API throws a JavaScript <code>SyntaxError</code> with the text provided.</p>
<h5><code>napi_is_error</code><span><a class="mark" href="#all_n-api_napi_is_error" id="all_n-api_napi_is_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_error"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_is_error</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The <code>napi_value</code> to be checked.</li>
<li><code>[out] result</code>: Boolean value that is set to true if <code>napi_value</code> represents
an error, false otherwise.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API queries a <code>napi_value</code> to check if it represents an error object.</p>
<h5><code>napi_create_error</code><span><a class="mark" href="#all_n-api_napi_create_error" id="all_n-api_napi_create_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_error"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_create_error</span><span class="hljs-params">(napi_env env,
napi_value code,
napi_value msg,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be
associated with the error.</li>
<li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>string</code> to be used as
the message for the <code>Error</code>.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns a JavaScript <code>Error</code> with the text provided.</p>
<h5><code>napi_create_type_error</code><span><a class="mark" href="#all_n-api_napi_create_type_error" id="all_n-api_napi_create_type_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_type_error"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_create_type_error</span><span class="hljs-params">(napi_env env,
napi_value code,
napi_value msg,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be
associated with the error.</li>
<li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>string</code> to be used as
the message for the <code>Error</code>.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns a JavaScript <code>TypeError</code> with the text provided.</p>
<h5><code>napi_create_range_error</code><span><a class="mark" href="#all_n-api_napi_create_range_error" id="all_n-api_napi_create_range_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_range_error"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_create_range_error</span><span class="hljs-params">(napi_env env,
napi_value code,
napi_value msg,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be
associated with the error.</li>
<li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>string</code> to be used as
the message for the <code>Error</code>.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns a JavaScript <code>RangeError</code> with the text provided.</p>
<h5><code>node_api_create_syntax_error</code><span><a class="mark" href="#all_n-api_node_api_create_syntax_error" id="all_n-api_node_api_create_syntax_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_create_syntax_error"></a></h5>
<div class="api_metadata">
<span>Added in: v17.2.0, v16.14.0</span>
<span>N-API version: 9</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">node_api_create_syntax_error</span><span class="hljs-params">(napi_env env,
napi_value code,
napi_value msg,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be
associated with the error.</li>
<li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>string</code> to be used as
the message for the <code>Error</code>.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns a JavaScript <code>SyntaxError</code> with the text provided.</p>
<h5><code>napi_get_and_clear_last_exception</code><span><a class="mark" href="#all_n-api_napi_get_and_clear_last_exception" id="all_n-api_napi_get_and_clear_last_exception">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_and_clear_last_exception"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_and_clear_last_exception</span><span class="hljs-params">(napi_env env,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: The exception if one is pending, <code>NULL</code> otherwise.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h5><code>napi_is_exception_pending</code><span><a class="mark" href="#all_n-api_napi_is_exception_pending" id="all_n-api_napi_is_exception_pending">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_exception_pending"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_exception_pending</span><span class="hljs-params">(napi_env env, <span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: Boolean value that is set to true if an exception is pending.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h5><code>napi_fatal_exception</code><span><a class="mark" href="#all_n-api_napi_fatal_exception" id="all_n-api_napi_fatal_exception">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_fatal_exception"></a></h5>
<div class="api_metadata">
<span>Added in: v9.10.0</span>
<span>N-API version: 3</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_fatal_exception</span><span class="hljs-params">(napi_env env, napi_value err)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] err</code>: The error that is passed to <code>'uncaughtException'</code>.</li>
</ul>
<p>Trigger an <code>'uncaughtException'</code> in JavaScript. Useful if an async
callback throws an exception with no way to recover.</p>
<h4>Fatal errors<span><a class="mark" href="#all_n-api_fatal-errors" id="all_n-api_fatal-errors">#</a></span><a aria-hidden="true" class="legacy" id="n_api_fatal_errors"></a></h4>
<p>In the event of an unrecoverable error in a native addon, a fatal error can be
thrown to immediately terminate the process.</p>
<h5><code>napi_fatal_error</code><span><a class="mark" href="#all_n-api_napi_fatal_error" id="all_n-api_napi_fatal_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_fatal_error"></a></h5>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_NO_RETURN <span class="hljs-type">void</span> <span class="hljs-title function_">napi_fatal_error</span><span class="hljs-params">(<span class="hljs-type">const</span> <span class="hljs-type">char</span>* location,
<span class="hljs-type">size_t</span> location_len,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* message,
<span class="hljs-type">size_t</span> message_len)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] location</code>: Optional location at which the error occurred.</li>
<li><code>[in] location_len</code>: The length of the location in bytes, or
<code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li>
<li><code>[in] message</code>: The message associated with the error.</li>
<li><code>[in] message_len</code>: The length of the message in bytes, or <code>NAPI_AUTO_LENGTH</code>
if it is null-terminated.</li>
</ul>
<p>The function call does not return, the process will be terminated.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
</section><section><h3>Object lifetime management<span><a class="mark" href="#all_n-api_object-lifetime-management" id="all_n-api_object-lifetime-management">#</a></span><a aria-hidden="true" class="legacy" id="n_api_object_lifetime_management"></a></h3>
<p>As Node-API calls are made, handles to objects in the heap for the underlying
VM may be returned as <code>napi_values</code>. These handles must hold the
objects 'live' until they are no longer required by the native code,
otherwise the objects could be collected before the native code was
finished using them.</p>
<p>As object handles are returned they are associated with a
'scope'. The lifespan for the default scope is tied to the lifespan
of the native method call. The result is that, by default, handles
remain valid and the objects associated with these handles will be
held live for the lifespan of the native method call.</p>
<p>In many cases, however, it is necessary that the handles remain valid for
either a shorter or longer lifespan than that of the native method.
The sections which follow describe the Node-API functions that can be used
to change the handle lifespan from the default.</p>
<h4>Making handle lifespan shorter than that of the native method<span><a class="mark" href="#all_n-api_making-handle-lifespan-shorter-than-that-of-the-native-method" id="all_n-api_making-handle-lifespan-shorter-than-that-of-the-native-method">#</a></span><a aria-hidden="true" class="legacy" id="n_api_making_handle_lifespan_shorter_than_that_of_the_native_method"></a></h4>
<p>It is often necessary to make the lifespan of handles shorter than
the lifespan of a native method. For example, consider a native method
that has a loop which iterates through the elements in a large array:</p>
<pre><code class="language-c"><span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">1000000</span>; i++) {
napi_value result;
napi_status status = napi_get_element(env, object, i, &result);
<span class="hljs-keyword">if</span> (status != napi_ok) {
<span class="hljs-keyword">break</span>;
}
<span class="hljs-comment">// do something with element</span>
}</code> <button class="copy-button">copy</button></pre>
<p>This would result in a large number of handles being created, consuming
substantial resources. In addition, even though the native code could only
use the most recent handle, all of the associated objects would also be
kept alive since they all share the same scope.</p>
<p>To handle this case, Node-API provides the ability to establish a new 'scope' to
which newly created handles will be associated. Once those handles
are no longer required, the scope can be 'closed' and any handles associated
with the scope are invalidated. The methods available to open/close scopes are
<a href="#all_n-api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and <a href="#all_n-api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a>.</p>
<p>Node-API only supports a single nested hierarchy of scopes. There is only one
active scope at any time, and all new handles will be associated with that
scope while it is active. Scopes must be closed in the reverse order from
which they are opened. In addition, all scopes created within a native method
must be closed before returning from that method.</p>
<p>Taking the earlier example, adding calls to <a href="#all_n-api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and
<a href="#all_n-api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a> would ensure that at most a single handle
is valid throughout the execution of the loop:</p>
<pre><code class="language-c"><span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">1000000</span>; i++) {
napi_handle_scope scope;
napi_status status = napi_open_handle_scope(env, &scope);
<span class="hljs-keyword">if</span> (status != napi_ok) {
<span class="hljs-keyword">break</span>;
}
napi_value result;
status = napi_get_element(env, object, i, &result);
<span class="hljs-keyword">if</span> (status != napi_ok) {
<span class="hljs-keyword">break</span>;
}
<span class="hljs-comment">// do something with element</span>
status = napi_close_handle_scope(env, scope);
<span class="hljs-keyword">if</span> (status != napi_ok) {
<span class="hljs-keyword">break</span>;
}
}</code> <button class="copy-button">copy</button></pre>
<p>When nesting scopes, there are cases where a handle from an
inner scope needs to live beyond the lifespan of that scope. Node-API supports
an 'escapable scope' in order to support this case. An escapable scope
allows one handle to be 'promoted' so that it 'escapes' the
current scope and the lifespan of the handle changes from the current
scope to that of the outer scope.</p>
<p>The methods available to open/close escapable scopes are
<a href="#all_n-api_napi_open_escapable_handle_scope"><code>napi_open_escapable_handle_scope</code></a> and
<a href="#all_n-api_napi_close_escapable_handle_scope"><code>napi_close_escapable_handle_scope</code></a>.</p>
<p>The request to promote a handle is made through <a href="#all_n-api_napi_escape_handle"><code>napi_escape_handle</code></a> which
can only be called once.</p>
<h5><code>napi_open_handle_scope</code><span><a class="mark" href="#all_n-api_napi_open_handle_scope" id="all_n-api_napi_open_handle_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_open_handle_scope"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_open_handle_scope</span><span class="hljs-params">(napi_env env,
napi_handle_scope* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the new scope.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API opens a new scope.</p>
<h5><code>napi_close_handle_scope</code><span><a class="mark" href="#all_n-api_napi_close_handle_scope" id="all_n-api_napi_close_handle_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_close_handle_scope"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_close_handle_scope</span><span class="hljs-params">(napi_env env,
napi_handle_scope scope)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] scope</code>: <code>napi_value</code> representing the scope to be closed.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API closes the scope passed in. Scopes must be closed in the
reverse order from which they were created.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h5><code>napi_open_escapable_handle_scope</code><span><a class="mark" href="#all_n-api_napi_open_escapable_handle_scope" id="all_n-api_napi_open_escapable_handle_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_open_escapable_handle_scope"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
<span class="hljs-title function_">napi_open_escapable_handle_scope</span><span class="hljs-params">(napi_env env,
napi_handle_scope* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the new scope.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API opens a new scope from which one object can be promoted
to the outer scope.</p>
<h5><code>napi_close_escapable_handle_scope</code><span><a class="mark" href="#all_n-api_napi_close_escapable_handle_scope" id="all_n-api_napi_close_escapable_handle_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_close_escapable_handle_scope"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
<span class="hljs-title function_">napi_close_escapable_handle_scope</span><span class="hljs-params">(napi_env env,
napi_handle_scope scope)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] scope</code>: <code>napi_value</code> representing the scope to be closed.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API closes the scope passed in. Scopes must be closed in the
reverse order from which they were created.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h5><code>napi_escape_handle</code><span><a class="mark" href="#all_n-api_napi_escape_handle" id="all_n-api_napi_escape_handle">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_escape_handle"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_escape_handle</span><span class="hljs-params">(napi_env env,
napi_escapable_handle_scope scope,
napi_value escapee,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] scope</code>: <code>napi_value</code> representing the current scope.</li>
<li><code>[in] escapee</code>: <code>napi_value</code> representing the JavaScript <code>Object</code> to be
escaped.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the handle to the escaped <code>Object</code>
in the outer scope.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API promotes the handle to the JavaScript object so that it is valid
for the lifetime of the outer scope. It can only be called once per scope.
If it is called more than once an error will be returned.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h4>References to values with a lifespan longer than that of the native method<span><a class="mark" href="#all_n-api_references-to-values-with-a-lifespan-longer-than-that-of-the-native-method" id="all_n-api_references-to-values-with-a-lifespan-longer-than-that-of-the-native-method">#</a></span><a aria-hidden="true" class="legacy" id="n_api_references_to_values_with_a_lifespan_longer_than_that_of_the_native_method"></a></h4>
<p>In some cases, an addon will need to be able to create and reference values
with a lifespan longer than that of a single native method invocation. For
example, to create a constructor and later use that constructor
in a request to create instances, it must be possible to reference
the constructor object across many different instance creation requests. This
would not be possible with a normal handle returned as a <code>napi_value</code> as
described in the earlier section. The lifespan of a normal handle is
managed by scopes and all scopes must be closed before the end of a native
method.</p>
<p>Node-API provides methods for creating persistent references to values.
Currently Node-API only allows references to be created for a
limited set of value types, including object, external, function, and symbol.</p>
<p>Each reference has an associated count with a value of 0 or higher,
which determines whether the reference will keep the corresponding value alive.
References with a count of 0 do not prevent values from being collected.
Values of object (object, function, external) and symbol types are becoming
'weak' references and can still be accessed while they are not collected.
Any count greater than 0 will prevent the values from being collected.</p>
<p>Symbol values have different flavors. The true weak reference behavior is
only supported by local symbols created with the <code>napi_create_symbol</code> function
or the JavaScript <code>Symbol()</code> constructor calls. Globally registered symbols
created with the <code>node_api_symbol_for</code> function or JavaScript <code>Symbol.for()</code>
function calls remain always strong references because the garbage collector
does not collect them. The same is true for well-known symbols such as
<code>Symbol.iterator</code>. They are also never collected by the garbage collector.</p>
<p>References can be created with an initial reference count. The count can
then be modified through <a href="#all_n-api_napi_reference_ref"><code>napi_reference_ref</code></a> and
<a href="#all_n-api_napi_reference_unref"><code>napi_reference_unref</code></a>. If an object is collected while the count
for a reference is 0, all subsequent calls to
get the object associated with the reference <a href="#all_n-api_napi_get_reference_value"><code>napi_get_reference_value</code></a>
will return <code>NULL</code> for the returned <code>napi_value</code>. An attempt to call
<a href="#all_n-api_napi_reference_ref"><code>napi_reference_ref</code></a> for a reference whose object has been collected
results in an error.</p>
<p>References must be deleted once they are no longer required by the addon. When
a reference is deleted, it will no longer prevent the corresponding object from
being collected. Failure to delete a persistent reference results in
a 'memory leak' with both the native memory for the persistent reference and
the corresponding object on the heap being retained forever.</p>
<p>There can be multiple persistent references created which refer to the same
object, each of which will either keep the object live or not based on its
individual count. Multiple persistent references to the same object
can result in unexpectedly keeping alive native memory. The native structures
for a persistent reference must be kept alive until finalizers for the
referenced object are executed. If a new persistent reference is created
for the same object, the finalizers for that object will not be
run and the native memory pointed by the earlier persistent reference
will not be freed. This can be avoided by calling
<code>napi_delete_reference</code> in addition to <code>napi_reference_unref</code> when possible.</p>
<p><strong>Change History:</strong></p>
<ul>
<li>
<p>Experimental (<code>NAPI_EXPERIMENTAL</code> is defined):</p>
<p>References can be created for all value types. The new supported value
types do not support weak reference semantic and the values of these types
are released when the reference count becomes 0 and cannot be accessed from
the reference anymore.</p>
</li>
</ul>
<h5><code>napi_create_reference</code><span><a class="mark" href="#all_n-api_napi_create_reference" id="all_n-api_napi_create_reference">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_reference"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_create_reference</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">uint32_t</span> initial_refcount,
napi_ref* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The <code>napi_value</code> for which a reference is being created.</li>
<li><code>[in] initial_refcount</code>: Initial reference count for the new reference.</li>
<li><code>[out] result</code>: <code>napi_ref</code> pointing to the new reference.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a new reference with the specified reference count
to the value passed in.</p>
<h5><code>napi_delete_reference</code><span><a class="mark" href="#all_n-api_napi_delete_reference" id="all_n-api_napi_delete_reference">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_delete_reference"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_delete_reference</span><span class="hljs-params">(napi_env env, napi_ref ref)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] ref</code>: <code>napi_ref</code> to be deleted.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API deletes the reference passed in.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h5><code>napi_reference_ref</code><span><a class="mark" href="#all_n-api_napi_reference_ref" id="all_n-api_napi_reference_ref">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_reference_ref"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_reference_ref</span><span class="hljs-params">(napi_env env,
napi_ref ref,
<span class="hljs-type">uint32_t</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] ref</code>: <code>napi_ref</code> for which the reference count will be incremented.</li>
<li><code>[out] result</code>: The new reference count.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API increments the reference count for the reference
passed in and returns the resulting reference count.</p>
<h5><code>napi_reference_unref</code><span><a class="mark" href="#all_n-api_napi_reference_unref" id="all_n-api_napi_reference_unref">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_reference_unref"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_reference_unref</span><span class="hljs-params">(napi_env env,
napi_ref ref,
<span class="hljs-type">uint32_t</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] ref</code>: <code>napi_ref</code> for which the reference count will be decremented.</li>
<li><code>[out] result</code>: The new reference count.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API decrements the reference count for the reference
passed in and returns the resulting reference count.</p>
<h5><code>napi_get_reference_value</code><span><a class="mark" href="#all_n-api_napi_get_reference_value" id="all_n-api_napi_get_reference_value">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_reference_value"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_get_reference_value</span><span class="hljs-params">(napi_env env,
napi_ref ref,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] ref</code>: The <code>napi_ref</code> for which the corresponding value is
being requested.</li>
<li><code>[out] result</code>: The <code>napi_value</code> referenced by the <code>napi_ref</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>If still valid, this API returns the <code>napi_value</code> representing the
JavaScript value associated with the <code>napi_ref</code>. Otherwise, result
will be <code>NULL</code>.</p>
<h4>Cleanup on exit of the current Node.js environment<span><a class="mark" href="#all_n-api_cleanup-on-exit-of-the-current-nodejs-environment" id="all_n-api_cleanup-on-exit-of-the-current-nodejs-environment">#</a></span><a aria-hidden="true" class="legacy" id="n_api_cleanup_on_exit_of_the_current_node_js_environment"></a></h4>
<p>While a Node.js process typically releases all its resources when exiting,
embedders of Node.js, or future Worker support, may require addons to register
clean-up hooks that will be run once the current Node.js environment exits.</p>
<p>Node-API provides functions for registering and un-registering such callbacks.
When those callbacks are run, all resources that are being held by the addon
should be freed up.</p>
<h5><code>napi_add_env_cleanup_hook</code><span><a class="mark" href="#all_n-api_napi_add_env_cleanup_hook" id="all_n-api_napi_add_env_cleanup_hook">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_add_env_cleanup_hook"></a></h5>
<div class="api_metadata">
<span>Added in: v10.2.0</span>
<span>N-API version: 3</span>
</div>
<pre><code class="language-c">NODE_EXTERN napi_status <span class="hljs-title function_">napi_add_env_cleanup_hook</span><span class="hljs-params">(node_api_basic_env env,
napi_cleanup_hook fun,
<span class="hljs-type">void</span>* arg)</span>;</code> <button class="copy-button">copy</button></pre>
<p>Registers <code>fun</code> as a function to be run with the <code>arg</code> parameter once the
current Node.js environment exits.</p>
<p>A function can safely be specified multiple times with different
<code>arg</code> values. In that case, it will be called multiple times as well.
Providing the same <code>fun</code> and <code>arg</code> values multiple times is not allowed
and will lead the process to abort.</p>
<p>The hooks will be called in reverse order, i.e. the most recently added one
will be called first.</p>
<p>Removing this hook can be done by using <a href="#all_n-api_napi_remove_env_cleanup_hook"><code>napi_remove_env_cleanup_hook</code></a>.
Typically, that happens when the resource for which this hook was added
is being torn down anyway.</p>
<p>For asynchronous cleanup, <a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a> is available.</p>
<h5><code>napi_remove_env_cleanup_hook</code><span><a class="mark" href="#all_n-api_napi_remove_env_cleanup_hook" id="all_n-api_napi_remove_env_cleanup_hook">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_remove_env_cleanup_hook"></a></h5>
<div class="api_metadata">
<span>Added in: v10.2.0</span>
<span>N-API version: 3</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_remove_env_cleanup_hook</span><span class="hljs-params">(node_api_basic_env env,
<span class="hljs-type">void</span> (*fun)(<span class="hljs-type">void</span>* arg),
<span class="hljs-type">void</span>* arg)</span>;</code> <button class="copy-button">copy</button></pre>
<p>Unregisters <code>fun</code> as a function to be run with the <code>arg</code> parameter once the
current Node.js environment exits. Both the argument and the function value
need to be exact matches.</p>
<p>The function must have originally been registered
with <code>napi_add_env_cleanup_hook</code>, otherwise the process will abort.</p>
<h5><code>napi_add_async_cleanup_hook</code><span><a class="mark" href="#all_n-api_napi_add_async_cleanup_hook" id="all_n-api_napi_add_async_cleanup_hook">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_add_async_cleanup_hook"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p>Changed signature of the <code>hook</code> callback.</p></td></tr>
<tr><td>v14.8.0, v12.19.0</td>
<td><p><span>Added in: v14.8.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
<span>N-API version: 8</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_add_async_cleanup_hook</span><span class="hljs-params">(
node_api_basic_env env,
napi_async_cleanup_hook hook,
<span class="hljs-type">void</span>* arg,
napi_async_cleanup_hook_handle* remove_handle)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] hook</code>: The function pointer to call at environment teardown.</li>
<li><code>[in] arg</code>: The pointer to pass to <code>hook</code> when it gets called.</li>
<li><code>[out] remove_handle</code>: Optional handle that refers to the asynchronous cleanup
hook.</li>
</ul>
<p>Registers <code>hook</code>, which is a function of type <a href="#all_n-api_napi_async_cleanup_hook"><code>napi_async_cleanup_hook</code></a>, as
a function to be run with the <code>remove_handle</code> and <code>arg</code> parameters once the
current Node.js environment exits.</p>
<p>Unlike <a href="#all_n-api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a>, the hook is allowed to be asynchronous.</p>
<p>Otherwise, behavior generally matches that of <a href="#all_n-api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a>.</p>
<p>If <code>remove_handle</code> is not <code>NULL</code>, an opaque value will be stored in it
that must later be passed to <a href="#all_n-api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a>,
regardless of whether the hook has already been invoked.
Typically, that happens when the resource for which this hook was added
is being torn down anyway.</p>
<h5><code>napi_remove_async_cleanup_hook</code><span><a class="mark" href="#all_n-api_napi_remove_async_cleanup_hook" id="all_n-api_napi_remove_async_cleanup_hook">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_remove_async_cleanup_hook"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p>Removed <code>env</code> parameter.</p></td></tr>
<tr><td>v14.8.0, v12.19.0</td>
<td><p><span>Added in: v14.8.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_remove_async_cleanup_hook</span><span class="hljs-params">(
napi_async_cleanup_hook_handle remove_handle)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] remove_handle</code>: The handle to an asynchronous cleanup hook that was
created with <a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>.</li>
</ul>
<p>Unregisters the cleanup hook corresponding to <code>remove_handle</code>. This will prevent
the hook from being executed, unless it has already started executing.
This must be called on any <code>napi_async_cleanup_hook_handle</code> value obtained
from <a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>.</p>
<h4>Finalization on the exit of the Node.js environment<span><a class="mark" href="#all_n-api_finalization-on-the-exit-of-the-nodejs-environment" id="all_n-api_finalization-on-the-exit-of-the-nodejs-environment">#</a></span><a aria-hidden="true" class="legacy" id="n_api_finalization_on_the_exit_of_the_node_js_environment"></a></h4>
<p>The Node.js environment may be torn down at an arbitrary time as soon as
possible with JavaScript execution disallowed, like on the request of
<a href="#all_worker_threads_workerterminate"><code>worker.terminate()</code></a>. When the environment is being torn down, the
registered <code>napi_finalize</code> callbacks of JavaScript objects, thread-safe
functions and environment instance data are invoked immediately and
independently.</p>
<p>The invocation of <code>napi_finalize</code> callbacks is scheduled after the manually
registered cleanup hooks. In order to ensure a proper order of addon
finalization during environment shutdown to avoid use-after-free in the
<code>napi_finalize</code> callback, addons should register a cleanup hook with
<code>napi_add_env_cleanup_hook</code> and <code>napi_add_async_cleanup_hook</code> to manually
release the allocated resource in a proper order.</p>
</section><section><h3>Module registration<span><a class="mark" href="#all_n-api_module-registration" id="all_n-api_module-registration">#</a></span><a aria-hidden="true" class="legacy" id="n_api_module_registration"></a></h3>
<p>Node-API modules are registered in a manner similar to other modules
except that instead of using the <code>NODE_MODULE</code> macro the following
is used:</p>
<pre><code class="language-c">NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)</code> <button class="copy-button">copy</button></pre>
<p>The next difference is the signature for the <code>Init</code> method. For a Node-API
module it is as follows:</p>
<pre><code class="language-c">napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span>;</code> <button class="copy-button">copy</button></pre>
<p>The return value from <code>Init</code> is treated as the <code>exports</code> object for the module.
The <code>Init</code> method is passed an empty object via the <code>exports</code> parameter as a
convenience. If <code>Init</code> returns <code>NULL</code>, the parameter passed as <code>exports</code> is
exported by the module. Node-API modules cannot modify the <code>module</code> object but
can specify anything as the <code>exports</code> property of the module.</p>
<p>To add the method <code>hello</code> as a function so that it can be called as a method
provided by the addon:</p>
<pre><code class="language-c">napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> {
napi_status status;
napi_property_descriptor desc = {
<span class="hljs-string">"hello"</span>,
<span class="hljs-literal">NULL</span>,
Method,
<span class="hljs-literal">NULL</span>,
<span class="hljs-literal">NULL</span>,
<span class="hljs-literal">NULL</span>,
napi_writable | napi_enumerable | napi_configurable,
<span class="hljs-literal">NULL</span>
};
status = napi_define_properties(env, exports, <span class="hljs-number">1</span>, &desc);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-keyword">return</span> exports;
}</code> <button class="copy-button">copy</button></pre>
<p>To set a function to be returned by the <code>require()</code> for the addon:</p>
<pre><code class="language-c">napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> {
napi_value method;
napi_status status;
status = napi_create_function(env, <span class="hljs-string">"exports"</span>, NAPI_AUTO_LENGTH, Method, <span class="hljs-literal">NULL</span>, &method);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-keyword">return</span> method;
}</code> <button class="copy-button">copy</button></pre>
<p>To define a class so that new instances can be created (often used with
<a href="#all_n-api_object-wrap">Object wrap</a>):</p>
<pre><code class="language-c"><span class="hljs-comment">// <span class="hljs-doctag">NOTE:</span> partial example, not all referenced code is included</span>
napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> {
napi_status status;
napi_property_descriptor properties[] = {
{ <span class="hljs-string">"value"</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, GetValue, SetValue, <span class="hljs-literal">NULL</span>, napi_writable | napi_configurable, <span class="hljs-literal">NULL</span> },
DECLARE_NAPI_METHOD(<span class="hljs-string">"plusOne"</span>, PlusOne),
DECLARE_NAPI_METHOD(<span class="hljs-string">"multiply"</span>, Multiply),
};
napi_value cons;
status =
napi_define_class(env, <span class="hljs-string">"MyObject"</span>, New, <span class="hljs-literal">NULL</span>, <span class="hljs-number">3</span>, properties, &cons);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
status = napi_create_reference(env, cons, <span class="hljs-number">1</span>, &constructor);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
status = napi_set_named_property(env, exports, <span class="hljs-string">"MyObject"</span>, cons);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-keyword">return</span> exports;
}</code> <button class="copy-button">copy</button></pre>
<p>You can also use the <code>NAPI_MODULE_INIT</code> macro, which acts as a shorthand
for <code>NAPI_MODULE</code> and defining an <code>Init</code> function:</p>
<pre><code class="language-c">NAPI_MODULE_INIT(<span class="hljs-comment">/* napi_env env, napi_value exports */</span>) {
napi_value answer;
napi_status result;
status = napi_create_int64(env, <span class="hljs-number">42</span>, &answer);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
status = napi_set_named_property(env, exports, <span class="hljs-string">"answer"</span>, answer);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-keyword">return</span> exports;
}</code> <button class="copy-button">copy</button></pre>
<p>The parameters <code>env</code> and <code>exports</code> are provided to the body of the
<code>NAPI_MODULE_INIT</code> macro.</p>
<p>All Node-API addons are context-aware, meaning they may be loaded multiple
times. There are a few design considerations when declaring such a module.
The documentation on <a href="#all_addons_context-aware-addons">context-aware addons</a> provides more details.</p>
<p>The variables <code>env</code> and <code>exports</code> will be available inside the function body
following the macro invocation.</p>
<p>For more details on setting properties on objects, see the section on
<a href="#all_n-api_working-with-javascript-properties">Working with JavaScript properties</a>.</p>
<p>For more details on building addon modules in general, refer to the existing
API.</p>
</section><section><h3>Working with JavaScript values<span><a class="mark" href="#all_n-api_working-with-javascript-values" id="all_n-api_working-with-javascript-values">#</a></span><a aria-hidden="true" class="legacy" id="n_api_working_with_javascript_values"></a></h3>
<p>Node-API exposes a set of APIs to create all types of JavaScript values.
Some of these types are documented under <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Section 6</a>
of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p>
<p>Fundamentally, these APIs are used to do one of the following:</p>
<ol>
<li>Create a new JavaScript object</li>
<li>Convert from a primitive C type to a Node-API value</li>
<li>Convert from Node-API value to a primitive C type</li>
<li>Get global instances including <code>undefined</code> and <code>null</code></li>
</ol>
<p>Node-API values are represented by the type <code>napi_value</code>.
Any Node-API call that requires a JavaScript value takes in a <code>napi_value</code>.
In some cases, the API does check the type of the <code>napi_value</code> up-front.
However, for better performance, it's better for the caller to make sure that
the <code>napi_value</code> in question is of the JavaScript type expected by the API.</p>
<h4>Enum types<span><a class="mark" href="#all_n-api_enum-types" id="all_n-api_enum-types">#</a></span><a aria-hidden="true" class="legacy" id="n_api_enum_types"></a></h4>
<h5><code>napi_key_collection_mode</code><span><a class="mark" href="#all_n-api_napi_key_collection_mode" id="all_n-api_napi_key_collection_mode">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_key_collection_mode"></a></h5>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0, v10.20.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
napi_key_include_prototypes,
napi_key_own_only
} napi_key_collection_mode;</code> <button class="copy-button">copy</button></pre>
<p>Describes the <code>Keys/Properties</code> filter enums:</p>
<p><code>napi_key_collection_mode</code> limits the range of collected properties.</p>
<p><code>napi_key_own_only</code> limits the collected properties to the given
object only. <code>napi_key_include_prototypes</code> will include all keys
of the objects's prototype chain as well.</p>
<h5><code>napi_key_filter</code><span><a class="mark" href="#all_n-api_napi_key_filter" id="all_n-api_napi_key_filter">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_key_filter"></a></h5>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0, v10.20.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
napi_key_all_properties = <span class="hljs-number">0</span>,
napi_key_writable = <span class="hljs-number">1</span>,
napi_key_enumerable = <span class="hljs-number">1</span> << <span class="hljs-number">1</span>,
napi_key_configurable = <span class="hljs-number">1</span> << <span class="hljs-number">2</span>,
napi_key_skip_strings = <span class="hljs-number">1</span> << <span class="hljs-number">3</span>,
napi_key_skip_symbols = <span class="hljs-number">1</span> << <span class="hljs-number">4</span>
} napi_key_filter;</code> <button class="copy-button">copy</button></pre>
<p>Property filter bits. They can be or'ed to build a composite filter.</p>
<h5><code>napi_key_conversion</code><span><a class="mark" href="#all_n-api_napi_key_conversion" id="all_n-api_napi_key_conversion">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_key_conversion"></a></h5>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0, v10.20.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
napi_key_keep_numbers,
napi_key_numbers_to_strings
} napi_key_conversion;</code> <button class="copy-button">copy</button></pre>
<p><code>napi_key_numbers_to_strings</code> will convert integer indexes to
strings. <code>napi_key_keep_numbers</code> will return numbers for integer
indexes.</p>
<h5><code>napi_valuetype</code><span><a class="mark" href="#all_n-api_napi_valuetype" id="all_n-api_napi_valuetype">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_valuetype"></a></h5>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
<span class="hljs-comment">// ES6 types (corresponds to typeof)</span>
napi_undefined,
napi_null,
napi_boolean,
napi_number,
napi_string,
napi_symbol,
napi_object,
napi_function,
napi_external,
napi_bigint,
} napi_valuetype;</code> <button class="copy-button">copy</button></pre>
<p>Describes the type of a <code>napi_value</code>. This generally corresponds to the types
described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types">Section 6.1</a> of the ECMAScript Language Specification.
In addition to types in that section, <code>napi_valuetype</code> can also represent
<code>Function</code>s and <code>Object</code>s with external data.</p>
<p>A JavaScript value of type <code>napi_external</code> appears in JavaScript as a plain
object such that no properties can be set on it, and no prototype.</p>
<h5><code>napi_typedarray_type</code><span><a class="mark" href="#all_n-api_napi_typedarray_type" id="all_n-api_napi_typedarray_type">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_typedarray_type"></a></h5>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
napi_int8_array,
napi_uint8_array,
napi_uint8_clamped_array,
napi_int16_array,
napi_uint16_array,
napi_int32_array,
napi_uint32_array,
napi_float32_array,
napi_float64_array,
napi_bigint64_array,
napi_biguint64_array,
} napi_typedarray_type;</code> <button class="copy-button">copy</button></pre>
<p>This represents the underlying binary scalar datatype of the <code>TypedArray</code>.
Elements of this enum correspond to
<a href="https://tc39.github.io/ecma262/#sec-typedarray-objects">Section 22.2</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p>
<h4>Object creation functions<span><a class="mark" href="#all_n-api_object-creation-functions" id="all_n-api_object-creation-functions">#</a></span><a aria-hidden="true" class="legacy" id="n_api_object_creation_functions"></a></h4>
<h5><code>napi_create_array</code><span><a class="mark" href="#all_n-api_napi_create_array" id="all_n-api_napi_create_array">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_array"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_array</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Array</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns a Node-API value corresponding to a JavaScript <code>Array</code> type.
JavaScript arrays are described in
<a href="https://tc39.github.io/ecma262/#sec-array-objects">Section 22.1</a> of the ECMAScript Language Specification.</p>
<h5><code>napi_create_array_with_length</code><span><a class="mark" href="#all_n-api_napi_create_array_with_length" id="all_n-api_napi_create_array_with_length">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_array_with_length"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_array_with_length</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">size_t</span> length,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] length</code>: The initial length of the <code>Array</code>.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Array</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns a Node-API value corresponding to a JavaScript <code>Array</code> type.
The <code>Array</code>'s length property is set to the passed-in length parameter.
However, the underlying buffer is not guaranteed to be pre-allocated by the VM
when the array is created. That behavior is left to the underlying VM
implementation. If the buffer must be a contiguous block of memory that can be
directly read and/or written via C, consider using
<a href="#all_n-api_napi_create_external_arraybuffer"><code>napi_create_external_arraybuffer</code></a>.</p>
<p>JavaScript arrays are described in
<a href="https://tc39.github.io/ecma262/#sec-array-objects">Section 22.1</a> of the ECMAScript Language Specification.</p>
<h5><code>napi_create_arraybuffer</code><span><a class="mark" href="#all_n-api_napi_create_arraybuffer" id="all_n-api_napi_create_arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_arraybuffer"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_arraybuffer</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">size_t</span> byte_length,
<span class="hljs-type">void</span>** data,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] length</code>: The length in bytes of the array buffer to create.</li>
<li><code>[out] data</code>: Pointer to the underlying byte buffer of the <code>ArrayBuffer</code>.
<code>data</code> can optionally be ignored by passing <code>NULL</code>.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>ArrayBuffer</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns a Node-API value corresponding to a JavaScript <code>ArrayBuffer</code>.
<code>ArrayBuffer</code>s are used to represent fixed-length binary data buffers. They are
normally used as a backing-buffer for <code>TypedArray</code> objects.
The <code>ArrayBuffer</code> allocated will have an underlying byte buffer whose size is
determined by the <code>length</code> parameter that's passed in.
The underlying buffer is optionally returned back to the caller in case the
caller wants to directly manipulate the buffer. This buffer can only be
written to directly from native code. To write to this buffer from JavaScript,
a typed array or <code>DataView</code> object would need to be created.</p>
<p>JavaScript <code>ArrayBuffer</code> objects are described in
<a href="https://tc39.github.io/ecma262/#sec-arraybuffer-objects">Section 24.1</a> of the ECMAScript Language Specification.</p>
<h5><code>napi_create_buffer</code><span><a class="mark" href="#all_n-api_napi_create_buffer" id="all_n-api_napi_create_buffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_buffer"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_buffer</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">size_t</span> size,
<span class="hljs-type">void</span>** data,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] size</code>: Size in bytes of the underlying buffer.</li>
<li><code>[out] data</code>: Raw pointer to the underlying buffer.
<code>data</code> can optionally be ignored by passing <code>NULL</code>.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a <code>node::Buffer</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allocates a <code>node::Buffer</code> object. While this is still a
fully-supported data structure, in most cases using a <code>TypedArray</code> will suffice.</p>
<h5><code>napi_create_buffer_copy</code><span><a class="mark" href="#all_n-api_napi_create_buffer_copy" id="all_n-api_napi_create_buffer_copy">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_buffer_copy"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_buffer_copy</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">size_t</span> length,
<span class="hljs-type">const</span> <span class="hljs-type">void</span>* data,
<span class="hljs-type">void</span>** result_data,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] size</code>: Size in bytes of the input buffer (should be the same as the size
of the new buffer).</li>
<li><code>[in] data</code>: Raw pointer to the underlying buffer to copy from.</li>
<li><code>[out] result_data</code>: Pointer to the new <code>Buffer</code>'s underlying data buffer.
<code>result_data</code> can optionally be ignored by passing <code>NULL</code>.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a <code>node::Buffer</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allocates a <code>node::Buffer</code> object and initializes it with data copied
from the passed-in buffer. While this is still a fully-supported data
structure, in most cases using a <code>TypedArray</code> will suffice.</p>
<h5><code>napi_create_date</code><span><a class="mark" href="#all_n-api_napi_create_date" id="all_n-api_napi_create_date">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_date"></a></h5>
<div class="api_metadata">
<span>Added in: v11.11.0, v10.17.0</span>
<span>N-API version: 5</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_date</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">double</span> time,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] time</code>: ECMAScript time value in milliseconds since 01 January, 1970 UTC.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Date</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API does not observe leap seconds; they are ignored, as
ECMAScript aligns with POSIX time specification.</p>
<p>This API allocates a JavaScript <code>Date</code> object.</p>
<p>JavaScript <code>Date</code> objects are described in
<a href="https://tc39.github.io/ecma262/#sec-date-objects">Section 20.3</a> of the ECMAScript Language Specification.</p>
<h5><code>napi_create_external</code><span><a class="mark" href="#all_n-api_napi_create_external" id="all_n-api_napi_create_external">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_external"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_external</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">void</span>* data,
napi_finalize finalize_cb,
<span class="hljs-type">void</span>* finalize_hint,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] data</code>: Raw pointer to the external data.</li>
<li><code>[in] finalize_cb</code>: Optional callback to call when the external value is being
collected. <a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
collection.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing an external value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allocates a JavaScript value with external data attached to it. This
is used to pass external data through JavaScript code, so it can be retrieved
later by native code using <a href="#all_n-api_napi_get_value_external"><code>napi_get_value_external</code></a>.</p>
<p>The API adds a <code>napi_finalize</code> callback which will be called when the JavaScript
object just created has been garbage collected.</p>
<p>The created value is not an object, and therefore does not support additional
properties. It is considered a distinct value type: calling <code>napi_typeof()</code> with
an external value yields <code>napi_external</code>.</p>
<h5><code>napi_create_external_arraybuffer</code><span><a class="mark" href="#all_n-api_napi_create_external_arraybuffer" id="all_n-api_napi_create_external_arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_external_arraybuffer"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status
<span class="hljs-title function_">napi_create_external_arraybuffer</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">void</span>* external_data,
<span class="hljs-type">size_t</span> byte_length,
napi_finalize finalize_cb,
<span class="hljs-type">void</span>* finalize_hint,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] external_data</code>: Pointer to the underlying byte buffer of the
<code>ArrayBuffer</code>.</li>
<li><code>[in] byte_length</code>: The length in bytes of the underlying buffer.</li>
<li><code>[in] finalize_cb</code>: Optional callback to call when the <code>ArrayBuffer</code> is being
collected. <a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
collection.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>ArrayBuffer</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p><strong>Some runtimes other than Node.js have dropped support for external buffers</strong>.
On runtimes other than Node.js this method may return
<code>napi_no_external_buffers_allowed</code> to indicate that external
buffers are not supported. One such runtime is Electron as
described in this issue
<a href="https://github.com/electron/electron/issues/35801">electron/issues/35801</a>.</p>
<p>In order to maintain broadest compatibility with all runtimes
you may define <code>NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED</code> in your addon before
includes for the node-api headers. Doing so will hide the 2 functions
that create external buffers. This will ensure a compilation error
occurs if you accidentally use one of these methods.</p>
<p>This API returns a Node-API value corresponding to a JavaScript <code>ArrayBuffer</code>.
The underlying byte buffer of the <code>ArrayBuffer</code> is externally allocated and
managed. The caller must ensure that the byte buffer remains valid until the
finalize callback is called.</p>
<p>The API adds a <code>napi_finalize</code> callback which will be called when the JavaScript
object just created has been garbage collected.</p>
<p>JavaScript <code>ArrayBuffer</code>s are described in
<a href="https://tc39.github.io/ecma262/#sec-arraybuffer-objects">Section 24.1</a> of the ECMAScript Language Specification.</p>
<h5><code>napi_create_external_buffer</code><span><a class="mark" href="#all_n-api_napi_create_external_buffer" id="all_n-api_napi_create_external_buffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_external_buffer"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_external_buffer</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">size_t</span> length,
<span class="hljs-type">void</span>* data,
napi_finalize finalize_cb,
<span class="hljs-type">void</span>* finalize_hint,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] length</code>: Size in bytes of the input buffer (should be the same as the
size of the new buffer).</li>
<li><code>[in] data</code>: Raw pointer to the underlying buffer to expose to JavaScript.</li>
<li><code>[in] finalize_cb</code>: Optional callback to call when the <code>ArrayBuffer</code> is being
collected. <a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
collection.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a <code>node::Buffer</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p><strong>Some runtimes other than Node.js have dropped support for external buffers</strong>.
On runtimes other than Node.js this method may return
<code>napi_no_external_buffers_allowed</code> to indicate that external
buffers are not supported. One such runtime is Electron as
described in this issue
<a href="https://github.com/electron/electron/issues/35801">electron/issues/35801</a>.</p>
<p>In order to maintain broadest compatibility with all runtimes
you may define <code>NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED</code> in your addon before
includes for the node-api headers. Doing so will hide the 2 functions
that create external buffers. This will ensure a compilation error
occurs if you accidentally use one of these methods.</p>
<p>This API allocates a <code>node::Buffer</code> object and initializes it with data
backed by the passed in buffer. While this is still a fully-supported data
structure, in most cases using a <code>TypedArray</code> will suffice.</p>
<p>The API adds a <code>napi_finalize</code> callback which will be called when the JavaScript
object just created has been garbage collected.</p>
<p>For Node.js >=4 <code>Buffers</code> are <code>Uint8Array</code>s.</p>
<h5><code>napi_create_object</code><span><a class="mark" href="#all_n-api_napi_create_object" id="all_n-api_napi_create_object">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_object"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_object</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Object</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allocates a default JavaScript <code>Object</code>.
It is the equivalent of doing <code>new Object()</code> in JavaScript.</p>
<p>The JavaScript <code>Object</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-object-type">Section 6.1.7</a> of the
ECMAScript Language Specification.</p>
<h5><code>napi_create_symbol</code><span><a class="mark" href="#all_n-api_napi_create_symbol" id="all_n-api_napi_create_symbol">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_symbol"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_symbol</span><span class="hljs-params">(napi_env env,
napi_value description,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] description</code>: Optional <code>napi_value</code> which refers to a JavaScript
<code>string</code> to be set as the description for the symbol.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>symbol</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>symbol</code> value from a UTF8-encoded C string.</p>
<p>The JavaScript <code>symbol</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-symbol-objects">Section 19.4</a>
of the ECMAScript Language Specification.</p>
<h5><code>node_api_symbol_for</code><span><a class="mark" href="#all_n-api_node_api_symbol_for" id="all_n-api_node_api_symbol_for">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_symbol_for"></a></h5>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
<span>N-API version: 9</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">node_api_symbol_for</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8description,
<span class="hljs-type">size_t</span> length,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] utf8description</code>: UTF-8 C string representing the text to be used as the
description for the symbol.</li>
<li><code>[in] length</code>: The length of the description string in bytes, or
<code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>symbol</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API searches in the global registry for an existing symbol with the given
description. If the symbol already exists it will be returned, otherwise a new
symbol will be created in the registry.</p>
<p>The JavaScript <code>symbol</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-symbol-objects">Section 19.4</a> of the ECMAScript
Language Specification.</p>
<h5><code>napi_create_typedarray</code><span><a class="mark" href="#all_n-api_napi_create_typedarray" id="all_n-api_napi_create_typedarray">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_typedarray"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_typedarray</span><span class="hljs-params">(napi_env env,
napi_typedarray_type type,
<span class="hljs-type">size_t</span> length,
napi_value arraybuffer,
<span class="hljs-type">size_t</span> byte_offset,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] type</code>: Scalar datatype of the elements within the <code>TypedArray</code>.</li>
<li><code>[in] length</code>: Number of elements in the <code>TypedArray</code>.</li>
<li><code>[in] arraybuffer</code>: <code>ArrayBuffer</code> underlying the typed array.</li>
<li><code>[in] byte_offset</code>: The byte offset within the <code>ArrayBuffer</code> from which to
start projecting the <code>TypedArray</code>.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>TypedArray</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>TypedArray</code> object over an existing
<code>ArrayBuffer</code>. <code>TypedArray</code> objects provide an array-like view over an
underlying data buffer where each element has the same underlying binary scalar
datatype.</p>
<p>It's required that <code>(length * size_of_element) + byte_offset</code> should
be <= the size in bytes of the array passed in. If not, a <code>RangeError</code> exception
is raised.</p>
<p>JavaScript <code>TypedArray</code> objects are described in
<a href="https://tc39.github.io/ecma262/#sec-typedarray-objects">Section 22.2</a> of the ECMAScript Language Specification.</p>
<h5><code>napi_create_dataview</code><span><a class="mark" href="#all_n-api_napi_create_dataview" id="all_n-api_napi_create_dataview">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_dataview"></a></h5>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_dataview</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">size_t</span> byte_length,
napi_value arraybuffer,
<span class="hljs-type">size_t</span> byte_offset,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] length</code>: Number of elements in the <code>DataView</code>.</li>
<li><code>[in] arraybuffer</code>: <code>ArrayBuffer</code> underlying the <code>DataView</code>.</li>
<li><code>[in] byte_offset</code>: The byte offset within the <code>ArrayBuffer</code> from which to
start projecting the <code>DataView</code>.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>DataView</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>DataView</code> object over an existing <code>ArrayBuffer</code>.
<code>DataView</code> objects provide an array-like view over an underlying data buffer,
but one which allows items of different size and type in the <code>ArrayBuffer</code>.</p>
<p>It is required that <code>byte_length + byte_offset</code> is less than or equal to the
size in bytes of the array passed in. If not, a <code>RangeError</code> exception is
raised.</p>
<p>JavaScript <code>DataView</code> objects are described in
<a href="https://tc39.github.io/ecma262/#sec-dataview-objects">Section 24.3</a> of the ECMAScript Language Specification.</p>
<h4>Functions to convert from C types to Node-API<span><a class="mark" href="#all_n-api_functions-to-convert-from-c-types-to-node-api" id="all_n-api_functions-to-convert-from-c-types-to-node-api">#</a></span><a aria-hidden="true" class="legacy" id="n_api_functions_to_convert_from_c_types_to_node_api"></a></h4>
<h5><code>napi_create_int32</code><span><a class="mark" href="#all_n-api_napi_create_int32" id="all_n-api_napi_create_int32">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_int32"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_int32</span><span class="hljs-params">(napi_env env, <span class="hljs-type">int32_t</span> value, napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: Integer value to be represented in JavaScript.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to convert from the C <code>int32_t</code> type to the JavaScript
<code>number</code> type.</p>
<p>The JavaScript <code>number</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification.</p>
<h5><code>napi_create_uint32</code><span><a class="mark" href="#all_n-api_napi_create_uint32" id="all_n-api_napi_create_uint32">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_uint32"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_uint32</span><span class="hljs-params">(napi_env env, <span class="hljs-type">uint32_t</span> value, napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: Unsigned integer value to be represented in JavaScript.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to convert from the C <code>uint32_t</code> type to the JavaScript
<code>number</code> type.</p>
<p>The JavaScript <code>number</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification.</p>
<h5><code>napi_create_int64</code><span><a class="mark" href="#all_n-api_napi_create_int64" id="all_n-api_napi_create_int64">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_int64"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_int64</span><span class="hljs-params">(napi_env env, <span class="hljs-type">int64_t</span> value, napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: Integer value to be represented in JavaScript.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to convert from the C <code>int64_t</code> type to the JavaScript
<code>number</code> type.</p>
<p>The JavaScript <code>number</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a>
of the ECMAScript Language Specification. Note the complete range of <code>int64_t</code>
cannot be represented with full precision in JavaScript. Integer values
outside the range of <a href="https://tc39.github.io/ecma262/#sec-number.min_safe_integer"><code>Number.MIN_SAFE_INTEGER</code></a> <code>-(2**53 - 1)</code> -
<a href="https://tc39.github.io/ecma262/#sec-number.max_safe_integer"><code>Number.MAX_SAFE_INTEGER</code></a> <code>(2**53 - 1)</code> will lose precision.</p>
<h5><code>napi_create_double</code><span><a class="mark" href="#all_n-api_napi_create_double" id="all_n-api_napi_create_double">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_double"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_double</span><span class="hljs-params">(napi_env env, <span class="hljs-type">double</span> value, napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: Double-precision value to be represented in JavaScript.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to convert from the C <code>double</code> type to the JavaScript
<code>number</code> type.</p>
<p>The JavaScript <code>number</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification.</p>
<h5><code>napi_create_bigint_int64</code><span><a class="mark" href="#all_n-api_napi_create_bigint_int64" id="all_n-api_napi_create_bigint_int64">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_bigint_int64"></a></h5>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_bigint_int64</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">int64_t</span> value,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: Integer value to be represented in JavaScript.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>BigInt</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API converts the C <code>int64_t</code> type to the JavaScript <code>BigInt</code> type.</p>
<h5><code>napi_create_bigint_uint64</code><span><a class="mark" href="#all_n-api_napi_create_bigint_uint64" id="all_n-api_napi_create_bigint_uint64">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_bigint_uint64"></a></h5>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_bigint_uint64</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">uint64_t</span> value,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: Unsigned integer value to be represented in JavaScript.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>BigInt</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API converts the C <code>uint64_t</code> type to the JavaScript <code>BigInt</code> type.</p>
<h5><code>napi_create_bigint_words</code><span><a class="mark" href="#all_n-api_napi_create_bigint_words" id="all_n-api_napi_create_bigint_words">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_bigint_words"></a></h5>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_bigint_words</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">int</span> sign_bit,
<span class="hljs-type">size_t</span> word_count,
<span class="hljs-type">const</span> <span class="hljs-type">uint64_t</span>* words,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] sign_bit</code>: Determines if the resulting <code>BigInt</code> will be positive or
negative.</li>
<li><code>[in] word_count</code>: The length of the <code>words</code> array.</li>
<li><code>[in] words</code>: An array of <code>uint64_t</code> little-endian 64-bit words.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>BigInt</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API converts an array of unsigned 64-bit words into a single <code>BigInt</code>
value.</p>
<p>The resulting <code>BigInt</code> is calculated as: (–1)<sup><code>sign_bit</code></sup> (<code>words[0]</code>
× (2<sup>64</sup>)<sup>0</sup> + <code>words[1]</code> × (2<sup>64</sup>)<sup>1</sup> + …)</p>
<h5><code>napi_create_string_latin1</code><span><a class="mark" href="#all_n-api_napi_create_string_latin1" id="all_n-api_napi_create_string_latin1">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_string_latin1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_string_latin1</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* str,
<span class="hljs-type">size_t</span> length,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] str</code>: Character buffer representing an ISO-8859-1-encoded string.</li>
<li><code>[in] length</code>: The length of the string in bytes, or <code>NAPI_AUTO_LENGTH</code> if it
is null-terminated.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>string</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>string</code> value from an ISO-8859-1-encoded C
string. The native string is copied.</p>
<p>The JavaScript <code>string</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
<h5><code>node_api_create_external_string_latin1</code><span><a class="mark" href="#all_n-api_node_api_create_external_string_latin1" id="all_n-api_node_api_create_external_string_latin1">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_create_external_string_latin1"></a></h5>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status
<span class="hljs-title function_">node_api_create_external_string_latin1</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">char</span>* str,
<span class="hljs-type">size_t</span> length,
napi_finalize finalize_callback,
<span class="hljs-type">void</span>* finalize_hint,
napi_value* result,
<span class="hljs-type">bool</span>* copied)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] str</code>: Character buffer representing an ISO-8859-1-encoded string.</li>
<li><code>[in] length</code>: The length of the string in bytes, or <code>NAPI_AUTO_LENGTH</code> if it
is null-terminated.</li>
<li><code>[in] finalize_callback</code>: The function to call when the string is being
collected. The function will be called with the following parameters:
<ul>
<li><code>[in] env</code>: The environment in which the add-on is running. This value
may be null if the string is being collected as part of the termination
of the worker or the main Node.js instance.</li>
<li><code>[in] data</code>: This is the value <code>str</code> as a <code>void*</code> pointer.</li>
<li><code>[in] finalize_hint</code>: This is the value <code>finalize_hint</code> that was given
to the API.
<a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.
This parameter is optional. Passing a null value means that the add-on
doesn't need to be notified when the corresponding JavaScript string is
collected.</li>
</ul>
</li>
<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
collection.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>string</code>.</li>
<li><code>[out] copied</code>: Whether the string was copied. If it was, the finalizer will
already have been invoked to destroy <code>str</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>string</code> value from an ISO-8859-1-encoded C
string. The native string may not be copied and must thus exist for the entire
life cycle of the JavaScript value.</p>
<p>The JavaScript <code>string</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
<h5><code>napi_create_string_utf16</code><span><a class="mark" href="#all_n-api_napi_create_string_utf16" id="all_n-api_napi_create_string_utf16">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_string_utf16"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_string_utf16</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char16_t</span>* str,
<span class="hljs-type">size_t</span> length,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] str</code>: Character buffer representing a UTF16-LE-encoded string.</li>
<li><code>[in] length</code>: The length of the string in two-byte code units, or
<code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>string</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>string</code> value from a UTF16-LE-encoded C string.
The native string is copied.</p>
<p>The JavaScript <code>string</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
<h5><code>node_api_create_external_string_utf16</code><span><a class="mark" href="#all_n-api_node_api_create_external_string_utf16" id="all_n-api_node_api_create_external_string_utf16">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_create_external_string_utf16"></a></h5>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status
<span class="hljs-title function_">node_api_create_external_string_utf16</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">char16_t</span>* str,
<span class="hljs-type">size_t</span> length,
napi_finalize finalize_callback,
<span class="hljs-type">void</span>* finalize_hint,
napi_value* result,
<span class="hljs-type">bool</span>* copied)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] str</code>: Character buffer representing a UTF16-LE-encoded string.</li>
<li><code>[in] length</code>: The length of the string in two-byte code units, or
<code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li>
<li><code>[in] finalize_callback</code>: The function to call when the string is being
collected. The function will be called with the following parameters:
<ul>
<li><code>[in] env</code>: The environment in which the add-on is running. This value
may be null if the string is being collected as part of the termination
of the worker or the main Node.js instance.</li>
<li><code>[in] data</code>: This is the value <code>str</code> as a <code>void*</code> pointer.</li>
<li><code>[in] finalize_hint</code>: This is the value <code>finalize_hint</code> that was given
to the API.
<a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.
This parameter is optional. Passing a null value means that the add-on
doesn't need to be notified when the corresponding JavaScript string is
collected.</li>
</ul>
</li>
<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
collection.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>string</code>.</li>
<li><code>[out] copied</code>: Whether the string was copied. If it was, the finalizer will
already have been invoked to destroy <code>str</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>string</code> value from a UTF16-LE-encoded C string.
The native string may not be copied and must thus exist for the entire life
cycle of the JavaScript value.</p>
<p>The JavaScript <code>string</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
<h5><code>napi_create_string_utf8</code><span><a class="mark" href="#all_n-api_napi_create_string_utf8" id="all_n-api_napi_create_string_utf8">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_string_utf8"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_string_utf8</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* str,
<span class="hljs-type">size_t</span> length,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] str</code>: Character buffer representing a UTF8-encoded string.</li>
<li><code>[in] length</code>: The length of the string in bytes, or <code>NAPI_AUTO_LENGTH</code> if it
is null-terminated.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>string</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>string</code> value from a UTF8-encoded C string.
The native string is copied.</p>
<p>The JavaScript <code>string</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
<h4>Functions to create optimized property keys<span><a class="mark" href="#all_n-api_functions-to-create-optimized-property-keys" id="all_n-api_functions-to-create-optimized-property-keys">#</a></span><a aria-hidden="true" class="legacy" id="n_api_functions_to_create_optimized_property_keys"></a></h4>
<p>Many JavaScript engines including V8 use internalized strings as keys
to set and get property values. They typically use a hash table to create
and lookup such strings. While it adds some cost per key creation, it improves
the performance after that by enabling comparison of string pointers instead
of the whole strings.</p>
<p>If a new JavaScript string is intended to be used as a property key, then for
some JavaScript engines it will be more efficient to use the functions in this
section. Otherwise, use the <code>napi_create_string_utf8</code> or
<code>node_api_create_external_string_utf8</code> series functions as there may be
additional overhead in creating/storing strings with the property key
creation methods.</p>
<h5><code>node_api_create_property_key_latin1</code><span><a class="mark" href="#all_n-api_node_api_create_property_key_latin1" id="all_n-api_node_api_create_property_key_latin1">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_create_property_key_latin1"></a></h5>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status NAPI_CDECL <span class="hljs-title function_">node_api_create_property_key_latin1</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* str,
<span class="hljs-type">size_t</span> length,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] str</code>: Character buffer representing an ISO-8859-1-encoded string.</li>
<li><code>[in] length</code>: The length of the string in bytes, or <code>NAPI_AUTO_LENGTH</code> if it
is null-terminated.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing an optimized JavaScript <code>string</code>
to be used as a property key for objects.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates an optimized JavaScript <code>string</code> value from
an ISO-8859-1-encoded C string to be used as a property key for objects.
The native string is copied. In contrast with <code>napi_create_string_latin1</code>,
subsequent calls to this function with the same <code>str</code> pointer may benefit from a speedup
in the creation of the requested <code>napi_value</code>, depending on the engine.</p>
<p>The JavaScript <code>string</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
<h5><code>node_api_create_property_key_utf16</code><span><a class="mark" href="#all_n-api_node_api_create_property_key_utf16" id="all_n-api_node_api_create_property_key_utf16">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_create_property_key_utf16"></a></h5>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status NAPI_CDECL <span class="hljs-title function_">node_api_create_property_key_utf16</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char16_t</span>* str,
<span class="hljs-type">size_t</span> length,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] str</code>: Character buffer representing a UTF16-LE-encoded string.</li>
<li><code>[in] length</code>: The length of the string in two-byte code units, or
<code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing an optimized JavaScript <code>string</code>
to be used as a property key for objects.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates an optimized JavaScript <code>string</code> value from
a UTF16-LE-encoded C string to be used as a property key for objects.
The native string is copied.</p>
<p>The JavaScript <code>string</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
<h5><code>node_api_create_property_key_utf8</code><span><a class="mark" href="#all_n-api_node_api_create_property_key_utf8" id="all_n-api_node_api_create_property_key_utf8">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_create_property_key_utf8"></a></h5>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status NAPI_CDECL <span class="hljs-title function_">node_api_create_property_key_utf8</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* str,
<span class="hljs-type">size_t</span> length,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] str</code>: Character buffer representing a UTF8-encoded string.</li>
<li><code>[in] length</code>: The length of the string in two-byte code units, or
<code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing an optimized JavaScript <code>string</code>
to be used as a property key for objects.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates an optimized JavaScript <code>string</code> value from
a UTF8-encoded C string to be used as a property key for objects.
The native string is copied.</p>
<p>The JavaScript <code>string</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
<h4>Functions to convert from Node-API to C types<span><a class="mark" href="#all_n-api_functions-to-convert-from-node-api-to-c-types" id="all_n-api_functions-to-convert-from-node-api-to-c-types">#</a></span><a aria-hidden="true" class="legacy" id="n_api_functions_to_convert_from_node_api_to_c_types"></a></h4>
<h5><code>napi_get_array_length</code><span><a class="mark" href="#all_n-api_napi_get_array_length" id="all_n-api_napi_get_array_length">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_array_length"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_array_length</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">uint32_t</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing the JavaScript <code>Array</code> whose length is
being queried.</li>
<li><code>[out] result</code>: <code>uint32</code> representing length of the array.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the length of an array.</p>
<p><code>Array</code> length is described in <a href="https://tc39.github.io/ecma262/#sec-properties-of-array-instances-length">Section 22.1.4.1</a> of the ECMAScript Language
Specification.</p>
<h5><code>napi_get_arraybuffer_info</code><span><a class="mark" href="#all_n-api_napi_get_arraybuffer_info" id="all_n-api_napi_get_arraybuffer_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_arraybuffer_info"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_arraybuffer_info</span><span class="hljs-params">(napi_env env,
napi_value arraybuffer,
<span class="hljs-type">void</span>** data,
<span class="hljs-type">size_t</span>* byte_length)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] arraybuffer</code>: <code>napi_value</code> representing the <code>ArrayBuffer</code> being queried.</li>
<li><code>[out] data</code>: The underlying data buffer of the <code>ArrayBuffer</code>. If byte_length
is <code>0</code>, this may be <code>NULL</code> or any other pointer value.</li>
<li><code>[out] byte_length</code>: Length in bytes of the underlying data buffer.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to retrieve the underlying data buffer of an <code>ArrayBuffer</code> and
its length.</p>
<p><em>WARNING</em>: Use caution while using this API. The lifetime of the underlying data
buffer is managed by the <code>ArrayBuffer</code> even after it's returned. A
possible safe way to use this API is in conjunction with
<a href="#all_n-api_napi_create_reference"><code>napi_create_reference</code></a>, which can be used to guarantee control over the
lifetime of the <code>ArrayBuffer</code>. It's also safe to use the returned data buffer
within the same callback as long as there are no calls to other APIs that might
trigger a GC.</p>
<h5><code>napi_get_buffer_info</code><span><a class="mark" href="#all_n-api_napi_get_buffer_info" id="all_n-api_napi_get_buffer_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_buffer_info"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_buffer_info</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">void</span>** data,
<span class="hljs-type">size_t</span>* length)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing the <code>node::Buffer</code> or <code>Uint8Array</code>
being queried.</li>
<li><code>[out] data</code>: The underlying data buffer of the <code>node::Buffer</code> or
<code>Uint8Array</code>. If length is <code>0</code>, this may be <code>NULL</code> or any other pointer value.</li>
<li><code>[out] length</code>: Length in bytes of the underlying data buffer.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method returns the identical <code>data</code> and <code>byte_length</code> as
<a href="#all_n-api_napi_get_typedarray_info"><code>napi_get_typedarray_info</code></a>. And <code>napi_get_typedarray_info</code> accepts a
<code>node::Buffer</code> (a Uint8Array) as the value too.</p>
<p>This API is used to retrieve the underlying data buffer of a <code>node::Buffer</code>
and its length.</p>
<p><em>Warning</em>: Use caution while using this API since the underlying data buffer's
lifetime is not guaranteed if it's managed by the VM.</p>
<h5><code>napi_get_prototype</code><span><a class="mark" href="#all_n-api_napi_get_prototype" id="all_n-api_napi_get_prototype">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_prototype"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_prototype</span><span class="hljs-params">(napi_env env,
napi_value object,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] object</code>: <code>napi_value</code> representing JavaScript <code>Object</code> whose prototype
to return. This returns the equivalent of <code>Object.getPrototypeOf</code> (which is
not the same as the function's <code>prototype</code> property).</li>
<li><code>[out] result</code>: <code>napi_value</code> representing prototype of the given object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<h5><code>napi_get_typedarray_info</code><span><a class="mark" href="#all_n-api_napi_get_typedarray_info" id="all_n-api_napi_get_typedarray_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_typedarray_info"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_typedarray_info</span><span class="hljs-params">(napi_env env,
napi_value typedarray,
napi_typedarray_type* type,
<span class="hljs-type">size_t</span>* length,
<span class="hljs-type">void</span>** data,
napi_value* arraybuffer,
<span class="hljs-type">size_t</span>* byte_offset)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] typedarray</code>: <code>napi_value</code> representing the <code>TypedArray</code> whose
properties to query.</li>
<li><code>[out] type</code>: Scalar datatype of the elements within the <code>TypedArray</code>.</li>
<li><code>[out] length</code>: The number of elements in the <code>TypedArray</code>.</li>
<li><code>[out] data</code>: The data buffer underlying the <code>TypedArray</code> adjusted by
the <code>byte_offset</code> value so that it points to the first element in the
<code>TypedArray</code>. If the length of the array is <code>0</code>, this may be <code>NULL</code> or
any other pointer value.</li>
<li><code>[out] arraybuffer</code>: The <code>ArrayBuffer</code> underlying the <code>TypedArray</code>.</li>
<li><code>[out] byte_offset</code>: The byte offset within the underlying native array
at which the first element of the arrays is located. The value for the data
parameter has already been adjusted so that data points to the first element
in the array. Therefore, the first byte of the native array would be at
<code>data - byte_offset</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns various properties of a typed array.</p>
<p>Any of the out parameters may be <code>NULL</code> if that property is unneeded.</p>
<p><em>Warning</em>: Use caution while using this API since the underlying data buffer
is managed by the VM.</p>
<h5><code>napi_get_dataview_info</code><span><a class="mark" href="#all_n-api_napi_get_dataview_info" id="all_n-api_napi_get_dataview_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_dataview_info"></a></h5>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_dataview_info</span><span class="hljs-params">(napi_env env,
napi_value dataview,
<span class="hljs-type">size_t</span>* byte_length,
<span class="hljs-type">void</span>** data,
napi_value* arraybuffer,
<span class="hljs-type">size_t</span>* byte_offset)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] dataview</code>: <code>napi_value</code> representing the <code>DataView</code> whose
properties to query.</li>
<li><code>[out] byte_length</code>: Number of bytes in the <code>DataView</code>.</li>
<li><code>[out] data</code>: The data buffer underlying the <code>DataView</code>.
If byte_length is <code>0</code>, this may be <code>NULL</code> or any other pointer value.</li>
<li><code>[out] arraybuffer</code>: <code>ArrayBuffer</code> underlying the <code>DataView</code>.</li>
<li><code>[out] byte_offset</code>: The byte offset within the data buffer from which
to start projecting the <code>DataView</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Any of the out parameters may be <code>NULL</code> if that property is unneeded.</p>
<p>This API returns various properties of a <code>DataView</code>.</p>
<h5><code>napi_get_date_value</code><span><a class="mark" href="#all_n-api_napi_get_date_value" id="all_n-api_napi_get_date_value">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_date_value"></a></h5>
<div class="api_metadata">
<span>Added in: v11.11.0, v10.17.0</span>
<span>N-API version: 5</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_date_value</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">double</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing a JavaScript <code>Date</code>.</li>
<li><code>[out] result</code>: Time value as a <code>double</code> represented as milliseconds since
midnight at the beginning of 01 January, 1970 UTC.</li>
</ul>
<p>This API does not observe leap seconds; they are ignored, as
ECMAScript aligns with POSIX time specification.</p>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-date <code>napi_value</code> is passed
in it returns <code>napi_date_expected</code>.</p>
<p>This API returns the C double primitive of time value for the given JavaScript
<code>Date</code>.</p>
<h5><code>napi_get_value_bool</code><span><a class="mark" href="#all_n-api_napi_get_value_bool" id="all_n-api_napi_get_value_bool">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_bool"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_bool</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>Boolean</code>.</li>
<li><code>[out] result</code>: C boolean primitive equivalent of the given JavaScript
<code>Boolean</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-boolean <code>napi_value</code> is
passed in it returns <code>napi_boolean_expected</code>.</p>
<p>This API returns the C boolean primitive equivalent of the given JavaScript
<code>Boolean</code>.</p>
<h5><code>napi_get_value_double</code><span><a class="mark" href="#all_n-api_napi_get_value_double" id="all_n-api_napi_get_value_double">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_double"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_double</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">double</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>number</code>.</li>
<li><code>[out] result</code>: C double primitive equivalent of the given JavaScript
<code>number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code> is passed
in it returns <code>napi_number_expected</code>.</p>
<p>This API returns the C double primitive equivalent of the given JavaScript
<code>number</code>.</p>
<h5><code>napi_get_value_bigint_int64</code><span><a class="mark" href="#all_n-api_napi_get_value_bigint_int64" id="all_n-api_napi_get_value_bigint_int64">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_bigint_int64"></a></h5>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_bigint_int64</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">int64_t</span>* result,
<span class="hljs-type">bool</span>* lossless)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>BigInt</code>.</li>
<li><code>[out] result</code>: C <code>int64_t</code> primitive equivalent of the given JavaScript
<code>BigInt</code>.</li>
<li><code>[out] lossless</code>: Indicates whether the <code>BigInt</code> value was converted
losslessly.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>BigInt</code> is passed in it
returns <code>napi_bigint_expected</code>.</p>
<p>This API returns the C <code>int64_t</code> primitive equivalent of the given JavaScript
<code>BigInt</code>. If needed it will truncate the value, setting <code>lossless</code> to <code>false</code>.</p>
<h5><code>napi_get_value_bigint_uint64</code><span><a class="mark" href="#all_n-api_napi_get_value_bigint_uint64" id="all_n-api_napi_get_value_bigint_uint64">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_bigint_uint64"></a></h5>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_bigint_uint64</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">uint64_t</span>* result,
<span class="hljs-type">bool</span>* lossless)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>BigInt</code>.</li>
<li><code>[out] result</code>: C <code>uint64_t</code> primitive equivalent of the given JavaScript
<code>BigInt</code>.</li>
<li><code>[out] lossless</code>: Indicates whether the <code>BigInt</code> value was converted
losslessly.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>BigInt</code> is passed in it
returns <code>napi_bigint_expected</code>.</p>
<p>This API returns the C <code>uint64_t</code> primitive equivalent of the given JavaScript
<code>BigInt</code>. If needed it will truncate the value, setting <code>lossless</code> to <code>false</code>.</p>
<h5><code>napi_get_value_bigint_words</code><span><a class="mark" href="#all_n-api_napi_get_value_bigint_words" id="all_n-api_napi_get_value_bigint_words">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_bigint_words"></a></h5>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_bigint_words</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">int</span>* sign_bit,
<span class="hljs-type">size_t</span>* word_count,
<span class="hljs-type">uint64_t</span>* words)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>BigInt</code>.</li>
<li><code>[out] sign_bit</code>: Integer representing if the JavaScript <code>BigInt</code> is positive
or negative.</li>
<li><code>[in/out] word_count</code>: Must be initialized to the length of the <code>words</code>
array. Upon return, it will be set to the actual number of words that
would be needed to store this <code>BigInt</code>.</li>
<li><code>[out] words</code>: Pointer to a pre-allocated 64-bit word array.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API converts a single <code>BigInt</code> value into a sign bit, 64-bit little-endian
array, and the number of elements in the array. <code>sign_bit</code> and <code>words</code> may be
both set to <code>NULL</code>, in order to get only <code>word_count</code>.</p>
<h5><code>napi_get_value_external</code><span><a class="mark" href="#all_n-api_napi_get_value_external" id="all_n-api_napi_get_value_external">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_external"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_external</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">void</span>** result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript external value.</li>
<li><code>[out] result</code>: Pointer to the data wrapped by the JavaScript external value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-external <code>napi_value</code> is
passed in it returns <code>napi_invalid_arg</code>.</p>
<p>This API retrieves the external data pointer that was previously passed to
<code>napi_create_external()</code>.</p>
<h5><code>napi_get_value_int32</code><span><a class="mark" href="#all_n-api_napi_get_value_int32" id="all_n-api_napi_get_value_int32">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_int32"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_int32</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">int32_t</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>number</code>.</li>
<li><code>[out] result</code>: C <code>int32</code> primitive equivalent of the given JavaScript
<code>number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code>
is passed in <code>napi_number_expected</code>.</p>
<p>This API returns the C <code>int32</code> primitive equivalent
of the given JavaScript <code>number</code>.</p>
<p>If the number exceeds the range of the 32 bit integer, then the result is
truncated to the equivalent of the bottom 32 bits. This can result in a large
positive number becoming a negative number if the value is > 2<sup>31</sup> - 1.</p>
<p>Non-finite number values (<code>NaN</code>, <code>+Infinity</code>, or <code>-Infinity</code>) set the
result to zero.</p>
<h5><code>napi_get_value_int64</code><span><a class="mark" href="#all_n-api_napi_get_value_int64" id="all_n-api_napi_get_value_int64">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_int64"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_int64</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">int64_t</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>number</code>.</li>
<li><code>[out] result</code>: C <code>int64</code> primitive equivalent of the given JavaScript
<code>number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code>
is passed in it returns <code>napi_number_expected</code>.</p>
<p>This API returns the C <code>int64</code> primitive equivalent of the given JavaScript
<code>number</code>.</p>
<p><code>number</code> values outside the range of <a href="https://tc39.github.io/ecma262/#sec-number.min_safe_integer"><code>Number.MIN_SAFE_INTEGER</code></a>
<code>-(2**53 - 1)</code> - <a href="https://tc39.github.io/ecma262/#sec-number.max_safe_integer"><code>Number.MAX_SAFE_INTEGER</code></a> <code>(2**53 - 1)</code> will lose
precision.</p>
<p>Non-finite number values (<code>NaN</code>, <code>+Infinity</code>, or <code>-Infinity</code>) set the
result to zero.</p>
<h5><code>napi_get_value_string_latin1</code><span><a class="mark" href="#all_n-api_napi_get_value_string_latin1" id="all_n-api_napi_get_value_string_latin1">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_string_latin1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_string_latin1</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">char</span>* buf,
<span class="hljs-type">size_t</span> bufsize,
<span class="hljs-type">size_t</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript string.</li>
<li><code>[in] buf</code>: Buffer to write the ISO-8859-1-encoded string into. If <code>NULL</code> is
passed in, the length of the string in bytes and excluding the null terminator
is returned in <code>result</code>.</li>
<li><code>[in] bufsize</code>: Size of the destination buffer. When this value is
insufficient, the returned string is truncated and null-terminated.</li>
<li><code>[out] result</code>: Number of bytes copied into the buffer, excluding the null
terminator.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>string</code> <code>napi_value</code>
is passed in it returns <code>napi_string_expected</code>.</p>
<p>This API returns the ISO-8859-1-encoded string corresponding the value passed
in.</p>
<h5><code>napi_get_value_string_utf8</code><span><a class="mark" href="#all_n-api_napi_get_value_string_utf8" id="all_n-api_napi_get_value_string_utf8">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_string_utf8"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_string_utf8</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">char</span>* buf,
<span class="hljs-type">size_t</span> bufsize,
<span class="hljs-type">size_t</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript string.</li>
<li><code>[in] buf</code>: Buffer to write the UTF8-encoded string into. If <code>NULL</code> is passed
in, the length of the string in bytes and excluding the null terminator is
returned in <code>result</code>.</li>
<li><code>[in] bufsize</code>: Size of the destination buffer. When this value is
insufficient, the returned string is truncated and null-terminated.</li>
<li><code>[out] result</code>: Number of bytes copied into the buffer, excluding the null
terminator.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>string</code> <code>napi_value</code>
is passed in it returns <code>napi_string_expected</code>.</p>
<p>This API returns the UTF8-encoded string corresponding the value passed in.</p>
<h5><code>napi_get_value_string_utf16</code><span><a class="mark" href="#all_n-api_napi_get_value_string_utf16" id="all_n-api_napi_get_value_string_utf16">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_string_utf16"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_string_utf16</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">char16_t</span>* buf,
<span class="hljs-type">size_t</span> bufsize,
<span class="hljs-type">size_t</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript string.</li>
<li><code>[in] buf</code>: Buffer to write the UTF16-LE-encoded string into. If <code>NULL</code> is
passed in, the length of the string in 2-byte code units and excluding the
null terminator is returned.</li>
<li><code>[in] bufsize</code>: Size of the destination buffer. When this value is
insufficient, the returned string is truncated and null-terminated.</li>
<li><code>[out] result</code>: Number of 2-byte code units copied into the buffer, excluding
the null terminator.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>string</code> <code>napi_value</code>
is passed in it returns <code>napi_string_expected</code>.</p>
<p>This API returns the UTF16-encoded string corresponding the value passed in.</p>
<h5><code>napi_get_value_uint32</code><span><a class="mark" href="#all_n-api_napi_get_value_uint32" id="all_n-api_napi_get_value_uint32">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_uint32"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_value_uint32</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">uint32_t</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>number</code>.</li>
<li><code>[out] result</code>: C primitive equivalent of the given <code>napi_value</code> as a
<code>uint32_t</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code>
is passed in it returns <code>napi_number_expected</code>.</p>
<p>This API returns the C primitive equivalent of the given <code>napi_value</code> as a
<code>uint32_t</code>.</p>
<h4>Functions to get global instances<span><a class="mark" href="#all_n-api_functions-to-get-global-instances" id="all_n-api_functions-to-get-global-instances">#</a></span><a aria-hidden="true" class="legacy" id="n_api_functions_to_get_global_instances"></a></h4>
<h5><code>napi_get_boolean</code><span><a class="mark" href="#all_n-api_napi_get_boolean" id="all_n-api_napi_get_boolean">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_boolean"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_boolean</span><span class="hljs-params">(napi_env env, <span class="hljs-type">bool</span> value, napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The value of the boolean to retrieve.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing JavaScript <code>Boolean</code> singleton to
retrieve.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to return the JavaScript singleton object that is used to
represent the given boolean value.</p>
<h5><code>napi_get_global</code><span><a class="mark" href="#all_n-api_napi_get_global" id="all_n-api_napi_get_global">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_global"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_global</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing JavaScript <code>global</code> object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the <code>global</code> object.</p>
<h5><code>napi_get_null</code><span><a class="mark" href="#all_n-api_napi_get_null" id="all_n-api_napi_get_null">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_null"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_null</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing JavaScript <code>null</code> object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the <code>null</code> object.</p>
<h5><code>napi_get_undefined</code><span><a class="mark" href="#all_n-api_napi_get_undefined" id="all_n-api_napi_get_undefined">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_undefined"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_undefined</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing JavaScript Undefined value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the Undefined object.</p>
</section><section><h3>Working with JavaScript values and abstract operations<span><a class="mark" href="#all_n-api_working-with-javascript-values-and-abstract-operations" id="all_n-api_working-with-javascript-values-and-abstract-operations">#</a></span><a aria-hidden="true" class="legacy" id="n_api_working_with_javascript_values_and_abstract_operations"></a></h3>
<p>Node-API exposes a set of APIs to perform some abstract operations on JavaScript
values. Some of these operations are documented under <a href="https://tc39.github.io/ecma262/#sec-abstract-operations">Section 7</a>
of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p>
<p>These APIs support doing one of the following:</p>
<ol>
<li>Coerce JavaScript values to specific JavaScript types (such as <code>number</code> or
<code>string</code>).</li>
<li>Check the type of a JavaScript value.</li>
<li>Check for equality between two JavaScript values.</li>
</ol>
<h4><code>napi_coerce_to_bool</code><span><a class="mark" href="#all_n-api_napi_coerce_to_bool" id="all_n-api_napi_coerce_to_bool">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_coerce_to_bool"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_coerce_to_bool</span><span class="hljs-params">(napi_env env,
napi_value value,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to coerce.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>Boolean</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API implements the abstract operation <code>ToBoolean()</code> as defined in
<a href="https://tc39.github.io/ecma262/#sec-toboolean">Section 7.1.2</a> of the ECMAScript Language Specification.</p>
<h4><code>napi_coerce_to_number</code><span><a class="mark" href="#all_n-api_napi_coerce_to_number" id="all_n-api_napi_coerce_to_number">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_coerce_to_number"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_coerce_to_number</span><span class="hljs-params">(napi_env env,
napi_value value,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to coerce.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API implements the abstract operation <code>ToNumber()</code> as defined in
<a href="https://tc39.github.io/ecma262/#sec-tonumber">Section 7.1.3</a> of the ECMAScript Language Specification.
This function potentially runs JS code if the passed-in value is an
object.</p>
<h4><code>napi_coerce_to_object</code><span><a class="mark" href="#all_n-api_napi_coerce_to_object" id="all_n-api_napi_coerce_to_object">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_coerce_to_object"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_coerce_to_object</span><span class="hljs-params">(napi_env env,
napi_value value,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to coerce.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>Object</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API implements the abstract operation <code>ToObject()</code> as defined in
<a href="https://tc39.github.io/ecma262/#sec-toobject">Section 7.1.13</a> of the ECMAScript Language Specification.</p>
<h4><code>napi_coerce_to_string</code><span><a class="mark" href="#all_n-api_napi_coerce_to_string" id="all_n-api_napi_coerce_to_string">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_coerce_to_string"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_coerce_to_string</span><span class="hljs-params">(napi_env env,
napi_value value,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to coerce.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>string</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API implements the abstract operation <code>ToString()</code> as defined in
<a href="https://tc39.github.io/ecma262/#sec-toobject">Section 7.1.13</a> of the ECMAScript Language Specification.
This function potentially runs JS code if the passed-in value is an
object.</p>
<h4><code>napi_typeof</code><span><a class="mark" href="#all_n-api_napi_typeof" id="all_n-api_napi_typeof">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_typeof"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_typeof</span><span class="hljs-params">(napi_env env, napi_value value, napi_valuetype* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value whose type to query.</li>
<li><code>[out] result</code>: The type of the JavaScript value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<ul>
<li><code>napi_invalid_arg</code> if the type of <code>value</code> is not a known ECMAScript type and
<code>value</code> is not an External value.</li>
</ul>
<p>This API represents behavior similar to invoking the <code>typeof</code> Operator on
the object as defined in <a href="https://tc39.github.io/ecma262/#sec-typeof-operator">Section 12.5.5</a> of the ECMAScript Language
Specification. However, there are some differences:</p>
<ol>
<li>It has support for detecting an External value.</li>
<li>It detects <code>null</code> as a separate type, while ECMAScript <code>typeof</code> would detect
<code>object</code>.</li>
</ol>
<p>If <code>value</code> has a type that is invalid, an error is returned.</p>
<h4><code>napi_instanceof</code><span><a class="mark" href="#all_n-api_napi_instanceof" id="all_n-api_napi_instanceof">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_instanceof"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_instanceof</span><span class="hljs-params">(napi_env env,
napi_value object,
napi_value constructor,
<span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] object</code>: The JavaScript value to check.</li>
<li><code>[in] constructor</code>: The JavaScript function object of the constructor function
to check against.</li>
<li><code>[out] result</code>: Boolean that is set to true if <code>object instanceof constructor</code>
is true.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API represents invoking the <code>instanceof</code> Operator on the object as
defined in <a href="https://tc39.github.io/ecma262/#sec-instanceofoperator">Section 12.10.4</a> of the ECMAScript Language Specification.</p>
<h4><code>napi_is_array</code><span><a class="mark" href="#all_n-api_napi_is_array" id="all_n-api_napi_is_array">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_array"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_array</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given object is an array.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API represents invoking the <code>IsArray</code> operation on the object
as defined in <a href="https://tc39.github.io/ecma262/#sec-isarray">Section 7.2.2</a> of the ECMAScript Language Specification.</p>
<h4><code>napi_is_arraybuffer</code><span><a class="mark" href="#all_n-api_napi_is_arraybuffer" id="all_n-api_napi_is_arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_arraybuffer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_arraybuffer</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given object is an <code>ArrayBuffer</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in is an array buffer.</p>
<h4><code>napi_is_buffer</code><span><a class="mark" href="#all_n-api_napi_is_buffer" id="all_n-api_napi_is_buffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_buffer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_buffer</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a <code>node::Buffer</code> or
<code>Uint8Array</code> object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in is a buffer or Uint8Array.
<a href="#all_n-api_napi_is_typedarray"><code>napi_is_typedarray</code></a> should be preferred if the caller needs to check if the
value is a Uint8Array.</p>
<h4><code>napi_is_date</code><span><a class="mark" href="#all_n-api_napi_is_date" id="all_n-api_napi_is_date">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_date"></a></h4>
<div class="api_metadata">
<span>Added in: v11.11.0, v10.17.0</span>
<span>N-API version: 5</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_date</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a JavaScript <code>Date</code>
object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in is a date.</p>
<h4><code>napi_is_error</code><span><a class="mark" href="#all_n-api_napi_is_error_1" id="all_n-api_napi_is_error_1">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_error_1"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_error</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents an <code>Error</code> object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in is an <code>Error</code>.</p>
<h4><code>napi_is_typedarray</code><span><a class="mark" href="#all_n-api_napi_is_typedarray" id="all_n-api_napi_is_typedarray">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_typedarray"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_typedarray</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a <code>TypedArray</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in is a typed array.</p>
<h4><code>napi_is_dataview</code><span><a class="mark" href="#all_n-api_napi_is_dataview" id="all_n-api_napi_is_dataview">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_dataview"></a></h4>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_dataview</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a <code>DataView</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in is a <code>DataView</code>.</p>
<h4><code>napi_strict_equals</code><span><a class="mark" href="#all_n-api_napi_strict_equals" id="all_n-api_napi_strict_equals">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_strict_equals"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_strict_equals</span><span class="hljs-params">(napi_env env,
napi_value lhs,
napi_value rhs,
<span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] lhs</code>: The JavaScript value to check.</li>
<li><code>[in] rhs</code>: The JavaScript value to check against.</li>
<li><code>[out] result</code>: Whether the two <code>napi_value</code> objects are equal.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API represents the invocation of the Strict Equality algorithm as
defined in <a href="https://tc39.github.io/ecma262/#sec-strict-equality-comparison">Section 7.2.14</a> of the ECMAScript Language Specification.</p>
<h4><code>napi_detach_arraybuffer</code><span><a class="mark" href="#all_n-api_napi_detach_arraybuffer" id="all_n-api_napi_detach_arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_detach_arraybuffer"></a></h4>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0, v10.22.0</span>
<span>N-API version: 7</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_detach_arraybuffer</span><span class="hljs-params">(napi_env env,
napi_value arraybuffer)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] arraybuffer</code>: The JavaScript <code>ArrayBuffer</code> to be detached.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-detachable <code>ArrayBuffer</code> is
passed in it returns <code>napi_detachable_arraybuffer_expected</code>.</p>
<p>Generally, an <code>ArrayBuffer</code> is non-detachable if it has been detached before.
The engine may impose additional conditions on whether an <code>ArrayBuffer</code> is
detachable. For example, V8 requires that the <code>ArrayBuffer</code> be external,
that is, created with <a href="#all_n-api_napi_create_external_arraybuffer"><code>napi_create_external_arraybuffer</code></a>.</p>
<p>This API represents the invocation of the <code>ArrayBuffer</code> detach operation as
defined in <a href="https://tc39.es/ecma262/#sec-detacharraybuffer">Section 24.1.1.3</a> of the ECMAScript Language Specification.</p>
<h4><code>napi_is_detached_arraybuffer</code><span><a class="mark" href="#all_n-api_napi_is_detached_arraybuffer" id="all_n-api_napi_is_detached_arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_detached_arraybuffer"></a></h4>
<div class="api_metadata">
<span>Added in: v13.3.0, v12.16.0, v10.22.0</span>
<span>N-API version: 7</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_detached_arraybuffer</span><span class="hljs-params">(napi_env env,
napi_value arraybuffer,
<span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] arraybuffer</code>: The JavaScript <code>ArrayBuffer</code> to be checked.</li>
<li><code>[out] result</code>: Whether the <code>arraybuffer</code> is detached.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>The <code>ArrayBuffer</code> is considered detached if its internal data is <code>null</code>.</p>
<p>This API represents the invocation of the <code>ArrayBuffer</code> <code>IsDetachedBuffer</code>
operation as defined in <a href="https://tc39.es/ecma262/#sec-isdetachedbuffer">Section 24.1.1.2</a> of the ECMAScript Language
Specification.</p>
</section><section><h3>Working with JavaScript properties<span><a class="mark" href="#all_n-api_working-with-javascript-properties" id="all_n-api_working-with-javascript-properties">#</a></span><a aria-hidden="true" class="legacy" id="n_api_working_with_javascript_properties"></a></h3>
<p>Node-API exposes a set of APIs to get and set properties on JavaScript
objects. Some of these types are documented under <a href="https://tc39.github.io/ecma262/#sec-abstract-operations">Section 7</a> of the
<a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p>
<p>Properties in JavaScript are represented as a tuple of a key and a value.
Fundamentally, all property keys in Node-API can be represented in one of the
following forms:</p>
<ul>
<li>Named: a simple UTF8-encoded string</li>
<li>Integer-Indexed: an index value represented by <code>uint32_t</code></li>
<li>JavaScript value: these are represented in Node-API by <code>napi_value</code>. This can
be a <code>napi_value</code> representing a <code>string</code>, <code>number</code>, or <code>symbol</code>.</li>
</ul>
<p>Node-API values are represented by the type <code>napi_value</code>.
Any Node-API call that requires a JavaScript value takes in a <code>napi_value</code>.
However, it's the caller's responsibility to make sure that the
<code>napi_value</code> in question is of the JavaScript type expected by the API.</p>
<p>The APIs documented in this section provide a simple interface to
get and set properties on arbitrary JavaScript objects represented by
<code>napi_value</code>.</p>
<p>For instance, consider the following JavaScript code snippet:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> obj = {};
obj.<span class="hljs-property">myProp</span> = <span class="hljs-number">123</span>;</code> <button class="copy-button">copy</button></pre>
<p>The equivalent can be done using Node-API values with the following snippet:</p>
<pre><code class="language-c">napi_status status = napi_generic_failure;
<span class="hljs-comment">// const obj = {}</span>
napi_value obj, value;
status = napi_create_object(env, &obj);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
<span class="hljs-comment">// Create a napi_value for 123</span>
status = napi_create_int32(env, <span class="hljs-number">123</span>, &value);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
<span class="hljs-comment">// obj.myProp = 123</span>
status = napi_set_named_property(env, obj, <span class="hljs-string">"myProp"</span>, value);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;</code> <button class="copy-button">copy</button></pre>
<p>Indexed properties can be set in a similar manner. Consider the following
JavaScript snippet:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> arr = [];
arr[<span class="hljs-number">123</span>] = <span class="hljs-string">'hello'</span>;</code> <button class="copy-button">copy</button></pre>
<p>The equivalent can be done using Node-API values with the following snippet:</p>
<pre><code class="language-c">napi_status status = napi_generic_failure;
<span class="hljs-comment">// const arr = [];</span>
napi_value arr, value;
status = napi_create_array(env, &arr);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
<span class="hljs-comment">// Create a napi_value for 'hello'</span>
status = napi_create_string_utf8(env, <span class="hljs-string">"hello"</span>, NAPI_AUTO_LENGTH, &value);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
<span class="hljs-comment">// arr[123] = 'hello';</span>
status = napi_set_element(env, arr, <span class="hljs-number">123</span>, value);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;</code> <button class="copy-button">copy</button></pre>
<p>Properties can be retrieved using the APIs described in this section.
Consider the following JavaScript snippet:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> arr = [];
<span class="hljs-keyword">const</span> value = arr[<span class="hljs-number">123</span>];</code> <button class="copy-button">copy</button></pre>
<p>The following is the approximate equivalent of the Node-API counterpart:</p>
<pre><code class="language-c">napi_status status = napi_generic_failure;
<span class="hljs-comment">// const arr = []</span>
napi_value arr, value;
status = napi_create_array(env, &arr);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
<span class="hljs-comment">// const value = arr[123]</span>
status = napi_get_element(env, arr, <span class="hljs-number">123</span>, &value);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;</code> <button class="copy-button">copy</button></pre>
<p>Finally, multiple properties can also be defined on an object for performance
reasons. Consider the following JavaScript:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> obj = {};
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperties</span>(obj, {
<span class="hljs-string">'foo'</span>: { <span class="hljs-attr">value</span>: <span class="hljs-number">123</span>, <span class="hljs-attr">writable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">configurable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span> },
<span class="hljs-string">'bar'</span>: { <span class="hljs-attr">value</span>: <span class="hljs-number">456</span>, <span class="hljs-attr">writable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">configurable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span> },
});</code> <button class="copy-button">copy</button></pre>
<p>The following is the approximate equivalent of the Node-API counterpart:</p>
<pre><code class="language-c">napi_status status = napi_status_generic_failure;
<span class="hljs-comment">// const obj = {};</span>
napi_value obj;
status = napi_create_object(env, &obj);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
<span class="hljs-comment">// Create napi_values for 123 and 456</span>
napi_value fooValue, barValue;
status = napi_create_int32(env, <span class="hljs-number">123</span>, &fooValue);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
status = napi_create_int32(env, <span class="hljs-number">456</span>, &barValue);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
<span class="hljs-comment">// Set the properties</span>
napi_property_descriptor descriptors[] = {
{ <span class="hljs-string">"foo"</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, fooValue, napi_writable | napi_configurable, <span class="hljs-literal">NULL</span> },
{ <span class="hljs-string">"bar"</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, barValue, napi_writable | napi_configurable, <span class="hljs-literal">NULL</span> }
}
status = napi_define_properties(env,
obj,
<span class="hljs-keyword">sizeof</span>(descriptors) / <span class="hljs-keyword">sizeof</span>(descriptors[<span class="hljs-number">0</span>]),
descriptors);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;</code> <button class="copy-button">copy</button></pre>
<h4>Structures<span><a class="mark" href="#all_n-api_structures" id="all_n-api_structures">#</a></span><a aria-hidden="true" class="legacy" id="n_api_structures"></a></h4>
<h5><code>napi_property_attributes</code><span><a class="mark" href="#all_n-api_napi_property_attributes" id="all_n-api_napi_property_attributes">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_property_attributes"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.12.0</td>
<td><p>added <code>napi_default_method</code> and <code>napi_default_property</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
napi_default = <span class="hljs-number">0</span>,
napi_writable = <span class="hljs-number">1</span> << <span class="hljs-number">0</span>,
napi_enumerable = <span class="hljs-number">1</span> << <span class="hljs-number">1</span>,
napi_configurable = <span class="hljs-number">1</span> << <span class="hljs-number">2</span>,
<span class="hljs-comment">// Used with napi_define_class to distinguish static properties</span>
<span class="hljs-comment">// from instance properties. Ignored by napi_define_properties.</span>
napi_static = <span class="hljs-number">1</span> << <span class="hljs-number">10</span>,
<span class="hljs-comment">// Default for class methods.</span>
napi_default_method = napi_writable | napi_configurable,
<span class="hljs-comment">// Default for object properties, like in JS obj[prop].</span>
napi_default_jsproperty = napi_writable |
napi_enumerable |
napi_configurable,
} napi_property_attributes;</code> <button class="copy-button">copy</button></pre>
<p><code>napi_property_attributes</code> are flags used to control the behavior of properties
set on a JavaScript object. Other than <code>napi_static</code> they correspond to the
attributes listed in <a href="https://tc39.github.io/ecma262/#table-2">Section 6.1.7.1</a>
of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.
They can be one or more of the following bitflags:</p>
<ul>
<li><code>napi_default</code>: No explicit attributes are set on the property. By default, a
property is read only, not enumerable and not configurable.</li>
<li><code>napi_writable</code>: The property is writable.</li>
<li><code>napi_enumerable</code>: The property is enumerable.</li>
<li><code>napi_configurable</code>: The property is configurable as defined in
<a href="https://tc39.github.io/ecma262/#table-2">Section 6.1.7.1</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</li>
<li><code>napi_static</code>: The property will be defined as a static property on a class as
opposed to an instance property, which is the default. This is used only by
<a href="#all_n-api_napi_define_class"><code>napi_define_class</code></a>. It is ignored by <code>napi_define_properties</code>.</li>
<li><code>napi_default_method</code>: Like a method in a JS class, the property is
configurable and writeable, but not enumerable.</li>
<li><code>napi_default_jsproperty</code>: Like a property set via assignment in JavaScript,
the property is writable, enumerable, and configurable.</li>
</ul>
<h5><code>napi_property_descriptor</code><span><a class="mark" href="#all_n-api_napi_property_descriptor" id="all_n-api_napi_property_descriptor">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_property_descriptor"></a></h5>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
<span class="hljs-comment">// One of utf8name or name should be NULL.</span>
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8name;
napi_value name;
napi_callback method;
napi_callback getter;
napi_callback setter;
napi_value value;
napi_property_attributes attributes;
<span class="hljs-type">void</span>* data;
} napi_property_descriptor;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>utf8name</code>: Optional string describing the key for the property,
encoded as UTF8. One of <code>utf8name</code> or <code>name</code> must be provided for the
property.</li>
<li><code>name</code>: Optional <code>napi_value</code> that points to a JavaScript string or symbol
to be used as the key for the property. One of <code>utf8name</code> or <code>name</code> must
be provided for the property.</li>
<li><code>value</code>: The value that's retrieved by a get access of the property if the
property is a data property. If this is passed in, set <code>getter</code>, <code>setter</code>,
<code>method</code> and <code>data</code> to <code>NULL</code> (since these members won't be used).</li>
<li><code>getter</code>: A function to call when a get access of the property is performed.
If this is passed in, set <code>value</code> and <code>method</code> to <code>NULL</code> (since these members
won't be used). The given function is called implicitly by the runtime when
the property is accessed from JavaScript code (or if a get on the property is
performed using a Node-API call). <a href="#all_n-api_napi_callback"><code>napi_callback</code></a> provides more details.</li>
<li><code>setter</code>: A function to call when a set access of the property is performed.
If this is passed in, set <code>value</code> and <code>method</code> to <code>NULL</code> (since these members
won't be used). The given function is called implicitly by the runtime when
the property is set from JavaScript code (or if a set on the property is
performed using a Node-API call). <a href="#all_n-api_napi_callback"><code>napi_callback</code></a> provides more details.</li>
<li><code>method</code>: Set this to make the property descriptor object's <code>value</code>
property to be a JavaScript function represented by <code>method</code>. If this is
passed in, set <code>value</code>, <code>getter</code> and <code>setter</code> to <code>NULL</code> (since these members
won't be used). <a href="#all_n-api_napi_callback"><code>napi_callback</code></a> provides more details.</li>
<li><code>attributes</code>: The attributes associated with the particular property. See
<a href="#all_n-api_napi_property_attributes"><code>napi_property_attributes</code></a>.</li>
<li><code>data</code>: The callback data passed into <code>method</code>, <code>getter</code> and <code>setter</code> if this
function is invoked.</li>
</ul>
<h4>Functions<span><a class="mark" href="#all_n-api_functions" id="all_n-api_functions">#</a></span><a aria-hidden="true" class="legacy" id="n_api_functions"></a></h4>
<h5><code>napi_get_property_names</code><span><a class="mark" href="#all_n-api_napi_get_property_names" id="all_n-api_napi_get_property_names">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_property_names"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_property_names</span><span class="hljs-params">(napi_env env,
napi_value object,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to retrieve the properties.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing an array of JavaScript values
that represent the property names of the object. The API can be used to
iterate over <code>result</code> using <a href="#all_n-api_napi_get_array_length"><code>napi_get_array_length</code></a>
and <a href="#all_n-api_napi_get_element"><code>napi_get_element</code></a>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the names of the enumerable properties of <code>object</code> as an array
of strings. The properties of <code>object</code> whose key is a symbol will not be
included.</p>
<h5><code>napi_get_all_property_names</code><span><a class="mark" href="#all_n-api_napi_get_all_property_names" id="all_n-api_napi_get_all_property_names">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_all_property_names"></a></h5>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0, v10.20.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_get_all_property_names(napi_env env,
napi_value object,
napi_key_collection_mode key_mode,
napi_key_filter key_filter,
napi_key_conversion key_conversion,
napi_value* result);</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to retrieve the properties.</li>
<li><code>[in] key_mode</code>: Whether to retrieve prototype properties as well.</li>
<li><code>[in] key_filter</code>: Which properties to retrieve
(enumerable/readable/writable).</li>
<li><code>[in] key_conversion</code>: Whether to convert numbered property keys to strings.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing an array of JavaScript values
that represent the property names of the object. <a href="#all_n-api_napi_get_array_length"><code>napi_get_array_length</code></a>
and <a href="#all_n-api_napi_get_element"><code>napi_get_element</code></a> can be used to iterate over <code>result</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns an array containing the names of the available properties
of this object.</p>
<h5><code>napi_set_property</code><span><a class="mark" href="#all_n-api_napi_set_property" id="all_n-api_napi_set_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_set_property"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_set_property</span><span class="hljs-params">(napi_env env,
napi_value object,
napi_value key,
napi_value value)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object on which to set the property.</li>
<li><code>[in] key</code>: The name of the property to set.</li>
<li><code>[in] value</code>: The property value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API set a property on the <code>Object</code> passed in.</p>
<h5><code>napi_get_property</code><span><a class="mark" href="#all_n-api_napi_get_property" id="all_n-api_napi_get_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_property"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_property</span><span class="hljs-params">(napi_env env,
napi_value object,
napi_value key,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to retrieve the property.</li>
<li><code>[in] key</code>: The name of the property to retrieve.</li>
<li><code>[out] result</code>: The value of the property.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API gets the requested property from the <code>Object</code> passed in.</p>
<h5><code>napi_has_property</code><span><a class="mark" href="#all_n-api_napi_has_property" id="all_n-api_napi_has_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_has_property"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_has_property</span><span class="hljs-params">(napi_env env,
napi_value object,
napi_value key,
<span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object to query.</li>
<li><code>[in] key</code>: The name of the property whose existence to check.</li>
<li><code>[out] result</code>: Whether the property exists on the object or not.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in has the named property.</p>
<h5><code>napi_delete_property</code><span><a class="mark" href="#all_n-api_napi_delete_property" id="all_n-api_napi_delete_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_delete_property"></a></h5>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_delete_property</span><span class="hljs-params">(napi_env env,
napi_value object,
napi_value key,
<span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object to query.</li>
<li><code>[in] key</code>: The name of the property to delete.</li>
<li><code>[out] result</code>: Whether the property deletion succeeded or not. <code>result</code> can
optionally be ignored by passing <code>NULL</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API attempts to delete the <code>key</code> own property from <code>object</code>.</p>
<h5><code>napi_has_own_property</code><span><a class="mark" href="#all_n-api_napi_has_own_property" id="all_n-api_napi_has_own_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_has_own_property"></a></h5>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_has_own_property</span><span class="hljs-params">(napi_env env,
napi_value object,
napi_value key,
<span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object to query.</li>
<li><code>[in] key</code>: The name of the own property whose existence to check.</li>
<li><code>[out] result</code>: Whether the own property exists on the object or not.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in has the named own property. <code>key</code> must
be a <code>string</code> or a <code>symbol</code>, or an error will be thrown. Node-API will not
perform any conversion between data types.</p>
<h5><code>napi_set_named_property</code><span><a class="mark" href="#all_n-api_napi_set_named_property" id="all_n-api_napi_set_named_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_set_named_property"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_set_named_property</span><span class="hljs-params">(napi_env env,
napi_value object,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8Name,
napi_value value)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object on which to set the property.</li>
<li><code>[in] utf8Name</code>: The name of the property to set.</li>
<li><code>[in] value</code>: The property value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method is equivalent to calling <a href="#all_n-api_napi_set_property"><code>napi_set_property</code></a> with a <code>napi_value</code>
created from the string passed in as <code>utf8Name</code>.</p>
<h5><code>napi_get_named_property</code><span><a class="mark" href="#all_n-api_napi_get_named_property" id="all_n-api_napi_get_named_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_named_property"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_named_property</span><span class="hljs-params">(napi_env env,
napi_value object,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8Name,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to retrieve the property.</li>
<li><code>[in] utf8Name</code>: The name of the property to get.</li>
<li><code>[out] result</code>: The value of the property.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method is equivalent to calling <a href="#all_n-api_napi_get_property"><code>napi_get_property</code></a> with a <code>napi_value</code>
created from the string passed in as <code>utf8Name</code>.</p>
<h5><code>napi_has_named_property</code><span><a class="mark" href="#all_n-api_napi_has_named_property" id="all_n-api_napi_has_named_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_has_named_property"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_has_named_property</span><span class="hljs-params">(napi_env env,
napi_value object,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8Name,
<span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object to query.</li>
<li><code>[in] utf8Name</code>: The name of the property whose existence to check.</li>
<li><code>[out] result</code>: Whether the property exists on the object or not.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method is equivalent to calling <a href="#all_n-api_napi_has_property"><code>napi_has_property</code></a> with a <code>napi_value</code>
created from the string passed in as <code>utf8Name</code>.</p>
<h5><code>napi_set_element</code><span><a class="mark" href="#all_n-api_napi_set_element" id="all_n-api_napi_set_element">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_set_element"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_set_element</span><span class="hljs-params">(napi_env env,
napi_value object,
<span class="hljs-type">uint32_t</span> index,
napi_value value)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to set the properties.</li>
<li><code>[in] index</code>: The index of the property to set.</li>
<li><code>[in] value</code>: The property value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API sets an element on the <code>Object</code> passed in.</p>
<h5><code>napi_get_element</code><span><a class="mark" href="#all_n-api_napi_get_element" id="all_n-api_napi_get_element">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_element"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_element</span><span class="hljs-params">(napi_env env,
napi_value object,
<span class="hljs-type">uint32_t</span> index,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to retrieve the property.</li>
<li><code>[in] index</code>: The index of the property to get.</li>
<li><code>[out] result</code>: The value of the property.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API gets the element at the requested index.</p>
<h5><code>napi_has_element</code><span><a class="mark" href="#all_n-api_napi_has_element" id="all_n-api_napi_has_element">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_has_element"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_has_element</span><span class="hljs-params">(napi_env env,
napi_value object,
<span class="hljs-type">uint32_t</span> index,
<span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object to query.</li>
<li><code>[in] index</code>: The index of the property whose existence to check.</li>
<li><code>[out] result</code>: Whether the property exists on the object or not.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns if the <code>Object</code> passed in has an element at the
requested index.</p>
<h5><code>napi_delete_element</code><span><a class="mark" href="#all_n-api_napi_delete_element" id="all_n-api_napi_delete_element">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_delete_element"></a></h5>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_delete_element</span><span class="hljs-params">(napi_env env,
napi_value object,
<span class="hljs-type">uint32_t</span> index,
<span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object to query.</li>
<li><code>[in] index</code>: The index of the property to delete.</li>
<li><code>[out] result</code>: Whether the element deletion succeeded or not. <code>result</code> can
optionally be ignored by passing <code>NULL</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API attempts to delete the specified <code>index</code> from <code>object</code>.</p>
<h5><code>napi_define_properties</code><span><a class="mark" href="#all_n-api_napi_define_properties" id="all_n-api_napi_define_properties">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_define_properties"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_define_properties</span><span class="hljs-params">(napi_env env,
napi_value object,
<span class="hljs-type">size_t</span> property_count,
<span class="hljs-type">const</span> napi_property_descriptor* properties)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to retrieve the properties.</li>
<li><code>[in] property_count</code>: The number of elements in the <code>properties</code> array.</li>
<li><code>[in] properties</code>: The array of property descriptors.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method allows the efficient definition of multiple properties on a given
object. The properties are defined using property descriptors (see
<a href="#all_n-api_napi_property_descriptor"><code>napi_property_descriptor</code></a>). Given an array of such property descriptors,
this API will set the properties on the object one at a time, as defined by
<code>DefineOwnProperty()</code> (described in <a href="https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-defineownproperty-p-desc">Section 9.1.6</a> of the ECMA-262
specification).</p>
<h5><code>napi_object_freeze</code><span><a class="mark" href="#all_n-api_napi_object_freeze" id="all_n-api_napi_object_freeze">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_object_freeze"></a></h5>
<div class="api_metadata">
<span>Added in: v14.14.0, v12.20.0</span>
<span>N-API version: 8</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_object_freeze</span><span class="hljs-params">(napi_env env,
napi_value object)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object to freeze.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method freezes a given object. This prevents new properties from
being added to it, existing properties from being removed, prevents
changing the enumerability, configurability, or writability of existing
properties, and prevents the values of existing properties from being changed.
It also prevents the object's prototype from being changed. This is described
in <a href="https://tc39.es/ecma262/#sec-object.freeze">Section 19.1.2.6</a> of the
ECMA-262 specification.</p>
<h5><code>napi_object_seal</code><span><a class="mark" href="#all_n-api_napi_object_seal" id="all_n-api_napi_object_seal">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_object_seal"></a></h5>
<div class="api_metadata">
<span>Added in: v14.14.0, v12.20.0</span>
<span>N-API version: 8</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_object_seal</span><span class="hljs-params">(napi_env env,
napi_value object)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object to seal.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method seals a given object. This prevents new properties from being
added to it, as well as marking all existing properties as non-configurable.
This is described in <a href="https://tc39.es/ecma262/#sec-object.seal">Section 19.1.2.20</a>
of the ECMA-262 specification.</p>
</section><section><h3>Working with JavaScript functions<span><a class="mark" href="#all_n-api_working-with-javascript-functions" id="all_n-api_working-with-javascript-functions">#</a></span><a aria-hidden="true" class="legacy" id="n_api_working_with_javascript_functions"></a></h3>
<p>Node-API provides a set of APIs that allow JavaScript code to
call back into native code. Node-APIs that support calling back
into native code take in a callback functions represented by
the <code>napi_callback</code> type. When the JavaScript VM calls back to
native code, the <code>napi_callback</code> function provided is invoked. The APIs
documented in this section allow the callback function to do the
following:</p>
<ul>
<li>Get information about the context in which the callback was invoked.</li>
<li>Get the arguments passed into the callback.</li>
<li>Return a <code>napi_value</code> back from the callback.</li>
</ul>
<p>Additionally, Node-API provides a set of functions which allow calling
JavaScript functions from native code. One can either call a function
like a regular JavaScript function call, or as a constructor
function.</p>
<p>Any non-<code>NULL</code> data which is passed to this API via the <code>data</code> field of the
<code>napi_property_descriptor</code> items can be associated with <code>object</code> and freed
whenever <code>object</code> is garbage-collected by passing both <code>object</code> and the data to
<a href="#all_n-api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p>
<h4><code>napi_call_function</code><span><a class="mark" href="#all_n-api_napi_call_function" id="all_n-api_napi_call_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_call_function"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_call_function</span><span class="hljs-params">(napi_env env,
napi_value recv,
napi_value func,
<span class="hljs-type">size_t</span> argc,
<span class="hljs-type">const</span> napi_value* argv,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] recv</code>: The <code>this</code> value passed to the called function.</li>
<li><code>[in] func</code>: <code>napi_value</code> representing the JavaScript function to be invoked.</li>
<li><code>[in] argc</code>: The count of elements in the <code>argv</code> array.</li>
<li><code>[in] argv</code>: Array of <code>napi_values</code> representing JavaScript values passed in
as arguments to the function.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript object returned.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method allows a JavaScript function object to be called from a native
add-on. This is the primary mechanism of calling back <em>from</em> the add-on's
native code <em>into</em> JavaScript. For the special case of calling into JavaScript
after an async operation, see <a href="#all_n-api_napi_make_callback"><code>napi_make_callback</code></a>.</p>
<p>A sample use case might look as follows. Consider the following JavaScript
snippet:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">AddTwo</span>(<span class="hljs-params">num</span>) {
<span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
}
<span class="hljs-variable language_">global</span>.<span class="hljs-property">AddTwo</span> = <span class="hljs-title class_">AddTwo</span>;</code> <button class="copy-button">copy</button></pre>
<p>Then, the above function can be invoked from a native add-on using the
following code:</p>
<pre><code class="language-c"><span class="hljs-comment">// Get the function named "AddTwo" on the global object</span>
napi_value global, add_two, arg;
napi_status status = napi_get_global(env, &global);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
status = napi_get_named_property(env, global, <span class="hljs-string">"AddTwo"</span>, &add_two);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
<span class="hljs-comment">// const arg = 1337</span>
status = napi_create_int32(env, <span class="hljs-number">1337</span>, &arg);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
napi_value* argv = &arg;
<span class="hljs-type">size_t</span> argc = <span class="hljs-number">1</span>;
<span class="hljs-comment">// AddTwo(arg);</span>
napi_value return_val;
status = napi_call_function(env, global, add_two, argc, argv, &return_val);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
<span class="hljs-comment">// Convert the result back to a native type</span>
<span class="hljs-type">int32_t</span> result;
status = napi_get_value_int32(env, return_val, &result);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;</code> <button class="copy-button">copy</button></pre>
<h4><code>napi_create_function</code><span><a class="mark" href="#all_n-api_napi_create_function" id="all_n-api_napi_create_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_function"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_function</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8name,
<span class="hljs-type">size_t</span> length,
napi_callback cb,
<span class="hljs-type">void</span>* data,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] utf8Name</code>: Optional name of the function encoded as UTF8. This is
visible within JavaScript as the new function object's <code>name</code> property.</li>
<li><code>[in] length</code>: The length of the <code>utf8name</code> in bytes, or <code>NAPI_AUTO_LENGTH</code> if
it is null-terminated.</li>
<li><code>[in] cb</code>: The native function which should be called when this function
object is invoked. <a href="#all_n-api_napi_callback"><code>napi_callback</code></a> provides more details.</li>
<li><code>[in] data</code>: User-provided data context. This will be passed back into the
function when invoked later.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript function object for
the newly created function.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allows an add-on author to create a function object in native code.
This is the primary mechanism to allow calling <em>into</em> the add-on's native code
<em>from</em> JavaScript.</p>
<p>The newly created function is not automatically visible from script after this
call. Instead, a property must be explicitly set on any object that is visible
to JavaScript, in order for the function to be accessible from script.</p>
<p>In order to expose a function as part of the
add-on's module exports, set the newly created function on the exports
object. A sample module might look as follows:</p>
<pre><code class="language-c">napi_value <span class="hljs-title function_">SayHello</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"Hello\n"</span>);
<span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
}
napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> {
napi_status status;
napi_value fn;
status = napi_create_function(env, <span class="hljs-literal">NULL</span>, <span class="hljs-number">0</span>, SayHello, <span class="hljs-literal">NULL</span>, &fn);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
status = napi_set_named_property(env, exports, <span class="hljs-string">"sayHello"</span>, fn);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-keyword">return</span> exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)</code> <button class="copy-button">copy</button></pre>
<p>Given the above code, the add-on can be used from JavaScript as follows:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myaddon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./addon'</span>);
myaddon.<span class="hljs-title function_">sayHello</span>();</code> <button class="copy-button">copy</button></pre>
<p>The string passed to <code>require()</code> is the name of the target in <code>binding.gyp</code>
responsible for creating the <code>.node</code> file.</p>
<p>Any non-<code>NULL</code> data which is passed to this API via the <code>data</code> parameter can
be associated with the resulting JavaScript function (which is returned in the
<code>result</code> parameter) and freed whenever the function is garbage-collected by
passing both the JavaScript function and the data to <a href="#all_n-api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p>
<p>JavaScript <code>Function</code>s are described in <a href="https://tc39.github.io/ecma262/#sec-function-objects">Section 19.2</a> of the ECMAScript
Language Specification.</p>
<h4><code>napi_get_cb_info</code><span><a class="mark" href="#all_n-api_napi_get_cb_info" id="all_n-api_napi_get_cb_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_cb_info"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_cb_info</span><span class="hljs-params">(napi_env env,
napi_callback_info cbinfo,
<span class="hljs-type">size_t</span>* argc,
napi_value* argv,
napi_value* thisArg,
<span class="hljs-type">void</span>** data)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] cbinfo</code>: The callback info passed into the callback function.</li>
<li><code>[in-out] argc</code>: Specifies the length of the provided <code>argv</code> array and
receives the actual count of arguments. <code>argc</code> can
optionally be ignored by passing <code>NULL</code>.</li>
<li><code>[out] argv</code>: C array of <code>napi_value</code>s to which the arguments will be
copied. If there are more arguments than the provided count, only the
requested number of arguments are copied. If there are fewer arguments
provided than claimed, the rest of <code>argv</code> is filled with <code>napi_value</code> values
that represent <code>undefined</code>. <code>argv</code> can optionally be ignored by
passing <code>NULL</code>.</li>
<li><code>[out] thisArg</code>: Receives the JavaScript <code>this</code> argument for the call.
<code>thisArg</code> can optionally be ignored by passing <code>NULL</code>.</li>
<li><code>[out] data</code>: Receives the data pointer for the callback. <code>data</code> can
optionally be ignored by passing <code>NULL</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method is used within a callback function to retrieve details about the
call like the arguments and the <code>this</code> pointer from a given callback info.</p>
<h4><code>napi_get_new_target</code><span><a class="mark" href="#all_n-api_napi_get_new_target" id="all_n-api_napi_get_new_target">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_new_target"></a></h4>
<div class="api_metadata">
<span>Added in: v8.6.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_new_target</span><span class="hljs-params">(napi_env env,
napi_callback_info cbinfo,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] cbinfo</code>: The callback info passed into the callback function.</li>
<li><code>[out] result</code>: The <code>new.target</code> of the constructor call.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the <code>new.target</code> of the constructor call. If the current
callback is not a constructor call, the result is <code>NULL</code>.</p>
<h4><code>napi_new_instance</code><span><a class="mark" href="#all_n-api_napi_new_instance" id="all_n-api_napi_new_instance">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_new_instance"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_new_instance</span><span class="hljs-params">(napi_env env,
napi_value cons,
<span class="hljs-type">size_t</span> argc,
napi_value* argv,
napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] cons</code>: <code>napi_value</code> representing the JavaScript function to be invoked
as a constructor.</li>
<li><code>[in] argc</code>: The count of elements in the <code>argv</code> array.</li>
<li><code>[in] argv</code>: Array of JavaScript values as <code>napi_value</code> representing the
arguments to the constructor. If <code>argc</code> is zero this parameter may be
omitted by passing in <code>NULL</code>.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript object returned,
which in this case is the constructed object.</li>
</ul>
<p>This method is used to instantiate a new JavaScript value using a given
<code>napi_value</code> that represents the constructor for the object. For example,
consider the following snippet:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">MyObject</span>(<span class="hljs-params">param</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">param</span> = param;
}
<span class="hljs-keyword">const</span> arg = <span class="hljs-string">'hello'</span>;
<span class="hljs-keyword">const</span> value = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyObject</span>(arg);</code> <button class="copy-button">copy</button></pre>
<p>The following can be approximated in Node-API using the following snippet:</p>
<pre><code class="language-c"><span class="hljs-comment">// Get the constructor function MyObject</span>
napi_value global, constructor, arg, value;
napi_status status = napi_get_global(env, &global);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
status = napi_get_named_property(env, global, <span class="hljs-string">"MyObject"</span>, &constructor);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
<span class="hljs-comment">// const arg = "hello"</span>
status = napi_create_string_utf8(env, <span class="hljs-string">"hello"</span>, NAPI_AUTO_LENGTH, &arg);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;
napi_value* argv = &arg;
<span class="hljs-type">size_t</span> argc = <span class="hljs-number">1</span>;
<span class="hljs-comment">// const value = new MyObject(arg)</span>
status = napi_new_instance(env, constructor, argc, argv, &value);</code> <button class="copy-button">copy</button></pre>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
</section><section><h3>Object wrap<span><a class="mark" href="#all_n-api_object-wrap" id="all_n-api_object-wrap">#</a></span><a aria-hidden="true" class="legacy" id="n_api_object_wrap"></a></h3>
<p>Node-API offers a way to "wrap" C++ classes and instances so that the class
constructor and methods can be called from JavaScript.</p>
<ol>
<li>The <a href="#all_n-api_napi_define_class"><code>napi_define_class</code></a> API defines a JavaScript class with constructor,
static properties and methods, and instance properties and methods that
correspond to the C++ class.</li>
<li>When JavaScript code invokes the constructor, the constructor callback
uses <a href="#all_n-api_napi_wrap"><code>napi_wrap</code></a> to wrap a new C++ instance in a JavaScript object,
then returns the wrapper object.</li>
<li>When JavaScript code invokes a method or property accessor on the class,
the corresponding <code>napi_callback</code> C++ function is invoked. For an instance
callback, <a href="#all_n-api_napi_unwrap"><code>napi_unwrap</code></a> obtains the C++ instance that is the target of
the call.</li>
</ol>
<p>For wrapped objects it may be difficult to distinguish between a function
called on a class prototype and a function called on an instance of a class.
A common pattern used to address this problem is to save a persistent
reference to the class constructor for later <code>instanceof</code> checks.</p>
<pre><code class="language-c">napi_value MyClass_constructor = <span class="hljs-literal">NULL</span>;
status = napi_get_reference_value(env, MyClass::es_constructor, &MyClass_constructor);
assert(napi_ok == status);
<span class="hljs-type">bool</span> is_instance = <span class="hljs-literal">false</span>;
status = napi_instanceof(env, es_this, MyClass_constructor, &is_instance);
assert(napi_ok == status);
<span class="hljs-keyword">if</span> (is_instance) {
<span class="hljs-comment">// napi_unwrap() ...</span>
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// otherwise...</span>
}</code> <button class="copy-button">copy</button></pre>
<p>The reference must be freed once it is no longer needed.</p>
<p>There are occasions where <code>napi_instanceof()</code> is insufficient for ensuring that
a JavaScript object is a wrapper for a certain native type. This is the case
especially when wrapped JavaScript objects are passed back into the addon via
static methods rather than as the <code>this</code> value of prototype methods. In such
cases there is a chance that they may be unwrapped incorrectly.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myAddon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/my_addon.node'</span>);
<span class="hljs-comment">// `openDatabase()` returns a JavaScript object that wraps a native database</span>
<span class="hljs-comment">// handle.</span>
<span class="hljs-keyword">const</span> dbHandle = myAddon.<span class="hljs-title function_">openDatabase</span>();
<span class="hljs-comment">// `query()` returns a JavaScript object that wraps a native query handle.</span>
<span class="hljs-keyword">const</span> queryHandle = myAddon.<span class="hljs-title function_">query</span>(dbHandle, <span class="hljs-string">'Gimme ALL the things!'</span>);
<span class="hljs-comment">// There is an accidental error in the line below. The first parameter to</span>
<span class="hljs-comment">// `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not</span>
<span class="hljs-comment">// the query handle (`query`), so the correct condition for the while-loop</span>
<span class="hljs-comment">// should be</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// myAddon.queryHasRecords(dbHandle, queryHandle)</span>
<span class="hljs-comment">//</span>
<span class="hljs-keyword">while</span> (myAddon.<span class="hljs-title function_">queryHasRecords</span>(queryHandle, dbHandle)) {
<span class="hljs-comment">// retrieve records</span>
}</code> <button class="copy-button">copy</button></pre>
<p>In the above example <code>myAddon.queryHasRecords()</code> is a method that accepts two
arguments. The first is a database handle and the second is a query handle.
Internally, it unwraps the first argument and casts the resulting pointer to a
native database handle. It then unwraps the second argument and casts the
resulting pointer to a query handle. If the arguments are passed in the wrong
order, the casts will work, however, there is a good chance that the underlying
database operation will fail, or will even cause an invalid memory access.</p>
<p>To ensure that the pointer retrieved from the first argument is indeed a pointer
to a database handle and, similarly, that the pointer retrieved from the second
argument is indeed a pointer to a query handle, the implementation of
<code>queryHasRecords()</code> has to perform a type validation. Retaining the JavaScript
class constructor from which the database handle was instantiated and the
constructor from which the query handle was instantiated in <code>napi_ref</code>s can
help, because <code>napi_instanceof()</code> can then be used to ensure that the instances
passed into <code>queryHashRecords()</code> are indeed of the correct type.</p>
<p>Unfortunately, <code>napi_instanceof()</code> does not protect against prototype
manipulation. For example, the prototype of the database handle instance can be
set to the prototype of the constructor for query handle instances. In this
case, the database handle instance can appear as a query handle instance, and it
will pass the <code>napi_instanceof()</code> test for a query handle instance, while still
containing a pointer to a database handle.</p>
<p>To this end, Node-API provides type-tagging capabilities.</p>
<p>A type tag is a 128-bit integer unique to the addon. Node-API provides the
<code>napi_type_tag</code> structure for storing a type tag. When such a value is passed
along with a JavaScript object or <a href="#all_n-api_napi_create_external">external</a> stored in a <code>napi_value</code> to
<code>napi_type_tag_object()</code>, the JavaScript object will be "marked" with the
type tag. The "mark" is invisible on the JavaScript side. When a JavaScript
object arrives into a native binding, <code>napi_check_object_type_tag()</code> can be used
along with the original type tag to determine whether the JavaScript object was
previously "marked" with the type tag. This creates a type-checking capability
of a higher fidelity than <code>napi_instanceof()</code> can provide, because such type-
tagging survives prototype manipulation and addon unloading/reloading.</p>
<p>Continuing the above example, the following skeleton addon implementation
illustrates the use of <code>napi_type_tag_object()</code> and
<code>napi_check_object_type_tag()</code>.</p>
<pre><code class="language-c"><span class="hljs-comment">// This value is the type tag for a database handle. The command</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.*)/0x\1, 0x\2/'</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// can be used to obtain the two values with which to initialize the structure.</span>
<span class="hljs-type">static</span> <span class="hljs-type">const</span> napi_type_tag DatabaseHandleTypeTag = {
<span class="hljs-number">0x1edf75a38336451d</span>, <span class="hljs-number">0xa5ed9ce2e4c00c38</span>
};
<span class="hljs-comment">// This value is the type tag for a query handle.</span>
<span class="hljs-type">static</span> <span class="hljs-type">const</span> napi_type_tag QueryHandleTypeTag = {
<span class="hljs-number">0x9c73317f9fad44a3</span>, <span class="hljs-number">0x93c3920bf3b0ad6a</span>
};
<span class="hljs-type">static</span> napi_value
<span class="hljs-title function_">openDatabase</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
napi_status status;
napi_value result;
<span class="hljs-comment">// Perform the underlying action which results in a database handle.</span>
DatabaseHandle* dbHandle = open_database();
<span class="hljs-comment">// Create a new, empty JS object.</span>
status = napi_create_object(env, &result);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-comment">// Tag the object to indicate that it holds a pointer to a `DatabaseHandle`.</span>
status = napi_type_tag_object(env, result, &DatabaseHandleTypeTag);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-comment">// Store the pointer to the `DatabaseHandle` structure inside the JS object.</span>
status = napi_wrap(env, result, dbHandle, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-keyword">return</span> result;
}
<span class="hljs-comment">// Later when we receive a JavaScript object purporting to be a database handle</span>
<span class="hljs-comment">// we can use `napi_check_object_type_tag()` to ensure that it is indeed such a</span>
<span class="hljs-comment">// handle.</span>
<span class="hljs-type">static</span> napi_value
<span class="hljs-title function_">query</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
napi_status status;
<span class="hljs-type">size_t</span> argc = <span class="hljs-number">2</span>;
napi_value argv[<span class="hljs-number">2</span>];
<span class="hljs-type">bool</span> is_db_handle;
status = napi_get_cb_info(env, info, &argc, argv, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-comment">// Check that the object passed as the first parameter has the previously</span>
<span class="hljs-comment">// applied tag.</span>
status = napi_check_object_type_tag(env,
argv[<span class="hljs-number">0</span>],
&DatabaseHandleTypeTag,
&is_db_handle);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-comment">// Throw a `TypeError` if it doesn't.</span>
<span class="hljs-keyword">if</span> (!is_db_handle) {
<span class="hljs-comment">// Throw a TypeError.</span>
<span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
}
}</code> <button class="copy-button">copy</button></pre>
<h4><code>napi_define_class</code><span><a class="mark" href="#all_n-api_napi_define_class" id="all_n-api_napi_define_class">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_define_class"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_define_class</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8name,
<span class="hljs-type">size_t</span> length,
napi_callback constructor,
<span class="hljs-type">void</span>* data,
<span class="hljs-type">size_t</span> property_count,
<span class="hljs-type">const</span> napi_property_descriptor* properties,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] utf8name</code>: Name of the JavaScript constructor function. For clarity,
it is recommended to use the C++ class name when wrapping a C++ class.</li>
<li><code>[in] length</code>: The length of the <code>utf8name</code> in bytes, or <code>NAPI_AUTO_LENGTH</code>
if it is null-terminated.</li>
<li><code>[in] constructor</code>: Callback function that handles constructing instances
of the class. When wrapping a C++ class, this method must be a static member
with the <a href="#all_n-api_napi_callback"><code>napi_callback</code></a> signature. A C++ class constructor cannot be
used. <a href="#all_n-api_napi_callback"><code>napi_callback</code></a> provides more details.</li>
<li><code>[in] data</code>: Optional data to be passed to the constructor callback as
the <code>data</code> property of the callback info.</li>
<li><code>[in] property_count</code>: Number of items in the <code>properties</code> array argument.</li>
<li><code>[in] properties</code>: Array of property descriptors describing static and
instance data properties, accessors, and methods on the class
See <code>napi_property_descriptor</code>.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing the constructor function for
the class.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Defines a JavaScript class, including:</p>
<ul>
<li>A JavaScript constructor function that has the class name. When wrapping a
corresponding C++ class, the callback passed via <code>constructor</code> can be used to
instantiate a new C++ class instance, which can then be placed inside the
JavaScript object instance being constructed using <a href="#all_n-api_napi_wrap"><code>napi_wrap</code></a>.</li>
<li>Properties on the constructor function whose implementation can call
corresponding <em>static</em> data properties, accessors, and methods of the C++
class (defined by property descriptors with the <code>napi_static</code> attribute).</li>
<li>Properties on the constructor function's <code>prototype</code> object. When wrapping a
C++ class, <em>non-static</em> data properties, accessors, and methods of the C++
class can be called from the static functions given in the property
descriptors without the <code>napi_static</code> attribute after retrieving the C++ class
instance placed inside the JavaScript object instance by using
<a href="#all_n-api_napi_unwrap"><code>napi_unwrap</code></a>.</li>
</ul>
<p>When wrapping a C++ class, the C++ constructor callback passed via <code>constructor</code>
should be a static method on the class that calls the actual class constructor,
then wraps the new C++ instance in a JavaScript object, and returns the wrapper
object. See <a href="#all_n-api_napi_wrap"><code>napi_wrap</code></a> for details.</p>
<p>The JavaScript constructor function returned from <a href="#all_n-api_napi_define_class"><code>napi_define_class</code></a> is
often saved and used later to construct new instances of the class from native
code, and/or to check whether provided values are instances of the class. In
that case, to prevent the function value from being garbage-collected, a
strong persistent reference to it can be created using
<a href="#all_n-api_napi_create_reference"><code>napi_create_reference</code></a>, ensuring that the reference count is kept >= 1.</p>
<p>Any non-<code>NULL</code> data which is passed to this API via the <code>data</code> parameter or via
the <code>data</code> field of the <code>napi_property_descriptor</code> array items can be associated
with the resulting JavaScript constructor (which is returned in the <code>result</code>
parameter) and freed whenever the class is garbage-collected by passing both
the JavaScript function and the data to <a href="#all_n-api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p>
<h4><code>napi_wrap</code><span><a class="mark" href="#all_n-api_napi_wrap" id="all_n-api_napi_wrap">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_wrap"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_wrap</span><span class="hljs-params">(napi_env env,
napi_value js_object,
<span class="hljs-type">void</span>* native_object,
napi_finalize finalize_cb,
<span class="hljs-type">void</span>* finalize_hint,
napi_ref* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] js_object</code>: The JavaScript object that will be the wrapper for the
native object.</li>
<li><code>[in] native_object</code>: The native instance that will be wrapped in the
JavaScript object.</li>
<li><code>[in] finalize_cb</code>: Optional native callback that can be used to free the
native instance when the JavaScript object has been garbage-collected.
<a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
<li><code>[in] finalize_hint</code>: Optional contextual hint that is passed to the
finalize callback.</li>
<li><code>[out] result</code>: Optional reference to the wrapped object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Wraps a native instance in a JavaScript object. The native instance can be
retrieved later using <code>napi_unwrap()</code>.</p>
<p>When JavaScript code invokes a constructor for a class that was defined using
<code>napi_define_class()</code>, the <code>napi_callback</code> for the constructor is invoked.
After constructing an instance of the native class, the callback must then call
<code>napi_wrap()</code> to wrap the newly constructed instance in the already-created
JavaScript object that is the <code>this</code> argument to the constructor callback.
(That <code>this</code> object was created from the constructor function's <code>prototype</code>,
so it already has definitions of all the instance properties and methods.)</p>
<p>Typically when wrapping a class instance, a finalize callback should be
provided that simply deletes the native instance that is received as the <code>data</code>
argument to the finalize callback.</p>
<p>The optional returned reference is initially a weak reference, meaning it
has a reference count of 0. Typically this reference count would be incremented
temporarily during async operations that require the instance to remain valid.</p>
<p><em>Caution</em>: The optional returned reference (if obtained) should be deleted via
<a href="#all_n-api_napi_delete_reference"><code>napi_delete_reference</code></a> ONLY in response to the finalize callback
invocation. If it is deleted before then, then the finalize callback may never
be invoked. Therefore, when obtaining a reference a finalize callback is also
required in order to enable correct disposal of the reference.</p>
<p>Finalizer callbacks may be deferred, leaving a window where the object has
been garbage collected (and the weak reference is invalid) but the finalizer
hasn't been called yet. When using <code>napi_get_reference_value()</code> on weak
references returned by <code>napi_wrap()</code>, you should still handle an empty result.</p>
<p>Calling <code>napi_wrap()</code> a second time on an object will return an error. To
associate another native instance with the object, use <code>napi_remove_wrap()</code>
first.</p>
<h4><code>napi_unwrap</code><span><a class="mark" href="#all_n-api_napi_unwrap" id="all_n-api_napi_unwrap">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_unwrap"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_unwrap</span><span class="hljs-params">(napi_env env,
napi_value js_object,
<span class="hljs-type">void</span>** result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] js_object</code>: The object associated with the native instance.</li>
<li><code>[out] result</code>: Pointer to the wrapped native instance.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Retrieves a native instance that was previously wrapped in a JavaScript
object using <code>napi_wrap()</code>.</p>
<p>When JavaScript code invokes a method or property accessor on the class, the
corresponding <code>napi_callback</code> is invoked. If the callback is for an instance
method or accessor, then the <code>this</code> argument to the callback is the wrapper
object; the wrapped C++ instance that is the target of the call can be obtained
then by calling <code>napi_unwrap()</code> on the wrapper object.</p>
<h4><code>napi_remove_wrap</code><span><a class="mark" href="#all_n-api_napi_remove_wrap" id="all_n-api_napi_remove_wrap">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_remove_wrap"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_remove_wrap</span><span class="hljs-params">(napi_env env,
napi_value js_object,
<span class="hljs-type">void</span>** result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] js_object</code>: The object associated with the native instance.</li>
<li><code>[out] result</code>: Pointer to the wrapped native instance.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Retrieves a native instance that was previously wrapped in the JavaScript
object <code>js_object</code> using <code>napi_wrap()</code> and removes the wrapping. If a finalize
callback was associated with the wrapping, it will no longer be called when the
JavaScript object becomes garbage-collected.</p>
<h4><code>napi_type_tag_object</code><span><a class="mark" href="#all_n-api_napi_type_tag_object" id="all_n-api_napi_type_tag_object">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_type_tag_object"></a></h4>
<div class="api_metadata">
<span>Added in: v14.8.0, v12.19.0</span>
<span>N-API version: 8</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_type_tag_object</span><span class="hljs-params">(napi_env env,
napi_value js_object,
<span class="hljs-type">const</span> napi_type_tag* type_tag)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] js_object</code>: The JavaScript object or <a href="#all_n-api_napi_create_external">external</a> to be marked.</li>
<li><code>[in] type_tag</code>: The tag with which the object is to be marked.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Associates the value of the <code>type_tag</code> pointer with the JavaScript object or
<a href="#all_n-api_napi_create_external">external</a>. <code>napi_check_object_type_tag()</code> can then be used to compare the tag
that was attached to the object with one owned by the addon to ensure that the
object has the right type.</p>
<p>If the object already has an associated type tag, this API will return
<code>napi_invalid_arg</code>.</p>
<h4><code>napi_check_object_type_tag</code><span><a class="mark" href="#all_n-api_napi_check_object_type_tag" id="all_n-api_napi_check_object_type_tag">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_check_object_type_tag"></a></h4>
<div class="api_metadata">
<span>Added in: v14.8.0, v12.19.0</span>
<span>N-API version: 8</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_check_object_type_tag</span><span class="hljs-params">(napi_env env,
napi_value js_object,
<span class="hljs-type">const</span> napi_type_tag* type_tag,
<span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] js_object</code>: The JavaScript object or <a href="#all_n-api_napi_create_external">external</a> whose type tag to
examine.</li>
<li><code>[in] type_tag</code>: The tag with which to compare any tag found on the object.</li>
<li><code>[out] result</code>: Whether the type tag given matched the type tag on the
object. <code>false</code> is also returned if no type tag was found on the object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Compares the pointer given as <code>type_tag</code> with any that can be found on
<code>js_object</code>. If no tag is found on <code>js_object</code> or, if a tag is found but it does
not match <code>type_tag</code>, then <code>result</code> is set to <code>false</code>. If a tag is found and it
matches <code>type_tag</code>, then <code>result</code> is set to <code>true</code>.</p>
<h4><code>napi_add_finalizer</code><span><a class="mark" href="#all_n-api_napi_add_finalizer" id="all_n-api_napi_add_finalizer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_add_finalizer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 5</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_add_finalizer</span><span class="hljs-params">(napi_env env,
napi_value js_object,
<span class="hljs-type">void</span>* finalize_data,
node_api_basic_finalize finalize_cb,
<span class="hljs-type">void</span>* finalize_hint,
napi_ref* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] js_object</code>: The JavaScript object to which the native data will be
attached.</li>
<li><code>[in] finalize_data</code>: Optional data to be passed to <code>finalize_cb</code>.</li>
<li><code>[in] finalize_cb</code>: Native callback that will be used to free the
native data when the JavaScript object has been garbage-collected.
<a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
<li><code>[in] finalize_hint</code>: Optional contextual hint that is passed to the
finalize callback.</li>
<li><code>[out] result</code>: Optional reference to the JavaScript object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Adds a <code>napi_finalize</code> callback which will be called when the JavaScript object
in <code>js_object</code> has been garbage-collected.</p>
<p>This API can be called multiple times on a single JavaScript object.</p>
<p><em>Caution</em>: The optional returned reference (if obtained) should be deleted via
<a href="#all_n-api_napi_delete_reference"><code>napi_delete_reference</code></a> ONLY in response to the finalize callback
invocation. If it is deleted before then, then the finalize callback may never
be invoked. Therefore, when obtaining a reference a finalize callback is also
required in order to enable correct disposal of the reference.</p>
<h5><code>node_api_post_finalizer</code><span><a class="mark" href="#all_n-api_node_api_post_finalizer" id="all_n-api_node_api_post_finalizer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_post_finalizer"></a></h5>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status <span class="hljs-title function_">node_api_post_finalizer</span><span class="hljs-params">(node_api_basic_env env,
napi_finalize finalize_cb,
<span class="hljs-type">void</span>* finalize_data,
<span class="hljs-type">void</span>* finalize_hint)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] finalize_cb</code>: Native callback that will be used to free the
native data when the JavaScript object has been garbage-collected.
<a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
<li><code>[in] finalize_data</code>: Optional data to be passed to <code>finalize_cb</code>.</li>
<li><code>[in] finalize_hint</code>: Optional contextual hint that is passed to the
finalize callback.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Schedules a <code>napi_finalize</code> callback to be called asynchronously in the
event loop.</p>
<p>Normally, finalizers are called while the GC (garbage collector) collects
objects. At that point calling any Node-API that may cause changes in the GC
state will be disabled and will crash Node.js.</p>
<p><code>node_api_post_finalizer</code> helps to work around this limitation by allowing the
add-on to defer calls to such Node-APIs to a point in time outside of the GC
finalization.</p>
</section><section><h3>Simple asynchronous operations<span><a class="mark" href="#all_n-api_simple-asynchronous-operations" id="all_n-api_simple-asynchronous-operations">#</a></span><a aria-hidden="true" class="legacy" id="n_api_simple_asynchronous_operations"></a></h3>
<p>Addon modules often need to leverage async helpers from libuv as part of their
implementation. This allows them to schedule work to be executed asynchronously
so that their methods can return in advance of the work being completed. This
allows them to avoid blocking overall execution of the Node.js application.</p>
<p>Node-API provides an ABI-stable interface for these
supporting functions which covers the most common asynchronous use cases.</p>
<p>Node-API defines the <code>napi_async_work</code> structure which is used to manage
asynchronous workers. Instances are created/deleted with
<a href="#all_n-api_napi_create_async_work"><code>napi_create_async_work</code></a> and <a href="#all_n-api_napi_delete_async_work"><code>napi_delete_async_work</code></a>.</p>
<p>The <code>execute</code> and <code>complete</code> callbacks are functions that will be
invoked when the executor is ready to execute and when it completes its
task respectively.</p>
<p>The <code>execute</code> function should avoid making any Node-API calls
that could result in the execution of JavaScript or interaction with
JavaScript objects. Most often, any code that needs to make Node-API
calls should be made in <code>complete</code> callback instead.
Avoid using the <code>napi_env</code> parameter in the execute callback as
it will likely execute JavaScript.</p>
<p>These functions implement the following interfaces:</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_execute_callback)</span><span class="hljs-params">(napi_env env,
<span class="hljs-type">void</span>* data)</span>;
<span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_complete_callback)</span><span class="hljs-params">(napi_env env,
napi_status status,
<span class="hljs-type">void</span>* data)</span>;</code> <button class="copy-button">copy</button></pre>
<p>When these methods are invoked, the <code>data</code> parameter passed will be the
addon-provided <code>void*</code> data that was passed into the
<code>napi_create_async_work</code> call.</p>
<p>Once created the async worker can be queued
for execution using the <a href="#all_n-api_napi_queue_async_work"><code>napi_queue_async_work</code></a> function:</p>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_queue_async_work</span><span class="hljs-params">(node_api_basic_env env,
napi_async_work work)</span>;</code> <button class="copy-button">copy</button></pre>
<p><a href="#all_n-api_napi_cancel_async_work"><code>napi_cancel_async_work</code></a> can be used if the work needs
to be cancelled before the work has started execution.</p>
<p>After calling <a href="#all_n-api_napi_cancel_async_work"><code>napi_cancel_async_work</code></a>, the <code>complete</code> callback
will be invoked with a status value of <code>napi_cancelled</code>.
The work should not be deleted before the <code>complete</code>
callback invocation, even when it was cancelled.</p>
<h4><code>napi_create_async_work</code><span><a class="mark" href="#all_n-api_napi_create_async_work" id="all_n-api_napi_create_async_work">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_async_work"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.6.0</td>
<td><p>Added <code>async_resource</code> and <code>async_resource_name</code> parameters.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p><span>Added in: v8.0.0</span></p></td></tr>
</tbody></table>
</details>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_async_work</span><span class="hljs-params">(napi_env env,
napi_value async_resource,
napi_value async_resource_name,
napi_async_execute_callback execute,
napi_async_complete_callback complete,
<span class="hljs-type">void</span>* data,
napi_async_work* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] async_resource</code>: An optional object associated with the async work
that will be passed to possible <code>async_hooks</code> <a href="#all_async_hooks_initasyncid-type-triggerasyncid-resource"><code>init</code> hooks</a>.</li>
<li><code>[in] async_resource_name</code>: Identifier for the kind of resource that is being
provided for diagnostic information exposed by the <code>async_hooks</code> API.</li>
<li><code>[in] execute</code>: The native function which should be called to execute the
logic asynchronously. The given function is called from a worker pool thread
and can execute in parallel with the main event loop thread.</li>
<li><code>[in] complete</code>: The native function which will be called when the
asynchronous logic is completed or is cancelled. The given function is called
from the main event loop thread. <a href="#all_n-api_napi_async_complete_callback"><code>napi_async_complete_callback</code></a> provides
more details.</li>
<li><code>[in] data</code>: User-provided data context. This will be passed back into the
execute and complete functions.</li>
<li><code>[out] result</code>: <code>napi_async_work*</code> which is the handle to the newly created
async work.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allocates a work object that is used to execute logic asynchronously.
It should be freed using <a href="#all_n-api_napi_delete_async_work"><code>napi_delete_async_work</code></a> once the work is no longer
required.</p>
<p><code>async_resource_name</code> should be a null-terminated, UTF-8-encoded string.</p>
<p>The <code>async_resource_name</code> identifier is provided by the user and should be
representative of the type of async work being performed. It is also recommended
to apply namespacing to the identifier, e.g. by including the module name. See
the <a href="#all_async_hooks_type"><code>async_hooks</code> documentation</a> for more information.</p>
<h4><code>napi_delete_async_work</code><span><a class="mark" href="#all_n-api_napi_delete_async_work" id="all_n-api_napi_delete_async_work">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_delete_async_work"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_delete_async_work</span><span class="hljs-params">(napi_env env,
napi_async_work work)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] work</code>: The handle returned by the call to <code>napi_create_async_work</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API frees a previously allocated work object.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h4><code>napi_queue_async_work</code><span><a class="mark" href="#all_n-api_napi_queue_async_work" id="all_n-api_napi_queue_async_work">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_queue_async_work"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_queue_async_work</span><span class="hljs-params">(node_api_basic_env env,
napi_async_work work)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] work</code>: The handle returned by the call to <code>napi_create_async_work</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API requests that the previously allocated work be scheduled
for execution. Once it returns successfully, this API must not be called again
with the same <code>napi_async_work</code> item or the result will be undefined.</p>
<h4><code>napi_cancel_async_work</code><span><a class="mark" href="#all_n-api_napi_cancel_async_work" id="all_n-api_napi_cancel_async_work">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_cancel_async_work"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_cancel_async_work</span><span class="hljs-params">(node_api_basic_env env,
napi_async_work work)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] work</code>: The handle returned by the call to <code>napi_create_async_work</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API cancels queued work if it has not yet
been started. If it has already started executing, it cannot be
cancelled and <code>napi_generic_failure</code> will be returned. If successful,
the <code>complete</code> callback will be invoked with a status value of
<code>napi_cancelled</code>. The work should not be deleted before the <code>complete</code>
callback invocation, even if it has been successfully cancelled.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
</section><section><h3>Custom asynchronous operations<span><a class="mark" href="#all_n-api_custom-asynchronous-operations" id="all_n-api_custom-asynchronous-operations">#</a></span><a aria-hidden="true" class="legacy" id="n_api_custom_asynchronous_operations"></a></h3>
<p>The simple asynchronous work APIs above may not be appropriate for every
scenario. When using any other asynchronous mechanism, the following APIs
are necessary to ensure an asynchronous operation is properly tracked by
the runtime.</p>
<h4><code>napi_async_init</code><span><a class="mark" href="#all_n-api_napi_async_init" id="all_n-api_napi_async_init">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_async_init"></a></h4>
<div class="api_metadata">
<span>Added in: v8.6.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_async_init</span><span class="hljs-params">(napi_env env,
napi_value async_resource,
napi_value async_resource_name,
napi_async_context* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] async_resource</code>: Object associated with the async work
that will be passed to possible <code>async_hooks</code> <a href="#all_async_hooks_initasyncid-type-triggerasyncid-resource"><code>init</code> hooks</a> and can be
accessed by <a href="#all_async_hooks_async_hooksexecutionasyncresource"><code>async_hooks.executionAsyncResource()</code></a>.</li>
<li><code>[in] async_resource_name</code>: Identifier for the kind of resource that is being
provided for diagnostic information exposed by the <code>async_hooks</code> API.</li>
<li><code>[out] result</code>: The initialized async context.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>The <code>async_resource</code> object needs to be kept alive until
<a href="#all_n-api_napi_async_destroy"><code>napi_async_destroy</code></a> to keep <code>async_hooks</code> related API acts correctly. In
order to retain ABI compatibility with previous versions, <code>napi_async_context</code>s
are not maintaining the strong reference to the <code>async_resource</code> objects to
avoid introducing causing memory leaks. However, if the <code>async_resource</code> is
garbage collected by JavaScript engine before the <code>napi_async_context</code> was
destroyed by <code>napi_async_destroy</code>, calling <code>napi_async_context</code> related APIs
like <a href="#all_n-api_napi_open_callback_scope"><code>napi_open_callback_scope</code></a> and <a href="#all_n-api_napi_make_callback"><code>napi_make_callback</code></a> can cause
problems like loss of async context when using the <code>AsyncLocalStorage</code> API.</p>
<p>In order to retain ABI compatibility with previous versions, passing <code>NULL</code>
for <code>async_resource</code> does not result in an error. However, this is not
recommended as this will result in undesirable behavior with <code>async_hooks</code>
<a href="#all_async_hooks_initasyncid-type-triggerasyncid-resource"><code>init</code> hooks</a> and <code>async_hooks.executionAsyncResource()</code> as the resource is
now required by the underlying <code>async_hooks</code> implementation in order to provide
the linkage between async callbacks.</p>
<h4><code>napi_async_destroy</code><span><a class="mark" href="#all_n-api_napi_async_destroy" id="all_n-api_napi_async_destroy">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_async_destroy"></a></h4>
<div class="api_metadata">
<span>Added in: v8.6.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_async_destroy</span><span class="hljs-params">(napi_env env,
napi_async_context async_context)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] async_context</code>: The async context to be destroyed.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h4><code>napi_make_callback</code><span><a class="mark" href="#all_n-api_napi_make_callback" id="all_n-api_napi_make_callback">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_make_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>v8.6.0</td>
<td><p>Added <code>async_context</code> parameter.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p><span>Added in: v8.0.0</span></p></td></tr>
</tbody></table>
</details>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_make_callback</span><span class="hljs-params">(napi_env env,
napi_async_context async_context,
napi_value recv,
napi_value func,
<span class="hljs-type">size_t</span> argc,
<span class="hljs-type">const</span> napi_value* argv,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] async_context</code>: Context for the async operation that is
invoking the callback. This should normally be a value previously
obtained from <a href="#all_n-api_napi_async_init"><code>napi_async_init</code></a>.
In order to retain ABI compatibility with previous versions, passing <code>NULL</code>
for <code>async_context</code> does not result in an error. However, this results
in incorrect operation of async hooks. Potential issues include loss of
async context when using the <code>AsyncLocalStorage</code> API.</li>
<li><code>[in] recv</code>: The <code>this</code> value passed to the called function.</li>
<li><code>[in] func</code>: <code>napi_value</code> representing the JavaScript function to be invoked.</li>
<li><code>[in] argc</code>: The count of elements in the <code>argv</code> array.</li>
<li><code>[in] argv</code>: Array of JavaScript values as <code>napi_value</code> representing the
arguments to the function. If <code>argc</code> is zero this parameter may be
omitted by passing in <code>NULL</code>.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript object returned.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method allows a JavaScript function object to be called from a native
add-on. This API is similar to <code>napi_call_function</code>. However, it is used to call
<em>from</em> native code back <em>into</em> JavaScript <em>after</em> returning from an async
operation (when there is no other script on the stack). It is a fairly simple
wrapper around <code>node::MakeCallback</code>.</p>
<p>Note it is <em>not</em> necessary to use <code>napi_make_callback</code> from within a
<code>napi_async_complete_callback</code>; in that situation the callback's async
context has already been set up, so a direct call to <code>napi_call_function</code>
is sufficient and appropriate. Use of the <code>napi_make_callback</code> function
may be required when implementing custom async behavior that does not use
<code>napi_create_async_work</code>.</p>
<p>Any <code>process.nextTick</code>s or Promises scheduled on the microtask queue by
JavaScript during the callback are ran before returning back to C/C++.</p>
<h4><code>napi_open_callback_scope</code><span><a class="mark" href="#all_n-api_napi_open_callback_scope" id="all_n-api_napi_open_callback_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_open_callback_scope"></a></h4>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
<span>N-API version: 3</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_open_callback_scope</span><span class="hljs-params">(napi_env env,
napi_value resource_object,
napi_async_context context,
napi_callback_scope* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] resource_object</code>: An object associated with the async work
that will be passed to possible <code>async_hooks</code> <a href="#all_async_hooks_initasyncid-type-triggerasyncid-resource"><code>init</code> hooks</a>. This
parameter has been deprecated and is ignored at runtime. Use the
<code>async_resource</code> parameter in <a href="#all_n-api_napi_async_init"><code>napi_async_init</code></a> instead.</li>
<li><code>[in] context</code>: Context for the async operation that is invoking the callback.
This should be a value previously obtained from <a href="#all_n-api_napi_async_init"><code>napi_async_init</code></a>.</li>
<li><code>[out] result</code>: The newly created scope.</li>
</ul>
<p>There are cases (for example, resolving promises) where it is
necessary to have the equivalent of the scope associated with a callback
in place when making certain Node-API calls. If there is no other script on
the stack the <a href="#all_n-api_napi_open_callback_scope"><code>napi_open_callback_scope</code></a> and
<a href="#all_n-api_napi_close_callback_scope"><code>napi_close_callback_scope</code></a> functions can be used to open/close
the required scope.</p>
<h4><code>napi_close_callback_scope</code><span><a class="mark" href="#all_n-api_napi_close_callback_scope" id="all_n-api_napi_close_callback_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_close_callback_scope"></a></h4>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
<span>N-API version: 3</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_close_callback_scope</span><span class="hljs-params">(napi_env env,
napi_callback_scope scope)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] scope</code>: The scope to be closed.</li>
</ul>
<p>This API can be called even if there is a pending JavaScript exception.</p>
</section><section><h3>Version management<span><a class="mark" href="#all_n-api_version-management" id="all_n-api_version-management">#</a></span><a aria-hidden="true" class="legacy" id="n_api_version_management"></a></h3>
<h4><code>napi_get_node_version</code><span><a class="mark" href="#all_n-api_napi_get_node_version" id="all_n-api_napi_get_node_version">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_node_version"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
<span class="hljs-type">uint32_t</span> major;
<span class="hljs-type">uint32_t</span> minor;
<span class="hljs-type">uint32_t</span> patch;
<span class="hljs-type">const</span> <span class="hljs-type">char</span>* release;
} napi_node_version;
napi_status <span class="hljs-title function_">napi_get_node_version</span><span class="hljs-params">(node_api_basic_env env,
<span class="hljs-type">const</span> napi_node_version** version)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] version</code>: A pointer to version information for Node.js itself.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This function fills the <code>version</code> struct with the major, minor, and patch
version of Node.js that is currently running, and the <code>release</code> field with the
value of <a href="#all_process_processrelease"><code>process.release.name</code></a>.</p>
<p>The returned buffer is statically allocated and does not need to be freed.</p>
<h4><code>napi_get_version</code><span><a class="mark" href="#all_n-api_napi_get_version" id="all_n-api_napi_get_version">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_version"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_version</span><span class="hljs-params">(node_api_basic_env env,
<span class="hljs-type">uint32_t</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: The highest version of Node-API supported.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the highest Node-API version supported by the
Node.js runtime. Node-API is planned to be additive such that
newer releases of Node.js may support additional API functions.
In order to allow an addon to use a newer function when running with
versions of Node.js that support it, while providing
fallback behavior when running with Node.js versions that don't
support it:</p>
<ul>
<li>Call <code>napi_get_version()</code> to determine if the API is available.</li>
<li>If available, dynamically load a pointer to the function using <code>uv_dlsym()</code>.</li>
<li>Use the dynamically loaded pointer to invoke the function.</li>
<li>If the function is not available, provide an alternate implementation
that does not use the function.</li>
</ul>
</section><section><h3>Memory management<span><a class="mark" href="#all_n-api_memory-management" id="all_n-api_memory-management">#</a></span><a aria-hidden="true" class="legacy" id="n_api_memory_management"></a></h3>
<h4><code>napi_adjust_external_memory</code><span><a class="mark" href="#all_n-api_napi_adjust_external_memory" id="all_n-api_napi_adjust_external_memory">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_adjust_external_memory"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_adjust_external_memory</span><span class="hljs-params">(node_api_basic_env env,
<span class="hljs-type">int64_t</span> change_in_bytes,
<span class="hljs-type">int64_t</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] change_in_bytes</code>: The change in externally allocated memory that is kept
alive by JavaScript objects.</li>
<li><code>[out] result</code>: The adjusted value</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This function gives V8 an indication of the amount of externally allocated
memory that is kept alive by JavaScript objects (i.e. a JavaScript object
that points to its own memory allocated by a native addon). Registering
externally allocated memory will trigger global garbage collections more
often than it would otherwise.</p>
</section><section><h3>Promises<span><a class="mark" href="#all_n-api_promises" id="all_n-api_promises">#</a></span><a aria-hidden="true" class="legacy" id="n_api_promises"></a></h3>
<p>Node-API provides facilities for creating <code>Promise</code> objects as described in
<a href="https://tc39.github.io/ecma262/#sec-promise-objects">Section 25.4</a> of the ECMA specification. It implements promises as a pair of
objects. When a promise is created by <code>napi_create_promise()</code>, a "deferred"
object is created and returned alongside the <code>Promise</code>. The deferred object is
bound to the created <code>Promise</code> and is the only means to resolve or reject the
<code>Promise</code> using <code>napi_resolve_deferred()</code> or <code>napi_reject_deferred()</code>. The
deferred object that is created by <code>napi_create_promise()</code> is freed by
<code>napi_resolve_deferred()</code> or <code>napi_reject_deferred()</code>. The <code>Promise</code> object may
be returned to JavaScript where it can be used in the usual fashion.</p>
<p>For example, to create a promise and pass it to an asynchronous worker:</p>
<pre><code class="language-c">napi_deferred deferred;
napi_value promise;
napi_status status;
<span class="hljs-comment">// Create the promise.</span>
status = napi_create_promise(env, &deferred, &promise);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-comment">// Pass the deferred to a function that performs an asynchronous action.</span>
do_something_asynchronous(deferred);
<span class="hljs-comment">// Return the promise to JS</span>
<span class="hljs-keyword">return</span> promise;</code> <button class="copy-button">copy</button></pre>
<p>The above function <code>do_something_asynchronous()</code> would perform its asynchronous
action and then it would resolve or reject the deferred, thereby concluding the
promise and freeing the deferred:</p>
<pre><code class="language-c">napi_deferred deferred;
napi_value undefined;
napi_status status;
<span class="hljs-comment">// Create a value with which to conclude the deferred.</span>
status = napi_get_undefined(env, &undefined);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-comment">// Resolve or reject the promise associated with the deferred depending on</span>
<span class="hljs-comment">// whether the asynchronous action succeeded.</span>
<span class="hljs-keyword">if</span> (asynchronous_action_succeeded) {
status = napi_resolve_deferred(env, deferred, undefined);
} <span class="hljs-keyword">else</span> {
status = napi_reject_deferred(env, deferred, undefined);
}
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
<span class="hljs-comment">// At this point the deferred has been freed, so we should assign NULL to it.</span>
deferred = <span class="hljs-literal">NULL</span>;</code> <button class="copy-button">copy</button></pre>
<h4><code>napi_create_promise</code><span><a class="mark" href="#all_n-api_napi_create_promise" id="all_n-api_napi_create_promise">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_promise"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_promise</span><span class="hljs-params">(napi_env env,
napi_deferred* deferred,
napi_value* promise)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] deferred</code>: A newly created deferred object which can later be passed to
<code>napi_resolve_deferred()</code> or <code>napi_reject_deferred()</code> to resolve resp. reject
the associated promise.</li>
<li><code>[out] promise</code>: The JavaScript promise associated with the deferred object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a deferred object and a JavaScript promise.</p>
<h4><code>napi_resolve_deferred</code><span><a class="mark" href="#all_n-api_napi_resolve_deferred" id="all_n-api_napi_resolve_deferred">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_resolve_deferred"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_resolve_deferred</span><span class="hljs-params">(napi_env env,
napi_deferred deferred,
napi_value resolution)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] deferred</code>: The deferred object whose associated promise to resolve.</li>
<li><code>[in] resolution</code>: The value with which to resolve the promise.</li>
</ul>
<p>This API resolves a JavaScript promise by way of the deferred object
with which it is associated. Thus, it can only be used to resolve JavaScript
promises for which the corresponding deferred object is available. This
effectively means that the promise must have been created using
<code>napi_create_promise()</code> and the deferred object returned from that call must
have been retained in order to be passed to this API.</p>
<p>The deferred object is freed upon successful completion.</p>
<h4><code>napi_reject_deferred</code><span><a class="mark" href="#all_n-api_napi_reject_deferred" id="all_n-api_napi_reject_deferred">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_reject_deferred"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_reject_deferred</span><span class="hljs-params">(napi_env env,
napi_deferred deferred,
napi_value rejection)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] deferred</code>: The deferred object whose associated promise to resolve.</li>
<li><code>[in] rejection</code>: The value with which to reject the promise.</li>
</ul>
<p>This API rejects a JavaScript promise by way of the deferred object
with which it is associated. Thus, it can only be used to reject JavaScript
promises for which the corresponding deferred object is available. This
effectively means that the promise must have been created using
<code>napi_create_promise()</code> and the deferred object returned from that call must
have been retained in order to be passed to this API.</p>
<p>The deferred object is freed upon successful completion.</p>
<h4><code>napi_is_promise</code><span><a class="mark" href="#all_n-api_napi_is_promise" id="all_n-api_napi_is_promise">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_promise"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_promise</span><span class="hljs-params">(napi_env env,
napi_value value,
<span class="hljs-type">bool</span>* is_promise)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The value to examine</li>
<li><code>[out] is_promise</code>: Flag indicating whether <code>promise</code> is a native promise
object (that is, a promise object created by the underlying engine).</li>
</ul>
</section><section><h3>Script execution<span><a class="mark" href="#all_n-api_script-execution" id="all_n-api_script-execution">#</a></span><a aria-hidden="true" class="legacy" id="n_api_script_execution"></a></h3>
<p>Node-API provides an API for executing a string containing JavaScript using the
underlying JavaScript engine.</p>
<h4><code>napi_run_script</code><span><a class="mark" href="#all_n-api_napi_run_script" id="all_n-api_napi_run_script">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_run_script"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_run_script</span><span class="hljs-params">(napi_env env,
napi_value script,
napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] script</code>: A JavaScript string containing the script to execute.</li>
<li><code>[out] result</code>: The value resulting from having executed the script.</li>
</ul>
<p>This function executes a string of JavaScript code and returns its result with
the following caveats:</p>
<ul>
<li>Unlike <code>eval</code>, this function does not allow the script to access the current
lexical scope, and therefore also does not allow to access the
<a href="#all_modules_the-module-scope">module scope</a>, meaning that pseudo-globals such as <code>require</code> will not be
available.</li>
<li>The script can access the <a href="globals.html">global scope</a>. Function and <code>var</code> declarations
in the script will be added to the <a href="#all_globals_global"><code>global</code></a> object. Variable declarations
made using <code>let</code> and <code>const</code> will be visible globally, but will not be added
to the <a href="#all_globals_global"><code>global</code></a> object.</li>
<li>The value of <code>this</code> is <a href="#all_globals_global"><code>global</code></a> within the script.</li>
</ul>
</section><section><h3>libuv event loop<span><a class="mark" href="#all_n-api_libuv-event-loop" id="all_n-api_libuv-event-loop">#</a></span><a aria-hidden="true" class="legacy" id="n_api_libuv_event_loop"></a></h3>
<p>Node-API provides a function for getting the current event loop associated with
a specific <code>napi_env</code>.</p>
<h4><code>napi_get_uv_event_loop</code><span><a class="mark" href="#all_n-api_napi_get_uv_event_loop" id="all_n-api_napi_get_uv_event_loop">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_uv_event_loop"></a></h4>
<div class="api_metadata">
<span>Added in: v9.3.0, v8.10.0</span>
<span>N-API version: 2</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_get_uv_event_loop</span><span class="hljs-params">(node_api_basic_env env,
<span class="hljs-keyword">struct</span> uv_loop_s** loop)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] loop</code>: The current libuv loop instance.</li>
</ul>
<p>Note: While libuv has been relatively stable over time, it does
not provide an ABI stability guarantee. Use of this function should be avoided.
Its use may result in an addon that does not work across Node.js versions.
<a href="https://nodejs.org/docs/latest/api/n-api.html#asynchronous-thread-safe-function-calls">asynchronous-thread-safe-function-calls</a>
are an alternative for many use cases.</p>
</section><section><h3>Asynchronous thread-safe function calls<span><a class="mark" href="#all_n-api_asynchronous-thread-safe-function-calls" id="all_n-api_asynchronous-thread-safe-function-calls">#</a></span><a aria-hidden="true" class="legacy" id="n_api_asynchronous_thread_safe_function_calls"></a></h3>
<p>JavaScript functions can normally only be called from a native addon's main
thread. If an addon creates additional threads, then Node-API functions that
require a <code>napi_env</code>, <code>napi_value</code>, or <code>napi_ref</code> must not be called from those
threads.</p>
<p>When an addon has additional threads and JavaScript functions need to be invoked
based on the processing completed by those threads, those threads must
communicate with the addon's main thread so that the main thread can invoke the
JavaScript function on their behalf. The thread-safe function APIs provide an
easy way to do this.</p>
<p>These APIs provide the type <code>napi_threadsafe_function</code> as well as APIs to
create, destroy, and call objects of this type.
<code>napi_create_threadsafe_function()</code> creates a persistent reference to a
<code>napi_value</code> that holds a JavaScript function which can be called from multiple
threads. The calls happen asynchronously. This means that values with which the
JavaScript callback is to be called will be placed in a queue, and, for each
value in the queue, a call will eventually be made to the JavaScript function.</p>
<p>Upon creation of a <code>napi_threadsafe_function</code> a <code>napi_finalize</code> callback can be
provided. This callback will be invoked on the main thread when the thread-safe
function is about to be destroyed. It receives the context and the finalize data
given during construction, and provides an opportunity for cleaning up after the
threads e.g. by calling <code>uv_thread_join()</code>. <strong>Aside from the main loop thread,
no threads should be using the thread-safe function after the finalize callback
completes.</strong></p>
<p>The <code>context</code> given during the call to <code>napi_create_threadsafe_function()</code> can
be retrieved from any thread with a call to
<code>napi_get_threadsafe_function_context()</code>.</p>
<h4>Calling a thread-safe function<span><a class="mark" href="#all_n-api_calling-a-thread-safe-function" id="all_n-api_calling-a-thread-safe-function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_calling_a_thread_safe_function"></a></h4>
<p><code>napi_call_threadsafe_function()</code> can be used for initiating a call into
JavaScript. <code>napi_call_threadsafe_function()</code> accepts a parameter which controls
whether the API behaves blockingly. If set to <code>napi_tsfn_nonblocking</code>, the API
behaves non-blockingly, returning <code>napi_queue_full</code> if the queue was full,
preventing data from being successfully added to the queue. If set to
<code>napi_tsfn_blocking</code>, the API blocks until space becomes available in the queue.
<code>napi_call_threadsafe_function()</code> never blocks if the thread-safe function was
created with a maximum queue size of 0.</p>
<p><code>napi_call_threadsafe_function()</code> should not be called with <code>napi_tsfn_blocking</code>
from a JavaScript thread, because, if the queue is full, it may cause the
JavaScript thread to deadlock.</p>
<p>The actual call into JavaScript is controlled by the callback given via the
<code>call_js_cb</code> parameter. <code>call_js_cb</code> is invoked on the main thread once for each
value that was placed into the queue by a successful call to
<code>napi_call_threadsafe_function()</code>. If such a callback is not given, a default
callback will be used, and the resulting JavaScript call will have no arguments.
The <code>call_js_cb</code> callback receives the JavaScript function to call as a
<code>napi_value</code> in its parameters, as well as the <code>void*</code> context pointer used when
creating the <code>napi_threadsafe_function</code>, and the next data pointer that was
created by one of the secondary threads. The callback can then use an API such
as <code>napi_call_function()</code> to call into JavaScript.</p>
<p>The callback may also be invoked with <code>env</code> and <code>call_js_cb</code> both set to <code>NULL</code>
to indicate that calls into JavaScript are no longer possible, while items
remain in the queue that may need to be freed. This normally occurs when the
Node.js process exits while there is a thread-safe function still active.</p>
<p>It is not necessary to call into JavaScript via <code>napi_make_callback()</code> because
Node-API runs <code>call_js_cb</code> in a context appropriate for callbacks.</p>
<p>Zero or more queued items may be invoked in each tick of the event loop.
Applications should not depend on a specific behavior other than progress in
invoking callbacks will be made and events will be invoked
as time moves forward.</p>
<h4>Reference counting of thread-safe functions<span><a class="mark" href="#all_n-api_reference-counting-of-thread-safe-functions" id="all_n-api_reference-counting-of-thread-safe-functions">#</a></span><a aria-hidden="true" class="legacy" id="n_api_reference_counting_of_thread_safe_functions"></a></h4>
<p>Threads can be added to and removed from a <code>napi_threadsafe_function</code> object
during its existence. Thus, in addition to specifying an initial number of
threads upon creation, <code>napi_acquire_threadsafe_function</code> can be called to
indicate that a new thread will start making use of the thread-safe function.
Similarly, <code>napi_release_threadsafe_function</code> can be called to indicate that an
existing thread will stop making use of the thread-safe function.</p>
<p><code>napi_threadsafe_function</code> objects are destroyed when every thread which uses
the object has called <code>napi_release_threadsafe_function()</code> or has received a
return status of <code>napi_closing</code> in response to a call to
<code>napi_call_threadsafe_function</code>. The queue is emptied before the
<code>napi_threadsafe_function</code> is destroyed. <code>napi_release_threadsafe_function()</code>
should be the last API call made in conjunction with a given
<code>napi_threadsafe_function</code>, because after the call completes, there is no
guarantee that the <code>napi_threadsafe_function</code> is still allocated. For the same
reason, do not use a thread-safe function
after receiving a return value of <code>napi_closing</code> in response to a call to
<code>napi_call_threadsafe_function</code>. Data associated with the
<code>napi_threadsafe_function</code> can be freed in its <code>napi_finalize</code> callback which
was passed to <code>napi_create_threadsafe_function()</code>. The parameter
<code>initial_thread_count</code> of <code>napi_create_threadsafe_function</code> marks the initial
number of acquisitions of the thread-safe functions, instead of calling
<code>napi_acquire_threadsafe_function</code> multiple times at creation.</p>
<p>Once the number of threads making use of a <code>napi_threadsafe_function</code> reaches
zero, no further threads can start making use of it by calling
<code>napi_acquire_threadsafe_function()</code>. In fact, all subsequent API calls
associated with it, except <code>napi_release_threadsafe_function()</code>, will return an
error value of <code>napi_closing</code>.</p>
<p>The thread-safe function can be "aborted" by giving a value of <code>napi_tsfn_abort</code>
to <code>napi_release_threadsafe_function()</code>. This will cause all subsequent APIs
associated with the thread-safe function except
<code>napi_release_threadsafe_function()</code> to return <code>napi_closing</code> even before its
reference count reaches zero. In particular, <code>napi_call_threadsafe_function()</code>
will return <code>napi_closing</code>, thus informing the threads that it is no longer
possible to make asynchronous calls to the thread-safe function. This can be
used as a criterion for terminating the thread. <strong>Upon receiving a return value
of <code>napi_closing</code> from <code>napi_call_threadsafe_function()</code> a thread must not use
the thread-safe function anymore because it is no longer guaranteed to
be allocated.</strong></p>
<h4>Deciding whether to keep the process running<span><a class="mark" href="#all_n-api_deciding-whether-to-keep-the-process-running" id="all_n-api_deciding-whether-to-keep-the-process-running">#</a></span><a aria-hidden="true" class="legacy" id="n_api_deciding_whether_to_keep_the_process_running"></a></h4>
<p>Similarly to libuv handles, thread-safe functions can be "referenced" and
"unreferenced". A "referenced" thread-safe function will cause the event loop on
the thread on which it is created to remain alive until the thread-safe function
is destroyed. In contrast, an "unreferenced" thread-safe function will not
prevent the event loop from exiting. The APIs <code>napi_ref_threadsafe_function</code> and
<code>napi_unref_threadsafe_function</code> exist for this purpose.</p>
<p>Neither does <code>napi_unref_threadsafe_function</code> mark the thread-safe functions as
able to be destroyed nor does <code>napi_ref_threadsafe_function</code> prevent it from
being destroyed.</p>
<h4><code>napi_create_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_create_threadsafe_function" id="all_n-api_napi_create_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_threadsafe_function"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.6.0, v10.17.0</td>
<td><p>Made <code>func</code> parameter optional with custom <code>call_js_cb</code>.</p></td></tr>
<tr><td>v10.6.0</td>
<td><p><span>Added in: v10.6.0</span></p></td></tr>
</tbody></table>
</details>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
<span class="hljs-title function_">napi_create_threadsafe_function</span><span class="hljs-params">(napi_env env,
napi_value func,
napi_value async_resource,
napi_value async_resource_name,
<span class="hljs-type">size_t</span> max_queue_size,
<span class="hljs-type">size_t</span> initial_thread_count,
<span class="hljs-type">void</span>* thread_finalize_data,
napi_finalize thread_finalize_cb,
<span class="hljs-type">void</span>* context,
napi_threadsafe_function_call_js call_js_cb,
napi_threadsafe_function* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] func</code>: An optional JavaScript function to call from another thread. It
must be provided if <code>NULL</code> is passed to <code>call_js_cb</code>.</li>
<li><code>[in] async_resource</code>: An optional object associated with the async work that
will be passed to possible <code>async_hooks</code> <a href="#all_async_hooks_initasyncid-type-triggerasyncid-resource"><code>init</code> hooks</a>.</li>
<li><code>[in] async_resource_name</code>: A JavaScript string to provide an identifier for
the kind of resource that is being provided for diagnostic information exposed
by the <code>async_hooks</code> API.</li>
<li><code>[in] max_queue_size</code>: Maximum size of the queue. <code>0</code> for no limit.</li>
<li><code>[in] initial_thread_count</code>: The initial number of acquisitions, i.e. the
initial number of threads, including the main thread, which will be making use
of this function.</li>
<li><code>[in] thread_finalize_data</code>: Optional data to be passed to <code>thread_finalize_cb</code>.</li>
<li><code>[in] thread_finalize_cb</code>: Optional function to call when the
<code>napi_threadsafe_function</code> is being destroyed.</li>
<li><code>[in] context</code>: Optional data to attach to the resulting
<code>napi_threadsafe_function</code>.</li>
<li><code>[in] call_js_cb</code>: Optional callback which calls the JavaScript function in
response to a call on a different thread. This callback will be called on the
main thread. If not given, the JavaScript function will be called with no
parameters and with <code>undefined</code> as its <code>this</code> value.
<a href="#all_n-api_napi_threadsafe_function_call_js"><code>napi_threadsafe_function_call_js</code></a> provides more details.</li>
<li><code>[out] result</code>: The asynchronous thread-safe JavaScript function.</li>
</ul>
<p><strong>Change History:</strong></p>
<ul>
<li>
<p>Experimental (<code>NAPI_EXPERIMENTAL</code> is defined):</p>
<p>Uncaught exceptions thrown in <code>call_js_cb</code> are handled with the
<a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a> event, instead of being ignored.</p>
</li>
</ul>
<h4><code>napi_get_threadsafe_function_context</code><span><a class="mark" href="#all_n-api_napi_get_threadsafe_function_context" id="all_n-api_napi_get_threadsafe_function_context">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_threadsafe_function_context"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
<span class="hljs-title function_">napi_get_threadsafe_function_context</span><span class="hljs-params">(napi_threadsafe_function func,
<span class="hljs-type">void</span>** result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] func</code>: The thread-safe function for which to retrieve the context.</li>
<li><code>[out] result</code>: The location where to store the context.</li>
</ul>
<p>This API may be called from any thread which makes use of <code>func</code>.</p>
<h4><code>napi_call_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_call_threadsafe_function" id="all_n-api_napi_call_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_call_threadsafe_function"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0</td>
<td><p>Support for <code>napi_would_deadlock</code> has been reverted.</p></td></tr>
<tr><td>v14.1.0</td>
<td><p>Return <code>napi_would_deadlock</code> when called with <code>napi_tsfn_blocking</code> from the main thread or a worker thread and the queue is full.</p></td></tr>
<tr><td>v10.6.0</td>
<td><p><span>Added in: v10.6.0</span></p></td></tr>
</tbody></table>
</details>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
<span class="hljs-title function_">napi_call_threadsafe_function</span><span class="hljs-params">(napi_threadsafe_function func,
<span class="hljs-type">void</span>* data,
napi_threadsafe_function_call_mode is_blocking)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] func</code>: The asynchronous thread-safe JavaScript function to invoke.</li>
<li><code>[in] data</code>: Data to send into JavaScript via the callback <code>call_js_cb</code>
provided during the creation of the thread-safe JavaScript function.</li>
<li><code>[in] is_blocking</code>: Flag whose value can be either <code>napi_tsfn_blocking</code> to
indicate that the call should block if the queue is full or
<code>napi_tsfn_nonblocking</code> to indicate that the call should return immediately
with a status of <code>napi_queue_full</code> whenever the queue is full.</li>
</ul>
<p>This API should not be called with <code>napi_tsfn_blocking</code> from a JavaScript
thread, because, if the queue is full, it may cause the JavaScript thread to
deadlock.</p>
<p>This API will return <code>napi_closing</code> if <code>napi_release_threadsafe_function()</code> was
called with <code>abort</code> set to <code>napi_tsfn_abort</code> from any thread. The value is only
added to the queue if the API returns <code>napi_ok</code>.</p>
<p>This API may be called from any thread which makes use of <code>func</code>.</p>
<h4><code>napi_acquire_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_acquire_threadsafe_function" id="all_n-api_napi_acquire_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_acquire_threadsafe_function"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
<span class="hljs-title function_">napi_acquire_threadsafe_function</span><span class="hljs-params">(napi_threadsafe_function func)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] func</code>: The asynchronous thread-safe JavaScript function to start making
use of.</li>
</ul>
<p>A thread should call this API before passing <code>func</code> to any other thread-safe
function APIs to indicate that it will be making use of <code>func</code>. This prevents
<code>func</code> from being destroyed when all other threads have stopped making use of
it.</p>
<p>This API may be called from any thread which will start making use of <code>func</code>.</p>
<h4><code>napi_release_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_release_threadsafe_function" id="all_n-api_napi_release_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_release_threadsafe_function"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
<span class="hljs-title function_">napi_release_threadsafe_function</span><span class="hljs-params">(napi_threadsafe_function func,
napi_threadsafe_function_release_mode mode)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] func</code>: The asynchronous thread-safe JavaScript function whose reference
count to decrement.</li>
<li><code>[in] mode</code>: Flag whose value can be either <code>napi_tsfn_release</code> to indicate
that the current thread will make no further calls to the thread-safe
function, or <code>napi_tsfn_abort</code> to indicate that in addition to the current
thread, no other thread should make any further calls to the thread-safe
function. If set to <code>napi_tsfn_abort</code>, further calls to
<code>napi_call_threadsafe_function()</code> will return <code>napi_closing</code>, and no further
values will be placed in the queue.</li>
</ul>
<p>A thread should call this API when it stops making use of <code>func</code>. Passing <code>func</code>
to any thread-safe APIs after having called this API has undefined results, as
<code>func</code> may have been destroyed.</p>
<p>This API may be called from any thread which will stop making use of <code>func</code>.</p>
<h4><code>napi_ref_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_ref_threadsafe_function" id="all_n-api_napi_ref_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_ref_threadsafe_function"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
<span class="hljs-title function_">napi_ref_threadsafe_function</span><span class="hljs-params">(node_api_basic_env env, napi_threadsafe_function func)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] func</code>: The thread-safe function to reference.</li>
</ul>
<p>This API is used to indicate that the event loop running on the main thread
should not exit until <code>func</code> has been destroyed. Similar to <a href="https://docs.libuv.org/en/v1.x/handle.html#c.uv_ref"><code>uv_ref</code></a> it is
also idempotent.</p>
<p>Neither does <code>napi_unref_threadsafe_function</code> mark the thread-safe functions as
able to be destroyed nor does <code>napi_ref_threadsafe_function</code> prevent it from
being destroyed. <code>napi_acquire_threadsafe_function</code> and
<code>napi_release_threadsafe_function</code> are available for that purpose.</p>
<p>This API may only be called from the main thread.</p>
<h4><code>napi_unref_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_unref_threadsafe_function" id="all_n-api_napi_unref_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_unref_threadsafe_function"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
<span class="hljs-title function_">napi_unref_threadsafe_function</span><span class="hljs-params">(node_api_basic_env env, napi_threadsafe_function func)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] func</code>: The thread-safe function to unreference.</li>
</ul>
<p>This API is used to indicate that the event loop running on the main thread
may exit before <code>func</code> is destroyed. Similar to <a href="https://docs.libuv.org/en/v1.x/handle.html#c.uv_unref"><code>uv_unref</code></a> it is also
idempotent.</p>
<p>This API may only be called from the main thread.</p>
</section><section><h3>Miscellaneous utilities<span><a class="mark" href="#all_n-api_miscellaneous-utilities" id="all_n-api_miscellaneous-utilities">#</a></span><a aria-hidden="true" class="legacy" id="n_api_miscellaneous_utilities"></a></h3>
<h4><code>node_api_get_module_file_name</code><span><a class="mark" href="#all_n-api_node_api_get_module_file_name" id="all_n-api_node_api_get_module_file_name">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_get_module_file_name"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0, v14.18.0, v12.22.0</span>
<span>N-API version: 9</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
<span class="hljs-title function_">node_api_get_module_file_name</span><span class="hljs-params">(node_api_basic_env env, <span class="hljs-type">const</span> <span class="hljs-type">char</span>** result)</span>;
</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: A URL containing the absolute path of the
location from which the add-on was loaded. For a file on the local
file system it will start with <code>file://</code>. The string is null-terminated and
owned by <code>env</code> and must thus not be modified or freed.</li>
</ul>
<p><code>result</code> may be an empty string if the add-on loading process fails to establish
the add-on's file name during loading.</p></section>
</section>
<section><h2>C++ embedder API<span><a class="mark" href="#all_embedding_c-embedder-api" id="all_embedding_c-embedder-api">#</a></span><a aria-hidden="true" class="legacy" id="embedding_c_embedder_api"></a></h2>
<p>Node.js provides a number of C++ APIs that can be used to execute JavaScript
in a Node.js environment from other C++ software.</p>
<p>The documentation for these APIs can be found in <a href="https://github.com/nodejs/node/blob/HEAD/src/node.h">src/node.h</a> in the Node.js
source tree. In addition to the APIs exposed by Node.js, some required concepts
are provided by the V8 embedder API.</p>
<p>Because using Node.js as an embedded library is different from writing code
that is executed by Node.js, breaking changes do not follow typical Node.js
<a href="deprecations.html">deprecation policy</a> and may occur on each semver-major release without prior
warning.</p>
<section><h3>Example embedding application<span><a class="mark" href="#all_embedding_example-embedding-application" id="all_embedding_example-embedding-application">#</a></span><a aria-hidden="true" class="legacy" id="embedding_example_embedding_application"></a></h3>
<p>The following sections will provide an overview over how to use these APIs
to create an application from scratch that will perform the equivalent of
<code>node -e <code></code>, i.e. that will take a piece of JavaScript and run it in
a Node.js-specific environment.</p>
<p>The full code can be found <a href="https://github.com/nodejs/node/blob/HEAD/test/embedding/embedtest.cc">in the Node.js source tree</a>.</p>
<h4>Setting up a per-process state<span><a class="mark" href="#all_embedding_setting-up-a-per-process-state" id="all_embedding_setting-up-a-per-process-state">#</a></span><a aria-hidden="true" class="legacy" id="embedding_setting_up_a_per_process_state"></a></h4>
<p>Node.js requires some per-process state management in order to run:</p>
<ul>
<li>Arguments parsing for Node.js <a href="cli.html">CLI options</a>,</li>
<li>V8 per-process requirements, such as a <code>v8::Platform</code> instance.</li>
</ul>
<p>The following example shows how these can be set up. Some class names are from
the <code>node</code> and <code>v8</code> C++ namespaces, respectively.</p>
<pre><code class="language-cpp"><span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-type">int</span> argc, <span class="hljs-type">char</span>** argv)</span> </span>{
argv = <span class="hljs-built_in">uv_setup_args</span>(argc, argv);
<span class="hljs-function">std::vector<std::string> <span class="hljs-title">args</span><span class="hljs-params">(argv, argv + argc)</span></span>;
<span class="hljs-comment">// Parse Node.js CLI options, and print any errors that have occurred while</span>
<span class="hljs-comment">// trying to parse them.</span>
std::unique_ptr<node::InitializationResult> result =
node::<span class="hljs-built_in">InitializeOncePerProcess</span>(args, {
node::ProcessInitializationFlags::kNoInitializeV8,
node::ProcessInitializationFlags::kNoInitializeNodeV8Platform
});
<span class="hljs-keyword">for</span> (<span class="hljs-type">const</span> std::string& error : result-><span class="hljs-built_in">errors</span>())
<span class="hljs-built_in">fprintf</span>(stderr, <span class="hljs-string">"%s: %s\n"</span>, args[<span class="hljs-number">0</span>].<span class="hljs-built_in">c_str</span>(), error.<span class="hljs-built_in">c_str</span>());
<span class="hljs-keyword">if</span> (result-><span class="hljs-built_in">early_return</span>() != <span class="hljs-number">0</span>) {
<span class="hljs-keyword">return</span> result-><span class="hljs-built_in">exit_code</span>();
}
<span class="hljs-comment">// Create a v8::Platform instance. `MultiIsolatePlatform::Create()` is a way</span>
<span class="hljs-comment">// to create a v8::Platform instance that Node.js can use when creating</span>
<span class="hljs-comment">// Worker threads. When no `MultiIsolatePlatform` instance is present,</span>
<span class="hljs-comment">// Worker threads are disabled.</span>
std::unique_ptr<MultiIsolatePlatform> platform =
MultiIsolatePlatform::<span class="hljs-built_in">Create</span>(<span class="hljs-number">4</span>);
V8::<span class="hljs-built_in">InitializePlatform</span>(platform.<span class="hljs-built_in">get</span>());
V8::<span class="hljs-built_in">Initialize</span>();
<span class="hljs-comment">// See below for the contents of this function.</span>
<span class="hljs-type">int</span> ret = <span class="hljs-built_in">RunNodeInstance</span>(
platform.<span class="hljs-built_in">get</span>(), result-><span class="hljs-built_in">args</span>(), result-><span class="hljs-built_in">exec_args</span>());
V8::<span class="hljs-built_in">Dispose</span>();
V8::<span class="hljs-built_in">DisposePlatform</span>();
node::<span class="hljs-built_in">TearDownOncePerProcess</span>();
<span class="hljs-keyword">return</span> ret;
}</code> <button class="copy-button">copy</button></pre>
<h4>Setting up a per-instance state<span><a class="mark" href="#all_embedding_setting-up-a-per-instance-state" id="all_embedding_setting-up-a-per-instance-state">#</a></span><a aria-hidden="true" class="legacy" id="embedding_setting_up_a_per_instance_state"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>CommonEnvironmentSetup</code> and <code>SpinEventLoop</code> utilities were added.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Node.js has a concept of a “Node.js instance”, that is commonly being referred
to as <code>node::Environment</code>. Each <code>node::Environment</code> is associated with:</p>
<ul>
<li>Exactly one <code>v8::Isolate</code>, i.e. one JS Engine instance,</li>
<li>Exactly one <code>uv_loop_t</code>, i.e. one event loop,</li>
<li>A number of <code>v8::Context</code>s, but exactly one main <code>v8::Context</code>, and</li>
<li>One <code>node::IsolateData</code> instance that contains information that could be
shared by multiple <code>node::Environment</code>s. The embedder should make sure
that <code>node::IsolateData</code> is shared only among <code>node::Environment</code>s that
use the same <code>v8::Isolate</code>, Node.js does not perform this check.</li>
</ul>
<p>In order to set up a <code>v8::Isolate</code>, an <code>v8::ArrayBuffer::Allocator</code> needs
to be provided. One possible choice is the default Node.js allocator, which
can be created through <code>node::ArrayBufferAllocator::Create()</code>. Using the Node.js
allocator allows minor performance optimizations when addons use the Node.js
C++ <code>Buffer</code> API, and is required in order to track <code>ArrayBuffer</code> memory in
<a href="#all_process_processmemoryusage"><code>process.memoryUsage()</code></a>.</p>
<p>Additionally, each <code>v8::Isolate</code> that is used for a Node.js instance needs to
be registered and unregistered with the <code>MultiIsolatePlatform</code> instance, if one
is being used, in order for the platform to know which event loop to use
for tasks scheduled by the <code>v8::Isolate</code>.</p>
<p>The <code>node::NewIsolate()</code> helper function creates a <code>v8::Isolate</code>,
sets it up with some Node.js-specific hooks (e.g. the Node.js error handler),
and registers it with the platform automatically.</p>
<pre><code class="language-cpp"><span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">RunNodeInstance</span><span class="hljs-params">(MultiIsolatePlatform* platform,
<span class="hljs-type">const</span> std::vector<std::string>& args,
<span class="hljs-type">const</span> std::vector<std::string>& exec_args)</span> </span>{
<span class="hljs-type">int</span> exit_code = <span class="hljs-number">0</span>;
<span class="hljs-comment">// Setup up a libuv event loop, v8::Isolate, and Node.js Environment.</span>
std::vector<std::string> errors;
std::unique_ptr<CommonEnvironmentSetup> setup =
CommonEnvironmentSetup::<span class="hljs-built_in">Create</span>(platform, &errors, args, exec_args);
<span class="hljs-keyword">if</span> (!setup) {
<span class="hljs-keyword">for</span> (<span class="hljs-type">const</span> std::string& err : errors)
<span class="hljs-built_in">fprintf</span>(stderr, <span class="hljs-string">"%s: %s\n"</span>, args[<span class="hljs-number">0</span>].<span class="hljs-built_in">c_str</span>(), err.<span class="hljs-built_in">c_str</span>());
<span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
}
Isolate* isolate = setup-><span class="hljs-built_in">isolate</span>();
Environment* env = setup-><span class="hljs-built_in">env</span>();
{
<span class="hljs-function">Locker <span class="hljs-title">locker</span><span class="hljs-params">(isolate)</span></span>;
<span class="hljs-function">Isolate::Scope <span class="hljs-title">isolate_scope</span><span class="hljs-params">(isolate)</span></span>;
<span class="hljs-function">HandleScope <span class="hljs-title">handle_scope</span><span class="hljs-params">(isolate)</span></span>;
<span class="hljs-comment">// The v8::Context needs to be entered when node::CreateEnvironment() and</span>
<span class="hljs-comment">// node::LoadEnvironment() are being called.</span>
<span class="hljs-function">Context::Scope <span class="hljs-title">context_scope</span><span class="hljs-params">(setup->context())</span></span>;
<span class="hljs-comment">// Set up the Node.js instance for execution, and run code inside of it.</span>
<span class="hljs-comment">// There is also a variant that takes a callback and provides it with</span>
<span class="hljs-comment">// the `require` and `process` objects, so that it can manually compile</span>
<span class="hljs-comment">// and run scripts as needed.</span>
<span class="hljs-comment">// The `require` function inside this script does *not* access the file</span>
<span class="hljs-comment">// system, and can only load built-in Node.js modules.</span>
<span class="hljs-comment">// `module.createRequire()` is being used to create one that is able to</span>
<span class="hljs-comment">// load files from the disk, and uses the standard CommonJS file loader</span>
<span class="hljs-comment">// instead of the internal-only `require` function.</span>
MaybeLocal<Value> loadenv_ret = node::<span class="hljs-built_in">LoadEnvironment</span>(
env,
<span class="hljs-string">"const publicRequire ="</span>
<span class="hljs-string">" require('node:module').createRequire(process.cwd() + '/');"</span>
<span class="hljs-string">"globalThis.require = publicRequire;"</span>
<span class="hljs-string">"require('node:vm').runInThisContext(process.argv[1]);"</span>);
<span class="hljs-keyword">if</span> (loadenv_ret.<span class="hljs-built_in">IsEmpty</span>()) <span class="hljs-comment">// There has been a JS exception.</span>
<span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
exit_code = node::<span class="hljs-built_in">SpinEventLoop</span>(env).<span class="hljs-built_in">FromMaybe</span>(<span class="hljs-number">1</span>);
<span class="hljs-comment">// node::Stop() can be used to explicitly stop the event loop and keep</span>
<span class="hljs-comment">// further JavaScript from running. It can be called from any thread,</span>
<span class="hljs-comment">// and will act like worker.terminate() if called from another thread.</span>
node::<span class="hljs-built_in">Stop</span>(env);
}
<span class="hljs-keyword">return</span> exit_code;
}</code> <button class="copy-button">copy</button></pre></section>
</section>
<section><h2>Child process<span><a class="mark" href="#all_child_process_child-process" id="all_child_process_child-process">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/child_process.js">lib/child_process.js</a></p>
<p>The <code>node:child_process</code> module provides the ability to spawn subprocesses in
a manner that is similar, but not identical, to <a href="http://man7.org/linux/man-pages/man3/popen.3.html"><code>popen(3)</code></a>. This capability
is primarily provided by the <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> function:</p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> ls = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, [<span class="hljs-string">'-lh'</span>, <span class="hljs-string">'/usr'</span>]);
ls.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${data}</span>`</span>);
});
ls.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`stderr: <span class="hljs-subst">${data}</span>`</span>);
});
ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process exited with code <span class="hljs-subst">${code}</span>`</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> ls = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, [<span class="hljs-string">'-lh'</span>, <span class="hljs-string">'/usr'</span>]);
ls.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${data}</span>`</span>);
});
ls.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`stderr: <span class="hljs-subst">${data}</span>`</span>);
});
ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process exited with code <span class="hljs-subst">${code}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<p>By default, pipes for <code>stdin</code>, <code>stdout</code>, and <code>stderr</code> are established between
the parent Node.js process and the spawned subprocess. These pipes have
limited (and platform-specific) capacity. If the subprocess writes to
stdout in excess of that limit without the output being captured, the
subprocess blocks waiting for the pipe buffer to accept more data. This is
identical to the behavior of pipes in the shell. Use the <code>{ stdio: 'ignore' }</code>
option if the output will not be consumed.</p>
<p>The command lookup is performed using the <code>options.env.PATH</code> environment
variable if <code>env</code> is in the <code>options</code> object. Otherwise, <code>process.env.PATH</code> is
used. If <code>options.env</code> is set without <code>PATH</code>, lookup on Unix is performed
on a default search path search of <code>/usr/bin:/bin</code> (see your operating system's
manual for execvpe/execvp), on Windows the current processes environment
variable <code>PATH</code> is used.</p>
<p>On Windows, environment variables are case-insensitive. Node.js
lexicographically sorts the <code>env</code> keys and uses the first one that
case-insensitively matches. Only first (in lexicographic order) entry will be
passed to the subprocess. This might lead to issues on Windows when passing
objects to the <code>env</code> option that have multiple variants of the same key, such as
<code>PATH</code> and <code>Path</code>.</p>
<p>The <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> method spawns the child process asynchronously,
without blocking the Node.js event loop. The <a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync()</code></a>
function provides equivalent functionality in a synchronous manner that blocks
the event loop until the spawned process either exits or is terminated.</p>
<p>For convenience, the <code>node:child_process</code> module provides a handful of
synchronous and asynchronous alternatives to <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> and
<a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync()</code></a>. Each of these alternatives are implemented on
top of <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> or <a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync()</code></a>.</p>
<ul>
<li><a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a>: spawns a shell and runs a command within that
shell, passing the <code>stdout</code> and <code>stderr</code> to a callback function when
complete.</li>
<li><a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile()</code></a>: similar to <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a> except
that it spawns the command directly without first spawning a shell by
default.</li>
<li><a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>: spawns a new Node.js process and invokes a
specified module with an IPC communication channel established that allows
sending messages between parent and child.</li>
<li><a href="#all_child_process_child_processexecsynccommand-options"><code>child_process.execSync()</code></a>: a synchronous version of
<a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a> that will block the Node.js event loop.</li>
<li><a href="#all_child_process_child_processexecfilesyncfile-args-options"><code>child_process.execFileSync()</code></a>: a synchronous version of
<a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile()</code></a> that will block the Node.js event loop.</li>
</ul>
<p>For certain use cases, such as automating shell scripts, the
<a href="#all_child_process_synchronous-process-creation">synchronous counterparts</a> may be more convenient. In many cases, however,
the synchronous methods can have significant impact on performance due to
stalling the event loop while spawned processes complete.</p>
<section><h3>Asynchronous process creation<span><a class="mark" href="#all_child_process_asynchronous-process-creation" id="all_child_process_asynchronous-process-creation">#</a></span><a aria-hidden="true" class="legacy" id="child_process_asynchronous_process_creation"></a></h3>
<p>The <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>, <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>, <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a>,
and <a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile()</code></a> methods all follow the idiomatic asynchronous
programming pattern typical of other Node.js APIs.</p>
<p>Each of the methods returns a <a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> instance. These objects
implement the Node.js <a href="#all_events_class-eventemitter"><code>EventEmitter</code></a> API, allowing the parent process to
register listener functions that are called when certain events occur during
the life cycle of the child process.</p>
<p>The <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a> and <a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile()</code></a> methods
additionally allow for an optional <code>callback</code> function to be specified that is
invoked when the child process terminates.</p>
<h4>Spawning <code>.bat</code> and <code>.cmd</code> files on Windows<span><a class="mark" href="#all_child_process_spawning-bat-and-cmd-files-on-windows" id="all_child_process_spawning-bat-and-cmd-files-on-windows">#</a></span><a aria-hidden="true" class="legacy" id="child_process_spawning_bat_and_cmd_files_on_windows"></a></h4>
<p>The importance of the distinction between <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a> and
<a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile()</code></a> can vary based on platform. On Unix-type
operating systems (Unix, Linux, macOS) <a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile()</code></a> can be
more efficient because it does not spawn a shell by default. On Windows,
however, <code>.bat</code> and <code>.cmd</code> files are not executable on their own without a
terminal, and therefore cannot be launched using <a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile()</code></a>.
When running on Windows, <code>.bat</code> and <code>.cmd</code> files can be invoked using
<a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> with the <code>shell</code> option set, with
<a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a>, or by spawning <code>cmd.exe</code> and passing the <code>.bat</code> or
<code>.cmd</code> file as an argument (which is what the <code>shell</code> option and
<a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a> do). In any case, if the script filename contains
spaces it needs to be quoted.</p>
<pre class="with-54-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-comment">// OR...</span>
<span class="hljs-keyword">const</span> { exec, spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'my.bat'</span>, <span class="hljs-function">(<span class="hljs-params">err, stdout, stderr</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">return</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
});
<span class="hljs-comment">// Script with spaces in the filename:</span>
<span class="hljs-keyword">const</span> bat = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'"my script.cmd"'</span>, [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>], { <span class="hljs-attr">shell</span>: <span class="hljs-literal">true</span> });
<span class="hljs-comment">// or:</span>
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'"my script.cmd" a b'</span>, <span class="hljs-function">(<span class="hljs-params">err, stdout, stderr</span>) =></span> {
<span class="hljs-comment">// ...</span>
});</code><code class="language-js mjs"><span class="hljs-comment">// OR...</span>
<span class="hljs-keyword">import</span> { exec, spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'my.bat'</span>, <span class="hljs-function">(<span class="hljs-params">err, stdout, stderr</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">return</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
});
<span class="hljs-comment">// Script with spaces in the filename:</span>
<span class="hljs-keyword">const</span> bat = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'"my script.cmd"'</span>, [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>], { <span class="hljs-attr">shell</span>: <span class="hljs-literal">true</span> });
<span class="hljs-comment">// or:</span>
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'"my script.cmd" a b'</span>, <span class="hljs-function">(<span class="hljs-params">err, stdout, stderr</span>) =></span> {
<span class="hljs-comment">// ...</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>child_process.exec(command[, options][, callback])</code><span><a class="mark" href="#all_child_process_child_processexeccommand-options-callback" id="all_child_process_child_processexeccommand-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_exec_command_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>v15.4.0</td>
<td><p>AbortSignal support was added.</p></td></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The command to run, with space-separated arguments.</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>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> Current working directory of the child process.
<strong>Default:</strong> <code>process.cwd()</code>.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</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> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Shell to execute the command with. See
<a href="#all_child_process_shell-requirements">Shell requirements</a> and <a href="#all_child_process_default-windows-shell">Default Windows shell</a>. <strong>Default:</strong>
<code>'/bin/sh'</code> on Unix, <code>process.env.ComSpec</code> on Windows.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows aborting the child process using an
AbortSignal.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>0</code></li>
<li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Largest amount of data in bytes allowed on stdout or
stderr. If exceeded, the child process is terminated and any output is
truncated. See caveat at <a href="#all_child_process_maxbuffer-and-unicode"><code>maxBuffer</code> and Unicode</a>.
<strong>Default:</strong> <code>1024 * 1024</code>.</li>
<li><code>killSignal</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#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>'SIGTERM'</code></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the subprocess console window that would
normally be created on Windows systems. <strong>Default:</strong> <code>false</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> called with the output when process terminates.
<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><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="#all_child_process_class-childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>Spawns a shell then executes the <code>command</code> within that shell, buffering any
generated output. The <code>command</code> string passed to the exec function is processed
directly by the shell and special characters (vary based on
<a href="https://en.wikipedia.org/wiki/List_of_command-line_interpreters">shell</a>)
need to be dealt with accordingly:</p>
<pre class="with-47-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> { exec } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'"/path/to/test file/test.sh" arg1 arg2'</span>);
<span class="hljs-comment">// Double quotes are used so that the space in the path is not interpreted as</span>
<span class="hljs-comment">// a delimiter of multiple arguments.</span>
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'echo "The \\$HOME variable is $HOME"'</span>);
<span class="hljs-comment">// The $HOME variable is escaped in the first instance, but not in the second.</span></code><code class="language-js mjs"><span class="hljs-keyword">import</span> { exec } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'"/path/to/test file/test.sh" arg1 arg2'</span>);
<span class="hljs-comment">// Double quotes are used so that the space in the path is not interpreted as</span>
<span class="hljs-comment">// a delimiter of multiple arguments.</span>
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'echo "The \\$HOME variable is $HOME"'</span>);
<span class="hljs-comment">// The $HOME variable is escaped in the first instance, but not in the second.</span></code><button class="copy-button">copy</button></pre>
<p><strong>Never pass unsanitized user input to this function. Any input containing shell
metacharacters may be used to trigger arbitrary command execution.</strong></p>
<p>If a <code>callback</code> function is provided, it is called with the arguments
<code>(error, stdout, stderr)</code>. On success, <code>error</code> will be <code>null</code>. On error,
<code>error</code> will be an instance of <a href="#all_errors_class-error"><code>Error</code></a>. The <code>error.code</code> property will be
the exit code of the process. By convention, any exit code other than <code>0</code>
indicates an error. <code>error.signal</code> will be the signal that terminated the
process.</p>
<p>The <code>stdout</code> and <code>stderr</code> arguments passed to the callback will contain the
stdout and stderr output of the child process. By default, Node.js will decode
the output as UTF-8 and pass strings to the callback. The <code>encoding</code> option
can be used to specify the character encoding used to decode the stdout and
stderr output. If <code>encoding</code> is <code>'buffer'</code>, or an unrecognized character
encoding, <code>Buffer</code> objects will be passed to the callback instead.</p>
<pre class="with-66-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> { exec } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'cat *.js missing_file | wc -l'</span>, <span class="hljs-function">(<span class="hljs-params">error, stdout, stderr</span>) =></span> {
<span class="hljs-keyword">if</span> (error) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`exec error: <span class="hljs-subst">${error}</span>`</span>);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${stdout}</span>`</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`stderr: <span class="hljs-subst">${stderr}</span>`</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { exec } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'cat *.js missing_file | wc -l'</span>, <span class="hljs-function">(<span class="hljs-params">error, stdout, stderr</span>) =></span> {
<span class="hljs-keyword">if</span> (error) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`exec error: <span class="hljs-subst">${error}</span>`</span>);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${stdout}</span>`</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`stderr: <span class="hljs-subst">${stderr}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<p>If <code>timeout</code> is greater than <code>0</code>, the parent process will send the signal
identified by the <code>killSignal</code> property (the default is <code>'SIGTERM'</code>) if the
child process runs longer than <code>timeout</code> milliseconds.</p>
<p>Unlike the <a href="http://man7.org/linux/man-pages/man3/exec.3.html"><code>exec(3)</code></a> POSIX system call, <code>child_process.exec()</code> does not replace
the existing process and uses a shell to execute the command.</p>
<p>If this method is invoked as its <a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed version, it returns
a <code>Promise</code> for an <code>Object</code> with <code>stdout</code> and <code>stderr</code> properties. The returned
<code>ChildProcess</code> instance is attached to the <code>Promise</code> as a <code>child</code> property. In
case of an error (including any error resulting in an exit code other than 0), a
rejected promise is returned, with the same <code>error</code> object given in the
callback, but with two additional properties <code>stdout</code> and <code>stderr</code>.</p>
<pre class="with-64-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> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> exec = util.<span class="hljs-title function_">promisify</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>).<span class="hljs-property">exec</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">lsExample</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> { stdout, stderr } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">exec</span>(<span class="hljs-string">'ls'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'stdout:'</span>, stdout);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'stderr:'</span>, stderr);
}
<span class="hljs-title function_">lsExample</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { promisify } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">import</span> child_process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> exec = <span class="hljs-title function_">promisify</span>(child_process.<span class="hljs-property">exec</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">lsExample</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> { stdout, stderr } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">exec</span>(<span class="hljs-string">'ls'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'stdout:'</span>, stdout);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'stderr:'</span>, stderr);
}
<span class="hljs-title function_">lsExample</span>();</code><button class="copy-button">copy</button></pre>
<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
<code>AbortController</code> is similar to calling <code>.kill()</code> on the child process except
the error passed to the callback will be an <code>AbortError</code>:</p>
<pre class="with-47-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> { exec } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</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> { signal } = controller;
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">exec</span>(<span class="hljs-string">'grep ssh'</span>, { signal }, <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-comment">// an AbortError</span>
});
controller.<span class="hljs-title function_">abort</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { exec } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</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> { signal } = controller;
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">exec</span>(<span class="hljs-string">'grep ssh'</span>, { signal }, <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-comment">// an AbortError</span>
});
controller.<span class="hljs-title function_">abort</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>child_process.execFile(file[, args][, options][, callback])</code><span><a class="mark" href="#all_child_process_child_processexecfilefile-args-options-callback" id="all_child_process_child_processexecfilefile-args-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_execfile_file_args_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>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v15.4.0, v14.17.0</td>
<td><p>AbortSignal support was added.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v0.1.91</td>
<td><p><span>Added in: v0.1.91</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name or path of the executable file to run.</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments.</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>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> Current working directory of the child process.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</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> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>0</code></li>
<li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Largest amount of data in bytes allowed on stdout or
stderr. If exceeded, the child process is terminated and any output is
truncated. See caveat at <a href="#all_child_process_maxbuffer-and-unicode"><code>maxBuffer</code> and Unicode</a>.
<strong>Default:</strong> <code>1024 * 1024</code>.</li>
<li><code>killSignal</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#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>'SIGTERM'</code></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the subprocess console window that would
normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li>
<li><code>windowsVerbatimArguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> No quoting or escaping of arguments is
done on Windows. Ignored on Unix. <strong>Default:</strong> <code>false</code>.</li>
<li><code>shell</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#String_type" class="type"><string></a> If <code>true</code>, runs <code>command</code> inside of a shell. Uses
<code>'/bin/sh'</code> on Unix, and <code>process.env.ComSpec</code> on Windows. A different
shell can be specified as a string. See <a href="#all_child_process_shell-requirements">Shell requirements</a> and
<a href="#all_child_process_default-windows-shell">Default Windows shell</a>. <strong>Default:</strong> <code>false</code> (no shell).</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows aborting the child process using an
AbortSignal.</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 with the output when process terminates.
<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><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="#all_child_process_class-childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>The <code>child_process.execFile()</code> function is similar to <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a>
except that it does not spawn a shell by default. Rather, the specified
executable <code>file</code> is spawned directly as a new process making it slightly more
efficient than <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a>.</p>
<p>The same options as <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a> are supported. Since a shell is
not spawned, behaviors such as I/O redirection and file globbing are not
supported.</p>
<pre class="with-74-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> { execFile } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">execFile</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'--version'</span>], <span class="hljs-function">(<span class="hljs-params">error, stdout, stderr</span>) =></span> {
<span class="hljs-keyword">if</span> (error) {
<span class="hljs-keyword">throw</span> error;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { execFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">execFile</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'--version'</span>], <span class="hljs-function">(<span class="hljs-params">error, stdout, stderr</span>) =></span> {
<span class="hljs-keyword">if</span> (error) {
<span class="hljs-keyword">throw</span> error;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
});</code><button class="copy-button">copy</button></pre>
<p>The <code>stdout</code> and <code>stderr</code> arguments passed to the callback will contain the
stdout and stderr output of the child process. By default, Node.js will decode
the output as UTF-8 and pass strings to the callback. The <code>encoding</code> option
can be used to specify the character encoding used to decode the stdout and
stderr output. If <code>encoding</code> is <code>'buffer'</code>, or an unrecognized character
encoding, <code>Buffer</code> objects will be passed to the callback instead.</p>
<p>If this method is invoked as its <a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed version, it returns
a <code>Promise</code> for an <code>Object</code> with <code>stdout</code> and <code>stderr</code> properties. The returned
<code>ChildProcess</code> instance is attached to the <code>Promise</code> as a <code>child</code> property. In
case of an error (including any error resulting in an exit code other than 0), a
rejected promise is returned, with the same <code>error</code> object given in the
callback, but with two additional properties <code>stdout</code> and <code>stderr</code>.</p>
<pre class="with-72-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> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> execFile = util.<span class="hljs-title function_">promisify</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>).<span class="hljs-property">execFile</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getVersion</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> { stdout } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">execFile</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'--version'</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
}
<span class="hljs-title function_">getVersion</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { promisify } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">import</span> child_process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> execFile = <span class="hljs-title function_">promisify</span>(child_process.<span class="hljs-property">execFile</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getVersion</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> { stdout } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">execFile</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'--version'</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
}
<span class="hljs-title function_">getVersion</span>();</code><button class="copy-button">copy</button></pre>
<p><strong>If the <code>shell</code> option is enabled, do not pass unsanitized user input to this
function. Any input containing shell metacharacters may be used to trigger
arbitrary command execution.</strong></p>
<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
<code>AbortController</code> is similar to calling <code>.kill()</code> on the child process except
the error passed to the callback will be an <code>AbortError</code>:</p>
<pre class="with-51-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> { execFile } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</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> { signal } = controller;
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">execFile</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'--version'</span>], { signal }, <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-comment">// an AbortError</span>
});
controller.<span class="hljs-title function_">abort</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { execFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</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> { signal } = controller;
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">execFile</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'--version'</span>], { signal }, <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-comment">// an AbortError</span>
});
controller.<span class="hljs-title function_">abort</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>child_process.fork(modulePath[, args][, options])</code><span><a class="mark" href="#all_child_process_child_processforkmodulepath-args-options" id="all_child_process_child_processforkmodulepath-args-options">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_fork_modulepath_args_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>v17.4.0, v16.14.0</td>
<td><p>The <code>modulePath</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v15.13.0, v14.18.0</td>
<td><p>timeout was added.</p></td></tr>
<tr><td>v15.11.0, v14.18.0</td>
<td><p>killSignal for AbortSignal was added.</p></td></tr>
<tr><td>v15.6.0, v14.17.0</td>
<td><p>AbortSignal support was added.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>The <code>serialization</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>stdio</code> option can now be a string.</p></td></tr>
<tr><td>v6.4.0</td>
<td><p>The <code>stdio</code> option is supported now.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>modulePath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> The module to run in the child.</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments.</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>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> Current working directory of the child process.</li>
<li><code>detached</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Prepare child process to run independently of its
parent process. Specific behavior depends on the platform (see
<a href="#all_child_process_optionsdetached"><code>options.detached</code></a>).</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>execPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Executable used to create the child process.</li>
<li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments passed to the executable.
<strong>Default:</strong> <code>process.execArgv</code>.</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>serialization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specify the kind of serialization used for sending
messages between processes. Possible values are <code>'json'</code> and <code>'advanced'</code>.
See <a href="#all_child_process_advanced-serialization">Advanced serialization</a> for more details. <strong>Default:</strong> <code>'json'</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows closing the child process using an
AbortSignal.</li>
<li><code>killSignal</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#Number_type" class="type"><integer></a> The signal value to be used when the spawned
process will be killed by timeout or abort signal. <strong>Default:</strong> <code>'SIGTERM'</code>.</li>
<li><code>silent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, stdin, stdout, and stderr of the child
process will be piped to the parent process, otherwise they will be inherited
from the parent process, see the <code>'pipe'</code> and <code>'inherit'</code> options for
<a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s <a href="#all_child_process_optionsstdio"><code>stdio</code></a> for more details.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s <a href="#all_child_process_optionsstdio"><code>stdio</code></a>.
When this option is provided, it overrides <code>silent</code>. If the array variant
is used, it must contain exactly one item with value <code>'ipc'</code> or an error
will be thrown. For instance <code>[0, 1, 2, 'ipc']</code>.</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>windowsVerbatimArguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> No quoting or escaping of arguments is
done on Windows. Ignored on Unix. <strong>Default:</strong> <code>false</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> In milliseconds the maximum amount of time the process
is allowed to run. <strong>Default:</strong> <code>undefined</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_child_process_class-childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>The <code>child_process.fork()</code> method is a special case of
<a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> used specifically to spawn new Node.js processes.
Like <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>, a <a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> object is returned. The
returned <a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> will have an additional communication channel
built-in that allows messages to be passed back and forth between the parent and
child. See <a href="#all_child_process_subprocesssendmessage-sendhandle-options-callback"><code>subprocess.send()</code></a> for details.</p>
<p>Keep in mind that spawned Node.js child processes are
independent of the parent with exception of the IPC communication channel
that is established between the two. Each process has its own memory, with
their own V8 instances. Because of the additional resource allocations
required, spawning a large number of child Node.js processes is not
recommended.</p>
<p>By default, <code>child_process.fork()</code> will spawn new Node.js instances using the
<a href="#all_process_processexecpath"><code>process.execPath</code></a> of the parent process. The <code>execPath</code> property in the
<code>options</code> object allows for an alternative execution path to be used.</p>
<p>Node.js processes launched with a custom <code>execPath</code> will communicate with the
parent process using the file descriptor (fd) identified using the
environment variable <code>NODE_CHANNEL_FD</code> on the child process.</p>
<p>Unlike the <a href="http://man7.org/linux/man-pages/man2/fork.2.html"><code>fork(2)</code></a> POSIX system call, <code>child_process.fork()</code> does not clone the
current process.</p>
<p>The <code>shell</code> option available in <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> is not supported by
<code>child_process.fork()</code> and will be ignored if set.</p>
<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
<code>AbortController</code> is similar to calling <code>.kill()</code> on the child process except
the error passed to the callback will be an <code>AbortError</code>:</p>
<pre class="with-47-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> { fork } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">argv</span>[<span class="hljs-number">2</span>] === <span class="hljs-string">'child'</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">`Hello from <span class="hljs-subst">${process.argv[<span class="hljs-number">2</span>]}</span>!`</span>);
}, <span class="hljs-number">1_000</span>);
} <span class="hljs-keyword">else</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> { signal } = controller;
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">fork</span>(__filename, [<span class="hljs-string">'child'</span>], { signal });
child.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-comment">// This will be called with err being an AbortError if the controller aborts</span>
});
controller.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Stops the child process</span>
}</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { fork } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">argv</span>[<span class="hljs-number">2</span>] === <span class="hljs-string">'child'</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">`Hello from <span class="hljs-subst">${process.argv[<span class="hljs-number">2</span>]}</span>!`</span>);
}, <span class="hljs-number">1_000</span>);
} <span class="hljs-keyword">else</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> { signal } = controller;
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">fork</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>, [<span class="hljs-string">'child'</span>], { signal });
child.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-comment">// This will be called with err being an AbortError if the controller aborts</span>
});
controller.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Stops the child process</span>
}</code><button class="copy-button">copy</button></pre>
<h4><code>child_process.spawn(command[, args][, options])</code><span><a class="mark" href="#all_child_process_child_processspawncommand-args-options" id="all_child_process_child_processspawncommand-args-options">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_spawn_command_args_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>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v15.13.0, v14.18.0</td>
<td><p>timeout was added.</p></td></tr>
<tr><td>v15.11.0, v14.18.0</td>
<td><p>killSignal for AbortSignal was added.</p></td></tr>
<tr><td>v15.5.0, v14.17.0</td>
<td><p>AbortSignal support was added.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>The <code>serialization</code> option is supported now.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v6.4.0</td>
<td><p>The <code>argv0</code> option is supported now.</p></td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>shell</code> option is supported now.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The command to run.</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments.</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>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> Current working directory of the child process.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>argv0</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Explicitly set the value of <code>argv[0]</code> sent to the child
process. This will be set to <code>command</code> if not specified.</li>
<li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Child's stdio configuration (see
<a href="#all_child_process_optionsstdio"><code>options.stdio</code></a>).</li>
<li><code>detached</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Prepare child process to run independently of
its parent process. Specific behavior depends on the platform (see
<a href="#all_child_process_optionsdetached"><code>options.detached</code></a>).</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>serialization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specify the kind of serialization used for sending
messages between processes. Possible values are <code>'json'</code> and <code>'advanced'</code>.
See <a href="#all_child_process_advanced-serialization">Advanced serialization</a> for more details. <strong>Default:</strong> <code>'json'</code>.</li>
<li><code>shell</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#String_type" class="type"><string></a> If <code>true</code>, runs <code>command</code> inside of a shell. Uses
<code>'/bin/sh'</code> on Unix, and <code>process.env.ComSpec</code> on Windows. A different
shell can be specified as a string. See <a href="#all_child_process_shell-requirements">Shell requirements</a> and
<a href="#all_child_process_default-windows-shell">Default Windows shell</a>. <strong>Default:</strong> <code>false</code> (no shell).</li>
<li><code>windowsVerbatimArguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> No quoting or escaping of arguments is
done on Windows. Ignored on Unix. This is set to <code>true</code> automatically
when <code>shell</code> is specified and is CMD. <strong>Default:</strong> <code>false</code>.</li>
<li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the subprocess console window that would
normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows aborting the child process using an
AbortSignal.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> In milliseconds the maximum amount of time the process
is allowed to run. <strong>Default:</strong> <code>undefined</code>.</li>
<li><code>killSignal</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#Number_type" class="type"><integer></a> The signal value to be used when the spawned
process will be killed by timeout or abort signal. <strong>Default:</strong> <code>'SIGTERM'</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_child_process_class-childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>The <code>child_process.spawn()</code> method spawns a new process using the given
<code>command</code>, with command-line arguments in <code>args</code>. If omitted, <code>args</code> defaults
to an empty array.</p>
<p><strong>If the <code>shell</code> option is enabled, do not pass unsanitized user input to this
function. Any input containing shell metacharacters may be used to trigger
arbitrary command execution.</strong></p>
<p>A third argument may be used to specify additional options, with these defaults:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> defaults = {
<span class="hljs-attr">cwd</span>: <span class="hljs-literal">undefined</span>,
<span class="hljs-attr">env</span>: process.<span class="hljs-property">env</span>,
};</code> <button class="copy-button">copy</button></pre>
<p>Use <code>cwd</code> to specify the working directory from which the process is spawned.
If not given, the default is to inherit the current working directory. If given,
but the path does not exist, the child process emits an <code>ENOENT</code> error
and exits immediately. <code>ENOENT</code> is also emitted when the command
does not exist.</p>
<p>Use <code>env</code> to specify environment variables that will be visible to the new
process, the default is <a href="#all_process_processenv"><code>process.env</code></a>.</p>
<p><code>undefined</code> values in <code>env</code> will be ignored.</p>
<p>Example of running <code>ls -lh /usr</code>, capturing <code>stdout</code>, <code>stderr</code>, and the
exit code:</p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> ls = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, [<span class="hljs-string">'-lh'</span>, <span class="hljs-string">'/usr'</span>]);
ls.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${data}</span>`</span>);
});
ls.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`stderr: <span class="hljs-subst">${data}</span>`</span>);
});
ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process exited with code <span class="hljs-subst">${code}</span>`</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> ls = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, [<span class="hljs-string">'-lh'</span>, <span class="hljs-string">'/usr'</span>]);
ls.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${data}</span>`</span>);
});
ls.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`stderr: <span class="hljs-subst">${data}</span>`</span>);
});
ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process exited with code <span class="hljs-subst">${code}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Example: A very elaborate way to run <code>ps ax | grep ssh</code></p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> ps = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ps'</span>, [<span class="hljs-string">'ax'</span>]);
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>]);
ps.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
grep.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">write</span>(data);
});
ps.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`ps stderr: <span class="hljs-subst">${data}</span>`</span>);
});
ps.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`ps process exited with code <span class="hljs-subst">${code}</span>`</span>);
}
grep.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">end</span>();
});
grep.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>());
});
grep.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`grep stderr: <span class="hljs-subst">${data}</span>`</span>);
});
grep.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`grep process exited with code <span class="hljs-subst">${code}</span>`</span>);
}
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> ps = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ps'</span>, [<span class="hljs-string">'ax'</span>]);
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>]);
ps.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
grep.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">write</span>(data);
});
ps.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`ps stderr: <span class="hljs-subst">${data}</span>`</span>);
});
ps.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`ps process exited with code <span class="hljs-subst">${code}</span>`</span>);
}
grep.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">end</span>();
});
grep.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>());
});
grep.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`grep stderr: <span class="hljs-subst">${data}</span>`</span>);
});
grep.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`grep process exited with code <span class="hljs-subst">${code}</span>`</span>);
}
});</code><button class="copy-button">copy</button></pre>
<p>Example of checking for failed <code>spawn</code>:</p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'bad_command'</span>);
subprocess.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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>(<span class="hljs-string">'Failed to start subprocess.'</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'bad_command'</span>);
subprocess.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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>(<span class="hljs-string">'Failed to start subprocess.'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Certain platforms (macOS, Linux) will use the value of <code>argv[0]</code> for the process
title while others (Windows, SunOS) will use <code>command</code>.</p>
<p>Node.js overwrites <code>argv[0]</code> with <code>process.execPath</code> on startup, so
<code>process.argv[0]</code> in a Node.js child process will not match the <code>argv0</code>
parameter passed to <code>spawn</code> from the parent. Retrieve it with the
<code>process.argv0</code> property instead.</p>
<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
<code>AbortController</code> is similar to calling <code>.kill()</code> on the child process except
the error passed to the callback will be an <code>AbortError</code>:</p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</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> { signal } = controller;
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>], { signal });
grep.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-comment">// This will be called with err being an AbortError if the controller aborts</span>
});
controller.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Stops the child process</span></code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</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> { signal } = controller;
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>], { signal });
grep.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-comment">// This will be called with err being an AbortError if the controller aborts</span>
});
controller.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Stops the child process</span></code><button class="copy-button">copy</button></pre>
<h5><code>options.detached</code><span><a class="mark" href="#all_child_process_optionsdetached" id="all_child_process_optionsdetached">#</a></span><a aria-hidden="true" class="legacy" id="child_process_options_detached"></a></h5>
<div class="api_metadata">
<span>Added in: v0.7.10</span>
</div>
<p>On Windows, setting <code>options.detached</code> to <code>true</code> makes it possible for the
child process to continue running after the parent exits. The child process
will have its own console window. Once enabled for a child process,
it cannot be disabled.</p>
<p>On non-Windows platforms, if <code>options.detached</code> is set to <code>true</code>, the child
process will be made the leader of a new process group and session. Child
processes may continue running after the parent exits regardless of whether
they are detached or not. See <a href="http://man7.org/linux/man-pages/man2/setsid.2.html"><code>setsid(2)</code></a> for more information.</p>
<p>By default, the parent will wait for the detached child process to exit.
To prevent the parent process from waiting for a given <code>subprocess</code> to exit, use
the <code>subprocess.unref()</code> method. Doing so will cause the parent process' event
loop to not include the child process in its reference count, allowing the
parent process to exit independently of the child process, unless there is an established
IPC channel between the child and the parent processes.</p>
<p>When using the <code>detached</code> option to start a long-running process, the process
will not stay running in the background after the parent exits unless it is
provided with a <code>stdio</code> configuration that is not connected to the parent.
If the parent process' <code>stdio</code> is inherited, the child process will remain attached
to the controlling terminal.</p>
<p>Example of a long-running process, by detaching and also ignoring its parent
<code>stdio</code> file descriptors, in order to ignore the parent's termination:</p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(process.<span class="hljs-property">argv</span>[<span class="hljs-number">0</span>], [<span class="hljs-string">'child_program.js'</span>], {
<span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">stdio</span>: <span class="hljs-string">'ignore'</span>,
});
subprocess.<span class="hljs-title function_">unref</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(process.<span class="hljs-property">argv</span>[<span class="hljs-number">0</span>], [<span class="hljs-string">'child_program.js'</span>], {
<span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">stdio</span>: <span class="hljs-string">'ignore'</span>,
});
subprocess.<span class="hljs-title function_">unref</span>();</code><button class="copy-button">copy</button></pre>
<p>Alternatively one can redirect the child process' output into files:</p>
<pre class="with-48-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> { openSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> out = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'./out.log'</span>, <span class="hljs-string">'a'</span>);
<span class="hljs-keyword">const</span> err = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'./out.log'</span>, <span class="hljs-string">'a'</span>);
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], {
<span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">stdio</span>: [ <span class="hljs-string">'ignore'</span>, out, err ],
});
subprocess.<span class="hljs-title function_">unref</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { openSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> out = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'./out.log'</span>, <span class="hljs-string">'a'</span>);
<span class="hljs-keyword">const</span> err = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'./out.log'</span>, <span class="hljs-string">'a'</span>);
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], {
<span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">stdio</span>: [ <span class="hljs-string">'ignore'</span>, out, err ],
});
subprocess.<span class="hljs-title function_">unref</span>();</code><button class="copy-button">copy</button></pre>
<h5><code>options.stdio</code><span><a class="mark" href="#all_child_process_optionsstdio" id="all_child_process_optionsstdio">#</a></span><a aria-hidden="true" class="legacy" id="child_process_options_stdio"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.6.0, v14.18.0</td>
<td><p>Added the <code>overlapped</code> stdio flag.</p></td></tr>
<tr><td>v3.3.1</td>
<td><p>The value <code>0</code> is now accepted as a file descriptor.</p></td></tr>
<tr><td>v0.7.10</td>
<td><p><span>Added in: v0.7.10</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>options.stdio</code> option is used to configure the pipes that are established
between the parent and child process. By default, the child's stdin, stdout,
and stderr are redirected to corresponding <a href="#all_child_process_subprocessstdin"><code>subprocess.stdin</code></a>,
<a href="#all_child_process_subprocessstdout"><code>subprocess.stdout</code></a>, and <a href="#all_child_process_subprocessstderr"><code>subprocess.stderr</code></a> streams on the
<a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> object. This is equivalent to setting the <code>options.stdio</code>
equal to <code>['pipe', 'pipe', 'pipe']</code>.</p>
<p>For convenience, <code>options.stdio</code> may be one of the following strings:</p>
<ul>
<li><code>'pipe'</code>: equivalent to <code>['pipe', 'pipe', 'pipe']</code> (the default)</li>
<li><code>'overlapped'</code>: equivalent to <code>['overlapped', 'overlapped', 'overlapped']</code></li>
<li><code>'ignore'</code>: equivalent to <code>['ignore', 'ignore', 'ignore']</code></li>
<li><code>'inherit'</code>: equivalent to <code>['inherit', 'inherit', 'inherit']</code> or <code>[0, 1, 2]</code></li>
</ul>
<p>Otherwise, the value of <code>options.stdio</code> is an array where each index corresponds
to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,
and stderr, respectively. Additional fds can be specified to create additional
pipes between the parent and child. The value is one of the following:</p>
<ol>
<li>
<p><code>'pipe'</code>: Create a pipe between the child process and the parent process.
The parent end of the pipe is exposed to the parent as a property on the
<code>child_process</code> object as <a href="#all_child_process_subprocessstdio"><code>subprocess.stdio[fd]</code></a>. Pipes
created for fds 0, 1, and 2 are also available as <a href="#all_child_process_subprocessstdin"><code>subprocess.stdin</code></a>,
<a href="#all_child_process_subprocessstdout"><code>subprocess.stdout</code></a> and <a href="#all_child_process_subprocessstderr"><code>subprocess.stderr</code></a>, respectively.
These are not actual Unix pipes and therefore the child process
can not use them by their descriptor files,
e.g. <code>/dev/fd/2</code> or <code>/dev/stdout</code>.</p>
</li>
<li>
<p><code>'overlapped'</code>: Same as <code>'pipe'</code> except that the <code>FILE_FLAG_OVERLAPPED</code> flag
is set on the handle. This is necessary for overlapped I/O on the child
process's stdio handles. See the
<a href="https://docs.microsoft.com/en-us/windows/win32/fileio/synchronous-and-asynchronous-i-o">docs</a>
for more details. This is exactly the same as <code>'pipe'</code> on non-Windows
systems.</p>
</li>
<li>
<p><code>'ipc'</code>: Create an IPC channel for passing messages/file descriptors
between parent and child. A <a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> may have at most one IPC
stdio file descriptor. Setting this option enables the
<a href="#all_child_process_subprocesssendmessage-sendhandle-options-callback"><code>subprocess.send()</code></a> method. If the child process is a Node.js instance,
the presence of an IPC channel will enable <a href="#all_process_processsendmessage-sendhandle-options-callback"><code>process.send()</code></a> and
<a href="#all_process_processdisconnect"><code>process.disconnect()</code></a> methods, as well as <a href="#all_process_event-disconnect"><code>'disconnect'</code></a> and
<a href="#all_process_event-message"><code>'message'</code></a> events within the child process.</p>
<p>Accessing the IPC channel fd in any way other than <a href="#all_process_processsendmessage-sendhandle-options-callback"><code>process.send()</code></a>
or using the IPC channel with a child process that is not a Node.js instance
is not supported.</p>
</li>
<li>
<p><code>'ignore'</code>: Instructs Node.js to ignore the fd in the child. While Node.js
will always open fds 0, 1, and 2 for the processes it spawns, setting the fd
to <code>'ignore'</code> will cause Node.js to open <code>/dev/null</code> and attach it to the
child's fd.</p>
</li>
<li>
<p><code>'inherit'</code>: Pass through the corresponding stdio stream to/from the
parent process. In the first three positions, this is equivalent to
<code>process.stdin</code>, <code>process.stdout</code>, and <code>process.stderr</code>, respectively. In
any other position, equivalent to <code>'ignore'</code>.</p>
</li>
<li>
<p><a href="#all_stream_stream" class="type"><Stream></a> object: Share a readable or writable stream that refers to a tty,
file, socket, or a pipe with the child process. The stream's underlying
file descriptor is duplicated in the child process to the fd that
corresponds to the index in the <code>stdio</code> array. The stream must have an
underlying descriptor (file streams do not start until the <code>'open'</code> event has
occurred).
<strong>NOTE:</strong> While it is technically possible to pass <code>stdin</code> as a writable or
<code>stdout</code>/<code>stderr</code> as readable, it is not recommended.
Readable and writable streams are designed with distinct behaviors, and using
them incorrectly (e.g., passing a readable stream where a writable stream is
expected) can lead to unexpected results or errors. This practice is discouraged
as it may result in undefined behavior or dropped callbacks if the stream
encounters errors. Always ensure that <code>stdin</code> is used as writable and
<code>stdout</code>/<code>stderr</code> as readable to maintain the intended flow of data between
the parent and child processes.</p>
</li>
<li>
<p>Positive integer: The integer value is interpreted as a file descriptor
that is open in the parent process. It is shared with the child
process, similar to how <a href="#all_stream_stream" class="type"><Stream></a> objects can be shared. Passing sockets
is not supported on Windows.</p>
</li>
<li>
<p><code>null</code>, <code>undefined</code>: Use default value. For stdio fds 0, 1, and 2 (in other
words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
default is <code>'ignore'</code>.</p>
</li>
</ol>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-comment">// Child will use parent's stdios.</span>
<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], { <span class="hljs-attr">stdio</span>: <span class="hljs-string">'inherit'</span> });
<span class="hljs-comment">// Spawn child sharing only stderr.</span>
<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], { <span class="hljs-attr">stdio</span>: [<span class="hljs-string">'pipe'</span>, <span class="hljs-string">'pipe'</span>, process.<span class="hljs-property">stderr</span>] });
<span class="hljs-comment">// Open an extra fd=4, to interact with programs presenting a</span>
<span class="hljs-comment">// startd-style interface.</span>
<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], { <span class="hljs-attr">stdio</span>: [<span class="hljs-string">'pipe'</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>, <span class="hljs-string">'pipe'</span>] });</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-comment">// Child will use parent's stdios.</span>
<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], { <span class="hljs-attr">stdio</span>: <span class="hljs-string">'inherit'</span> });
<span class="hljs-comment">// Spawn child sharing only stderr.</span>
<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], { <span class="hljs-attr">stdio</span>: [<span class="hljs-string">'pipe'</span>, <span class="hljs-string">'pipe'</span>, process.<span class="hljs-property">stderr</span>] });
<span class="hljs-comment">// Open an extra fd=4, to interact with programs presenting a</span>
<span class="hljs-comment">// startd-style interface.</span>
<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], { <span class="hljs-attr">stdio</span>: [<span class="hljs-string">'pipe'</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>, <span class="hljs-string">'pipe'</span>] });</code><button class="copy-button">copy</button></pre>
<p><em>It is worth noting that when an IPC channel is established between the
parent and child processes, and the child process is a Node.js instance,
the child process is launched with the IPC channel unreferenced (using
<code>unref()</code>) until the child process registers an event handler for the
<a href="#all_process_event-disconnect"><code>'disconnect'</code></a> event or the <a href="#all_process_event-message"><code>'message'</code></a> event. This allows the
child process to exit normally without the process being held open by the
open IPC channel.</em>
See also: <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a> and <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>.</p>
</section><section><h3>Synchronous process creation<span><a class="mark" href="#all_child_process_synchronous-process-creation" id="all_child_process_synchronous-process-creation">#</a></span><a aria-hidden="true" class="legacy" id="child_process_synchronous_process_creation"></a></h3>
<p>The <a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync()</code></a>, <a href="#all_child_process_child_processexecsynccommand-options"><code>child_process.execSync()</code></a>, and
<a href="#all_child_process_child_processexecfilesyncfile-args-options"><code>child_process.execFileSync()</code></a> methods are synchronous and will block the
Node.js event loop, pausing execution of any additional code until the spawned
process exits.</p>
<p>Blocking calls like these are mostly useful for simplifying general-purpose
scripting tasks and for simplifying the loading/processing of application
configuration at startup.</p>
<h4><code>child_process.execFileSync(file[, args][, options])</code><span><a class="mark" href="#all_child_process_child_processexecfilesyncfile-args-options" id="all_child_process_child_processexecfilesyncfile-args-options">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_execfilesync_file_args_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>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>input</code> option can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>input</code> option can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v6.2.1, v4.5.0</td>
<td><p>The <code>encoding</code> option can now explicitly be set to <code>buffer</code>.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name or path of the executable file to run.</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments.</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>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> Current working directory of the child process.</li>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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> The value which will be passed
as stdin to the spawned process. If <code>stdio[0]</code> is set to <code>'pipe'</code>, Supplying
this value will override <code>stdio[0]</code>.</li>
<li><code>stdio</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/Reference/Global_Objects/Array" class="type"><Array></a> Child's stdio configuration.
See <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s <a href="#all_child_process_optionsstdio"><code>stdio</code></a>. <code>stderr</code> by default will
be output to the parent process' stderr unless <code>stdio</code> is specified.
<strong>Default:</strong> <code>'pipe'</code>.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> In milliseconds the maximum amount of time the process
is allowed to run. <strong>Default:</strong> <code>undefined</code>.</li>
<li><code>killSignal</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#Number_type" class="type"><integer></a> The signal value to be used when the spawned
process will be killed. <strong>Default:</strong> <code>'SIGTERM'</code>.</li>
<li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Largest amount of data in bytes allowed on stdout or
stderr. If exceeded, the child process is terminated. See caveat at
<a href="#all_child_process_maxbuffer-and-unicode"><code>maxBuffer</code> and Unicode</a>. <strong>Default:</strong> <code>1024 * 1024</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 used for all stdio inputs and outputs.
<strong>Default:</strong> <code>'buffer'</code>.</li>
<li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the subprocess console window that would
normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li>
<li><code>shell</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#String_type" class="type"><string></a> If <code>true</code>, runs <code>command</code> inside of a shell. Uses
<code>'/bin/sh'</code> on Unix, and <code>process.env.ComSpec</code> on Windows. A different
shell can be specified as a string. See <a href="#all_child_process_shell-requirements">Shell requirements</a> and
<a href="#all_child_process_default-windows-shell">Default Windows shell</a>. <strong>Default:</strong> <code>false</code> (no shell).</li>
</ul>
</li>
<li>Returns: <a href="#all_buffer_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> The stdout from the command.</li>
</ul>
<p>The <code>child_process.execFileSync()</code> method is generally identical to
<a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile()</code></a> with the exception that the method will not
return until the child process has fully closed. When a timeout has been
encountered and <code>killSignal</code> is sent, the method won't return until the process
has completely exited.</p>
<p>If the child process intercepts and handles the <code>SIGTERM</code> signal and
does not exit, the parent process will still wait until the child process has
exited.</p>
<p>If the process times out or has a non-zero exit code, this method will throw an
<a href="#all_errors_class-error"><code>Error</code></a> that will include the full result of the underlying
<a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync()</code></a>.</p>
<p><strong>If the <code>shell</code> option is enabled, do not pass unsanitized user input to this
function. Any input containing shell metacharacters may be used to trigger
arbitrary command execution.</strong></p>
<pre class="with-55-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> { execFileSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> stdout = <span class="hljs-title function_">execFileSync</span>(<span class="hljs-string">'my-script.sh'</span>, [<span class="hljs-string">'my-arg'</span>], {
<span class="hljs-comment">// Capture stdout and stderr from child process. Overrides the</span>
<span class="hljs-comment">// default behavior of streaming child stderr to the parent stderr</span>
<span class="hljs-attr">stdio</span>: <span class="hljs-string">'pipe'</span>,
<span class="hljs-comment">// Use utf8 encoding for stdio pipes</span>
<span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span>,
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span>) {
<span class="hljs-comment">// Spawning child process failed</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span>);
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Child was spawned but exited with non-zero exit code</span>
<span class="hljs-comment">// Error contains any stdout and stderr from the child</span>
<span class="hljs-keyword">const</span> { stdout, stderr } = err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>({ stdout, stderr });
}
}</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { execFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> stdout = <span class="hljs-title function_">execFileSync</span>(<span class="hljs-string">'my-script.sh'</span>, [<span class="hljs-string">'my-arg'</span>], {
<span class="hljs-comment">// Capture stdout and stderr from child process. Overrides the</span>
<span class="hljs-comment">// default behavior of streaming child stderr to the parent stderr</span>
<span class="hljs-attr">stdio</span>: <span class="hljs-string">'pipe'</span>,
<span class="hljs-comment">// Use utf8 encoding for stdio pipes</span>
<span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span>,
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span>) {
<span class="hljs-comment">// Spawning child process failed</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span>);
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Child was spawned but exited with non-zero exit code</span>
<span class="hljs-comment">// Error contains any stdout and stderr from the child</span>
<span class="hljs-keyword">const</span> { stdout, stderr } = err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>({ stdout, stderr });
}
}</code><button class="copy-button">copy</button></pre>
<h4><code>child_process.execSync(command[, options])</code><span><a class="mark" href="#all_child_process_child_processexecsynccommand-options" id="all_child_process_child_processexecsynccommand-options">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_execsync_command_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>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>input</code> option can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>input</code> option can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The command to run.</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>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> Current working directory of the child process.</li>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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> The value which will be passed
as stdin to the spawned process. If <code>stdio[0]</code> is set to <code>'pipe'</code>, Supplying
this value will override <code>stdio[0]</code>.</li>
<li><code>stdio</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/Reference/Global_Objects/Array" class="type"><Array></a> Child's stdio configuration.
See <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s <a href="#all_child_process_optionsstdio"><code>stdio</code></a>. <code>stderr</code> by default will
be output to the parent process' stderr unless <code>stdio</code> is specified.
<strong>Default:</strong> <code>'pipe'</code>.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Shell to execute the command with. See
<a href="#all_child_process_shell-requirements">Shell requirements</a> and <a href="#all_child_process_default-windows-shell">Default Windows shell</a>. <strong>Default:</strong>
<code>'/bin/sh'</code> on Unix, <code>process.env.ComSpec</code> on Windows.</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> In milliseconds the maximum amount of time the process
is allowed to run. <strong>Default:</strong> <code>undefined</code>.</li>
<li><code>killSignal</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#Number_type" class="type"><integer></a> The signal value to be used when the spawned
process will be killed. <strong>Default:</strong> <code>'SIGTERM'</code>.</li>
<li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Largest amount of data in bytes allowed on stdout or
stderr. If exceeded, the child process is terminated and any output is
truncated. See caveat at <a href="#all_child_process_maxbuffer-and-unicode"><code>maxBuffer</code> and Unicode</a>.
<strong>Default:</strong> <code>1024 * 1024</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 used for all stdio inputs and outputs.
<strong>Default:</strong> <code>'buffer'</code>.</li>
<li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the subprocess console window that would
normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_buffer_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> The stdout from the command.</li>
</ul>
<p>The <code>child_process.execSync()</code> method is generally identical to
<a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a> with the exception that the method will not return
until the child process has fully closed. When a timeout has been encountered
and <code>killSignal</code> is sent, the method won't return until the process has
completely exited. If the child process intercepts and handles the <code>SIGTERM</code>
signal and doesn't exit, the parent process will wait until the child process
has exited.</p>
<p>If the process times out or has a non-zero exit code, this method will throw.
The <a href="#all_errors_class-error"><code>Error</code></a> object will contain the entire result from
<a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync()</code></a>.</p>
<p><strong>Never pass unsanitized user input to this function. Any input containing shell
metacharacters may be used to trigger arbitrary command execution.</strong></p>
<h4><code>child_process.spawnSync(command[, args][, options])</code><span><a class="mark" href="#all_child_process_child_processspawnsynccommand-args-options" id="all_child_process_child_processspawnsynccommand-args-options">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_spawnsync_command_args_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>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>input</code> option can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>input</code> option can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>shell</code> option is supported now.</p></td></tr>
<tr><td>v6.2.1, v4.5.0</td>
<td><p>The <code>encoding</code> option can now explicitly be set to <code>buffer</code>.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The command to run.</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments.</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>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> Current working directory of the child process.</li>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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> The value which will be passed
as stdin to the spawned process. If <code>stdio[0]</code> is set to <code>'pipe'</code>, Supplying
this value will override <code>stdio[0]</code>.</li>
<li><code>argv0</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Explicitly set the value of <code>argv[0]</code> sent to the child
process. This will be set to <code>command</code> if not specified.</li>
<li><code>stdio</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/Reference/Global_Objects/Array" class="type"><Array></a> Child's stdio configuration.
See <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s <a href="#all_child_process_optionsstdio"><code>stdio</code></a>. <strong>Default:</strong> <code>'pipe'</code>.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> In milliseconds the maximum amount of time the process
is allowed to run. <strong>Default:</strong> <code>undefined</code>.</li>
<li><code>killSignal</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#Number_type" class="type"><integer></a> The signal value to be used when the spawned
process will be killed. <strong>Default:</strong> <code>'SIGTERM'</code>.</li>
<li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Largest amount of data in bytes allowed on stdout or
stderr. If exceeded, the child process is terminated and any output is
truncated. See caveat at <a href="#all_child_process_maxbuffer-and-unicode"><code>maxBuffer</code> and Unicode</a>.
<strong>Default:</strong> <code>1024 * 1024</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 used for all stdio inputs and outputs.
<strong>Default:</strong> <code>'buffer'</code>.</li>
<li><code>shell</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#String_type" class="type"><string></a> If <code>true</code>, runs <code>command</code> inside of a shell. Uses
<code>'/bin/sh'</code> on Unix, and <code>process.env.ComSpec</code> on Windows. A different
shell can be specified as a string. See <a href="#all_child_process_shell-requirements">Shell requirements</a> and
<a href="#all_child_process_default-windows-shell">Default Windows shell</a>. <strong>Default:</strong> <code>false</code> (no shell).</li>
<li><code>windowsVerbatimArguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> No quoting or escaping of arguments is
done on Windows. Ignored on Unix. This is set to <code>true</code> automatically
when <code>shell</code> is specified and is CMD. <strong>Default:</strong> <code>false</code>.</li>
<li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the subprocess console window that would
normally be created on Windows systems. <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/Object" class="type"><Object></a>
<ul>
<li><code>pid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Pid of the child process.</li>
<li><code>output</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Array of results from stdio output.</li>
<li><code>stdout</code> <a href="#all_buffer_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> The contents of <code>output[1]</code>.</li>
<li><code>stderr</code> <a href="#all_buffer_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> The contents of <code>output[2]</code>.</li>
<li><code>status</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The exit code of the subprocess, or <code>null</code> if the
subprocess terminated due to a signal.</li>
<li><code>signal</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 signal used to kill the subprocess, or <code>null</code> if
the subprocess did not terminate due to a signal.</li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The error object if the child process failed or timed out.</li>
</ul>
</li>
</ul>
<p>The <code>child_process.spawnSync()</code> method is generally identical to
<a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> with the exception that the function will not return
until the child process has fully closed. When a timeout has been encountered
and <code>killSignal</code> is sent, the method won't return until the process has
completely exited. If the process intercepts and handles the <code>SIGTERM</code> signal
and doesn't exit, the parent process will wait until the child process has
exited.</p>
<p><strong>If the <code>shell</code> option is enabled, do not pass unsanitized user input to this
function. Any input containing shell metacharacters may be used to trigger
arbitrary command execution.</strong></p>
</section><section><h3>Class: <code>ChildProcess</code><span><a class="mark" href="#all_child_process_class-childprocess" id="all_child_process_class-childprocess">#</a></span><a aria-hidden="true" class="legacy" id="child_process_class_childprocess"></a></h3>
<div class="api_metadata">
<span>Added in: v2.2.0</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>Instances of the <code>ChildProcess</code> represent spawned child processes.</p>
<p>Instances of <code>ChildProcess</code> are not intended to be created directly. Rather,
use the <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>, <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a>,
<a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile()</code></a>, or <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a> methods to create
instances of <code>ChildProcess</code>.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_child_process_event-close" id="all_child_process_event-close">#</a></span><a aria-hidden="true" class="legacy" id="child_process_event_close"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The exit code if the child process exited on its own.</li>
<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The signal by which the child process was terminated.</li>
</ul>
<p>The <code>'close'</code> event is emitted after a process has ended <em>and</em> the stdio
streams of a child process have been closed. This is distinct from the
<a href="#all_child_process_event-exit"><code>'exit'</code></a> event, since multiple processes might share the same stdio
streams. The <code>'close'</code> event will always emit after <a href="#all_child_process_event-exit"><code>'exit'</code></a> was
already emitted, or <a href="#all_child_process_event-error"><code>'error'</code></a> if the child process failed to spawn.</p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> ls = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, [<span class="hljs-string">'-lh'</span>, <span class="hljs-string">'/usr'</span>]);
ls.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${data}</span>`</span>);
});
ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process close all stdio with code <span class="hljs-subst">${code}</span>`</span>);
});
ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process exited with code <span class="hljs-subst">${code}</span>`</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> ls = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, [<span class="hljs-string">'-lh'</span>, <span class="hljs-string">'/usr'</span>]);
ls.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${data}</span>`</span>);
});
ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process close all stdio with code <span class="hljs-subst">${code}</span>`</span>);
});
ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process exited with code <span class="hljs-subst">${code}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'disconnect'</code><span><a class="mark" href="#all_child_process_event-disconnect" id="all_child_process_event-disconnect">#</a></span><a aria-hidden="true" class="legacy" id="child_process_event_disconnect"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.2</span>
</div>
<p>The <code>'disconnect'</code> event is emitted after calling the
<a href="#all_child_process_subprocessdisconnect"><code>subprocess.disconnect()</code></a> method in parent process or
<a href="#all_process_processdisconnect"><code>process.disconnect()</code></a> in child process. After disconnecting it is no longer
possible to send or receive messages, and the <a href="#all_child_process_subprocessconnected"><code>subprocess.connected</code></a>
property is <code>false</code>.</p>
<h4>Event: <code>'error'</code><span><a class="mark" href="#all_child_process_event-error" id="all_child_process_event-error">#</a></span><a aria-hidden="true" class="legacy" id="child_process_event_error"></a></h4>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The error.</li>
</ul>
<p>The <code>'error'</code> event is emitted whenever:</p>
<ul>
<li>The process could not be spawned.</li>
<li>The process could not be killed.</li>
<li>Sending a message to the child process failed.</li>
<li>The child process was aborted via the <code>signal</code> option.</li>
</ul>
<p>The <code>'exit'</code> event may or may not fire after an error has occurred. When
listening to both the <code>'exit'</code> and <code>'error'</code> events, guard
against accidentally invoking handler functions multiple times.</p>
<p>See also <a href="#all_child_process_subprocesskillsignal"><code>subprocess.kill()</code></a> and <a href="#all_child_process_subprocesssendmessage-sendhandle-options-callback"><code>subprocess.send()</code></a>.</p>
<h4>Event: <code>'exit'</code><span><a class="mark" href="#all_child_process_event-exit" id="all_child_process_event-exit">#</a></span><a aria-hidden="true" class="legacy" id="child_process_event_exit"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The exit code if the child process exited on its own.</li>
<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The signal by which the child process was terminated.</li>
</ul>
<p>The <code>'exit'</code> event is emitted after the child process ends. If the process
exited, <code>code</code> is the final exit code of the process, otherwise <code>null</code>. If the
process terminated due to receipt of a signal, <code>signal</code> is the string name of
the signal, otherwise <code>null</code>. One of the two will always be non-<code>null</code>.</p>
<p>When the <code>'exit'</code> event is triggered, child process stdio streams might still be
open.</p>
<p>Node.js establishes signal handlers for <code>SIGINT</code> and <code>SIGTERM</code> and Node.js
processes will not terminate immediately due to receipt of those signals.
Rather, Node.js will perform a sequence of cleanup actions and then will
re-raise the handled signal.</p>
<p>See <a href="http://man7.org/linux/man-pages/man2/waitpid.2.html"><code>waitpid(2)</code></a>.</p>
<h4>Event: <code>'message'</code><span><a class="mark" href="#all_child_process_event-message" id="all_child_process_event-message">#</a></span><a aria-hidden="true" class="legacy" id="child_process_event_message"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A parsed JSON object or primitive value.</li>
<li><code>sendHandle</code> <a href="#all_net_serverlistenhandle-backlog-callback" class="type"><Handle></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> <code>undefined</code> or a <a href="#all_net_class-netsocket"><code>net.Socket</code></a>,
<a href="#all_net_class-netserver"><code>net.Server</code></a>, or <a href="#all_dgram_class-dgramsocket"><code>dgram.Socket</code></a> object.</li>
</ul>
<p>The <code>'message'</code> event is triggered when a child process uses
<a href="#all_process_processsendmessage-sendhandle-options-callback"><code>process.send()</code></a> to send messages.</p>
<p>The message goes through serialization and parsing. The resulting
message might not be the same as what is originally sent.</p>
<p>If the <code>serialization</code> option was set to <code>'advanced'</code> used when spawning the
child process, the <code>message</code> argument can contain data that JSON is not able
to represent.
See <a href="#all_child_process_advanced-serialization">Advanced serialization</a> for more details.</p>
<h4>Event: <code>'spawn'</code><span><a class="mark" href="#all_child_process_event-spawn" id="all_child_process_event-spawn">#</a></span><a aria-hidden="true" class="legacy" id="child_process_event_spawn"></a></h4>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<p>The <code>'spawn'</code> event is emitted once the child process has spawned successfully.
If the child process does not spawn successfully, the <code>'spawn'</code> event is not
emitted and the <code>'error'</code> event is emitted instead.</p>
<p>If emitted, the <code>'spawn'</code> event comes before all other events and before any
data is received via <code>stdout</code> or <code>stderr</code>.</p>
<p>The <code>'spawn'</code> event will fire regardless of whether an error occurs <strong>within</strong>
the spawned process. For example, if <code>bash some-command</code> spawns successfully,
the <code>'spawn'</code> event will fire, though <code>bash</code> may fail to spawn <code>some-command</code>.
This caveat also applies when using <code>{ shell: true }</code>.</p>
<h4><code>subprocess.channel</code><span><a class="mark" href="#all_child_process_subprocesschannel" id="all_child_process_subprocesschannel">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_channel"></a></h4>
<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>The object no longer accidentally exposes native C++ bindings.</p></td></tr>
<tr><td>v7.1.0</td>
<td><p><span>Added in: v7.1.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A pipe representing the IPC channel to the child process.</li>
</ul>
<p>The <code>subprocess.channel</code> property is a reference to the child's IPC channel. If
no IPC channel exists, this property is <code>undefined</code>.</p>
<h5><code>subprocess.channel.ref()</code><span><a class="mark" href="#all_child_process_subprocesschannelref" id="all_child_process_subprocesschannelref">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_channel_ref"></a></h5>
<div class="api_metadata">
<span>Added in: v7.1.0</span>
</div>
<p>This method makes the IPC channel keep the event loop of the parent process
running if <code>.unref()</code> has been called before.</p>
<h5><code>subprocess.channel.unref()</code><span><a class="mark" href="#all_child_process_subprocesschannelunref" id="all_child_process_subprocesschannelunref">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_channel_unref"></a></h5>
<div class="api_metadata">
<span>Added in: v7.1.0</span>
</div>
<p>This method makes the IPC channel not keep the event loop of the parent process
running, and lets it finish even while the channel is open.</p>
<h4><code>subprocess.connected</code><span><a class="mark" href="#all_child_process_subprocessconnected" id="all_child_process_subprocessconnected">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_connected"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.2</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Set to <code>false</code> after <code>subprocess.disconnect()</code> is called.</li>
</ul>
<p>The <code>subprocess.connected</code> property indicates whether it is still possible to
send and receive messages from a child process. When <code>subprocess.connected</code> is
<code>false</code>, it is no longer possible to send or receive messages.</p>
<h4><code>subprocess.disconnect()</code><span><a class="mark" href="#all_child_process_subprocessdisconnect" id="all_child_process_subprocessdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_disconnect"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.2</span>
</div>
<p>Closes the IPC channel between parent and child processes, allowing the child
process to exit gracefully once there are no other connections keeping it alive.
After calling this method the <code>subprocess.connected</code> and
<code>process.connected</code> properties in both the parent and child processes
(respectively) will be set to <code>false</code>, and it will be no longer possible
to pass messages between the processes.</p>
<p>The <code>'disconnect'</code> event will be emitted when there are no messages in the
process of being received. This will most often be triggered immediately after
calling <code>subprocess.disconnect()</code>.</p>
<p>When the child process is a Node.js instance (e.g. spawned using
<a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>), the <code>process.disconnect()</code> method can be invoked
within the child process to close the IPC channel as well.</p>
<h4><code>subprocess.exitCode</code><span><a class="mark" href="#all_child_process_subprocessexitcode" id="all_child_process_subprocessexitcode">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_exitcode"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>The <code>subprocess.exitCode</code> property indicates the exit code of the child process.
If the child process is still running, the field will be <code>null</code>.</p>
<h4><code>subprocess.kill([signal])</code><span><a class="mark" href="#all_child_process_subprocesskillsignal" id="all_child_process_subprocesskillsignal">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_kill_signal"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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>The <code>subprocess.kill()</code> method sends a signal to the child process. If no
argument is given, the process will be sent the <code>'SIGTERM'</code> signal. See
<a href="http://man7.org/linux/man-pages/man7/signal.7.html"><code>signal(7)</code></a> for a list of available signals. This function returns <code>true</code> if
<a href="http://man7.org/linux/man-pages/man2/kill.2.html"><code>kill(2)</code></a> succeeds, and <code>false</code> otherwise.</p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>]);
grep.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code, signal</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
<span class="hljs-string">`child process terminated due to receipt of signal <span class="hljs-subst">${signal}</span>`</span>);
});
<span class="hljs-comment">// Send SIGHUP to process.</span>
grep.<span class="hljs-title function_">kill</span>(<span class="hljs-string">'SIGHUP'</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>]);
grep.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code, signal</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
<span class="hljs-string">`child process terminated due to receipt of signal <span class="hljs-subst">${signal}</span>`</span>);
});
<span class="hljs-comment">// Send SIGHUP to process.</span>
grep.<span class="hljs-title function_">kill</span>(<span class="hljs-string">'SIGHUP'</span>);</code><button class="copy-button">copy</button></pre>
<p>The <a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> object may emit an <a href="#all_child_process_event-error"><code>'error'</code></a> event if the signal
cannot be delivered. Sending a signal to a child process that has already exited
is not an error but may have unforeseen consequences. Specifically, if the
process identifier (PID) has been reassigned to another process, the signal will
be delivered to that process instead which can have unexpected results.</p>
<p>While the function is called <code>kill</code>, the signal delivered to the child process
may not actually terminate the process.</p>
<p>See <a href="http://man7.org/linux/man-pages/man2/kill.2.html"><code>kill(2)</code></a> for reference.</p>
<p>On Windows, where POSIX signals do not exist, the <code>signal</code> argument will be
ignored except for <code>'SIGKILL'</code>, <code>'SIGTERM'</code>, <code>'SIGINT'</code> and <code>'SIGQUIT'</code>, and the
process will always be killed forcefully and abruptly (similar to <code>'SIGKILL'</code>).
See <a href="#all_process_signal-events">Signal Events</a> for more details.</p>
<p>On Linux, child processes of child processes will not be terminated
when attempting to kill their parent. This is likely to happen when running a
new process in a shell or with the use of the <code>shell</code> option of <code>ChildProcess</code>:</p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(
<span class="hljs-string">'sh'</span>,
[
<span class="hljs-string">'-c'</span>,
<span class="hljs-string">`node -e "setInterval(() => {
console.log(process.pid, 'is alive')
}, 500);"`</span>,
], {
<span class="hljs-attr">stdio</span>: [<span class="hljs-string">'inherit'</span>, <span class="hljs-string">'inherit'</span>, <span class="hljs-string">'inherit'</span>],
},
);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
subprocess.<span class="hljs-title function_">kill</span>(); <span class="hljs-comment">// Does not terminate the Node.js process in the shell.</span>
}, <span class="hljs-number">2000</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(
<span class="hljs-string">'sh'</span>,
[
<span class="hljs-string">'-c'</span>,
<span class="hljs-string">`node -e "setInterval(() => {
console.log(process.pid, 'is alive')
}, 500);"`</span>,
], {
<span class="hljs-attr">stdio</span>: [<span class="hljs-string">'inherit'</span>, <span class="hljs-string">'inherit'</span>, <span class="hljs-string">'inherit'</span>],
},
);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
subprocess.<span class="hljs-title function_">kill</span>(); <span class="hljs-comment">// Does not terminate the Node.js process in the shell.</span>
}, <span class="hljs-number">2000</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>subprocess[Symbol.dispose]()</code><span><a class="mark" href="#all_child_process_subprocesssymboldispose" id="all_child_process_subprocesssymboldispose">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_symbol_dispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_child_process_subprocesskillsignal"><code>subprocess.kill()</code></a> with <code>'SIGTERM'</code>.</p>
<h4><code>subprocess.killed</code><span><a class="mark" href="#all_child_process_subprocesskilled" id="all_child_process_subprocesskilled">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_killed"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.10</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Set to <code>true</code> after <code>subprocess.kill()</code> is used to successfully
send a signal to the child process.</li>
</ul>
<p>The <code>subprocess.killed</code> property indicates whether the child process
successfully received a signal from <code>subprocess.kill()</code>. The <code>killed</code> property
does not indicate that the child process has been terminated.</p>
<h4><code>subprocess.pid</code><span><a class="mark" href="#all_child_process_subprocesspid" id="all_child_process_subprocesspid">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_pid"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>Returns the process identifier (PID) of the child process. If the child process
fails to spawn due to errors, then the value is <code>undefined</code> and <code>error</code> is
emitted.</p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Spawned child pid: <span class="hljs-subst">${grep.pid}</span>`</span>);
grep.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">end</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Spawned child pid: <span class="hljs-subst">${grep.pid}</span>`</span>);
grep.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>subprocess.ref()</code><span><a class="mark" href="#all_child_process_subprocessref" id="all_child_process_subprocessref">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.10</span>
</div>
<p>Calling <code>subprocess.ref()</code> after making a call to <code>subprocess.unref()</code> will
restore the removed reference count for the child process, forcing the parent
process to wait for the child process to exit before exiting itself.</p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(process.<span class="hljs-property">argv</span>[<span class="hljs-number">0</span>], [<span class="hljs-string">'child_program.js'</span>], {
<span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">stdio</span>: <span class="hljs-string">'ignore'</span>,
});
subprocess.<span class="hljs-title function_">unref</span>();
subprocess.<span class="hljs-title function_">ref</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(process.<span class="hljs-property">argv</span>[<span class="hljs-number">0</span>], [<span class="hljs-string">'child_program.js'</span>], {
<span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">stdio</span>: <span class="hljs-string">'ignore'</span>,
});
subprocess.<span class="hljs-title function_">unref</span>();
subprocess.<span class="hljs-title function_">ref</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>subprocess.send(message[, sendHandle[, options]][, callback])</code><span><a class="mark" href="#all_child_process_subprocesssendmessage-sendhandle-options-callback" id="all_child_process_subprocesssendmessage-sendhandle-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_send_message_sendhandle_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>v5.8.0</td>
<td><p>The <code>options</code> parameter, and the <code>keepOpen</code> option in particular, is supported now.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>This method returns a boolean for flow control now.</p></td></tr>
<tr><td>v4.0.0</td>
<td><p>The <code>callback</code> parameter is supported now.</p></td></tr>
<tr><td>v0.5.9</td>
<td><p><span>Added in: v0.5.9</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>sendHandle</code> <a href="#all_net_serverlistenhandle-backlog-callback" class="type"><Handle></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> <code>undefined</code>, or a <a href="#all_net_class-netsocket"><code>net.Socket</code></a>,
<a href="#all_net_class-netserver"><code>net.Server</code></a>, or <a href="#all_dgram_class-dgramsocket"><code>dgram.Socket</code></a> object.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <code>options</code> argument, if present, is an object used to
parameterize the sending of certain types of handles. <code>options</code> supports
the following properties:
<ul>
<li><code>keepOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> A value that can be used when passing instances of
<code>net.Socket</code>. When <code>true</code>, the socket is kept open in the sending process.
<strong>Default:</strong> <code>false</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></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>When an IPC channel has been established between the parent and child processes
( i.e. when using <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>), the <code>subprocess.send()</code> method
can be used to send messages to the child process. When the child process is a
Node.js instance, these messages can be received via the <a href="#all_process_event-message"><code>'message'</code></a> event.</p>
<p>The message goes through serialization and parsing. The resulting
message might not be the same as what is originally sent.</p>
<p>For example, in the parent script:</p>
<pre class="with-60-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> { fork } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> forkedProcess = <span class="hljs-title function_">fork</span>(<span class="hljs-string">`<span class="hljs-subst">${__dirname}</span>/sub.js`</span>);
forkedProcess.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'PARENT got message:'</span>, message);
});
<span class="hljs-comment">// Causes the child to print: CHILD got message: { hello: 'world' }</span>
forkedProcess.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { fork } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> forkedProcess = <span class="hljs-title function_">fork</span>(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-keyword">import</span>.meta.dirname}</span>/sub.js`</span>);
forkedProcess.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'PARENT got message:'</span>, message);
});
<span class="hljs-comment">// Causes the child to print: CHILD got message: { hello: 'world' }</span>
forkedProcess.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });</code><button class="copy-button">copy</button></pre>
<p>And then the child script, <code>'sub.js'</code> might look like this:</p>
<pre><code class="language-js">process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'CHILD got message:'</span>, message);
});
<span class="hljs-comment">// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }</span>
process.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span>, <span class="hljs-attr">baz</span>: <span class="hljs-title class_">NaN</span> });</code> <button class="copy-button">copy</button></pre>
<p>Child Node.js processes will have a <a href="#all_process_processsendmessage-sendhandle-options-callback"><code>process.send()</code></a> method of their own
that allows the child process to send messages back to the parent process.</p>
<p>There is a special case when sending a <code>{cmd: 'NODE_foo'}</code> message. Messages
containing a <code>NODE_</code> prefix in the <code>cmd</code> property are reserved for use within
Node.js core and will not be emitted in the child's <a href="#all_process_event-message"><code>'message'</code></a>
event. Rather, such messages are emitted using the
<code>'internalMessage'</code> event and are consumed internally by Node.js.
Applications should avoid using such messages or listening for
<code>'internalMessage'</code> events as it is subject to change without notice.</p>
<p>The optional <code>sendHandle</code> argument that may be passed to <code>subprocess.send()</code> is
for passing a TCP server or socket object to the child process. The child process will
receive the object as the second argument passed to the callback function
registered on the <a href="#all_process_event-message"><code>'message'</code></a> event. Any data that is received
and buffered in the socket will not be sent to the child. Sending IPC sockets is
not supported on Windows.</p>
<p>The optional <code>callback</code> is a function that is invoked after the message is
sent but before the child process may have received it. The function is called with a
single argument: <code>null</code> on success, or an <a href="#all_errors_class-error"><code>Error</code></a> object on failure.</p>
<p>If no <code>callback</code> function is provided and the message cannot be sent, an
<code>'error'</code> event will be emitted by the <a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> object. This can
happen, for instance, when the child process has already exited.</p>
<p><code>subprocess.send()</code> will return <code>false</code> if the channel has closed or when the
backlog of unsent messages exceeds a threshold that makes it unwise to send
more. Otherwise, the method returns <code>true</code>. The <code>callback</code> function can be
used to implement flow control.</p>
<h5>Example: sending a server object<span><a class="mark" href="#all_child_process_example-sending-a-server-object" id="all_child_process_example-sending-a-server-object">#</a></span><a aria-hidden="true" class="legacy" id="child_process_example_sending_a_server_object"></a></h5>
<p>The <code>sendHandle</code> argument can be used, for instance, to pass the handle of
a TCP server object to the child process as illustrated in the example below:</p>
<pre class="with-47-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> { fork } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> { createServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">fork</span>(<span class="hljs-string">'subprocess.js'</span>);
<span class="hljs-comment">// Open up the server object and send the handle.</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'handled by parent'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-function">() =></span> {
subprocess.<span class="hljs-title function_">send</span>(<span class="hljs-string">'server'</span>, server);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { fork } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">fork</span>(<span class="hljs-string">'subprocess.js'</span>);
<span class="hljs-comment">// Open up the server object and send the handle.</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'handled by parent'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-function">() =></span> {
subprocess.<span class="hljs-title function_">send</span>(<span class="hljs-string">'server'</span>, server);
});</code><button class="copy-button">copy</button></pre>
<p>The child process would then receive the server object as:</p>
<pre><code class="language-js">process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">m, server</span>) =></span> {
<span class="hljs-keyword">if</span> (m === <span class="hljs-string">'server'</span>) {
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'handled by child'</span>);
});
}
});</code> <button class="copy-button">copy</button></pre>
<p>Once the server is now shared between the parent and child, some connections
can be handled by the parent and some by the child.</p>
<p>While the example above uses a server created using the <code>node:net</code> module,
<code>node:dgram</code> module servers use exactly the same workflow with the exceptions of
listening on a <code>'message'</code> event instead of <code>'connection'</code> and using
<code>server.bind()</code> instead of <code>server.listen()</code>. This is, however, only
supported on Unix platforms.</p>
<h5>Example: sending a socket object<span><a class="mark" href="#all_child_process_example-sending-a-socket-object" id="all_child_process_example-sending-a-socket-object">#</a></span><a aria-hidden="true" class="legacy" id="child_process_example_sending_a_socket_object"></a></h5>
<p>Similarly, the <code>sendHandler</code> argument can be used to pass the handle of a
socket to the child process. The example below spawns two children that each
handle connections with "normal" or "special" priority:</p>
<pre class="with-47-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> { fork } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> { createServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> normal = <span class="hljs-title function_">fork</span>(<span class="hljs-string">'subprocess.js'</span>, [<span class="hljs-string">'normal'</span>]);
<span class="hljs-keyword">const</span> special = <span class="hljs-title function_">fork</span>(<span class="hljs-string">'subprocess.js'</span>, [<span class="hljs-string">'special'</span>]);
<span class="hljs-comment">// Open up the server and send sockets to child. Use pauseOnConnect to prevent</span>
<span class="hljs-comment">// the sockets from being read before they are sent to the child process.</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>({ <span class="hljs-attr">pauseOnConnect</span>: <span class="hljs-literal">true</span> });
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
<span class="hljs-comment">// If this is special priority...</span>
<span class="hljs-keyword">if</span> (socket.<span class="hljs-property">remoteAddress</span> === <span class="hljs-string">'74.125.127.100'</span>) {
special.<span class="hljs-title function_">send</span>(<span class="hljs-string">'socket'</span>, socket);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-comment">// This is normal priority.</span>
normal.<span class="hljs-title function_">send</span>(<span class="hljs-string">'socket'</span>, socket);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { fork } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">const</span> normal = <span class="hljs-title function_">fork</span>(<span class="hljs-string">'subprocess.js'</span>, [<span class="hljs-string">'normal'</span>]);
<span class="hljs-keyword">const</span> special = <span class="hljs-title function_">fork</span>(<span class="hljs-string">'subprocess.js'</span>, [<span class="hljs-string">'special'</span>]);
<span class="hljs-comment">// Open up the server and send sockets to child. Use pauseOnConnect to prevent</span>
<span class="hljs-comment">// the sockets from being read before they are sent to the child process.</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>({ <span class="hljs-attr">pauseOnConnect</span>: <span class="hljs-literal">true</span> });
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
<span class="hljs-comment">// If this is special priority...</span>
<span class="hljs-keyword">if</span> (socket.<span class="hljs-property">remoteAddress</span> === <span class="hljs-string">'74.125.127.100'</span>) {
special.<span class="hljs-title function_">send</span>(<span class="hljs-string">'socket'</span>, socket);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-comment">// This is normal priority.</span>
normal.<span class="hljs-title function_">send</span>(<span class="hljs-string">'socket'</span>, socket);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code><button class="copy-button">copy</button></pre>
<p>The <code>subprocess.js</code> would receive the socket handle as the second argument
passed to the event callback function:</p>
<pre><code class="language-js">process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">m, socket</span>) =></span> {
<span class="hljs-keyword">if</span> (m === <span class="hljs-string">'socket'</span>) {
<span class="hljs-keyword">if</span> (socket) {
<span class="hljs-comment">// Check that the client socket exists.</span>
<span class="hljs-comment">// It is possible for the socket to be closed between the time it is</span>
<span class="hljs-comment">// sent and the time it is received in the child process.</span>
socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Request handled with <span class="hljs-subst">${process.argv[<span class="hljs-number">2</span>]}</span> priority`</span>);
}
}
});</code> <button class="copy-button">copy</button></pre>
<p>Do not use <code>.maxConnections</code> on a socket that has been passed to a subprocess.
The parent cannot track when the socket is destroyed.</p>
<p>Any <code>'message'</code> handlers in the subprocess should verify that <code>socket</code> exists,
as the connection may have been closed during the time it takes to send the
connection to the child.</p>
<h4><code>subprocess.signalCode</code><span><a class="mark" href="#all_child_process_subprocesssignalcode" id="all_child_process_subprocesssignalcode">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_signalcode"></a></h4>
<ul>
<li><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></li>
</ul>
<p>The <code>subprocess.signalCode</code> property indicates the signal received by
the child process if any, else <code>null</code>.</p>
<h4><code>subprocess.spawnargs</code><span><a class="mark" href="#all_child_process_subprocessspawnargs" id="all_child_process_subprocessspawnargs">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_spawnargs"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>The <code>subprocess.spawnargs</code> property represents the full list of command-line
arguments the child process was launched with.</p>
<h4><code>subprocess.spawnfile</code><span><a class="mark" href="#all_child_process_subprocessspawnfile" id="all_child_process_subprocessspawnfile">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_spawnfile"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>subprocess.spawnfile</code> property indicates the executable file name of
the child process that is launched.</p>
<p>For <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>, its value will be equal to
<a href="#all_process_processexecpath"><code>process.execPath</code></a>.
For <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>, its value will be the name of
the executable file.
For <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a>, its value will be the name of the shell
in which the child process is launched.</p>
<h4><code>subprocess.stderr</code><span><a class="mark" href="#all_child_process_subprocessstderr" id="all_child_process_subprocessstderr">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_stderr"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#all_stream_class-streamreadable" class="type"><stream.Readable></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#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>A <code>Readable Stream</code> that represents the child process's <code>stderr</code>.</p>
<p>If the child process was spawned with <code>stdio[2]</code> set to anything other than <code>'pipe'</code>,
then this will be <code>null</code>.</p>
<p><code>subprocess.stderr</code> is an alias for <code>subprocess.stdio[2]</code>. Both properties will
refer to the same value.</p>
<p>The <code>subprocess.stderr</code> property can be <code>null</code> or <code>undefined</code>
if the child process could not be successfully spawned.</p>
<h4><code>subprocess.stdin</code><span><a class="mark" href="#all_child_process_subprocessstdin" id="all_child_process_subprocessstdin">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_stdin"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#all_stream_class-streamwritable" class="type"><stream.Writable></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#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>A <code>Writable Stream</code> that represents the child process's <code>stdin</code>.</p>
<p>If a child process waits to read all of its input, the child process will not continue
until this stream has been closed via <code>end()</code>.</p>
<p>If the child process was spawned with <code>stdio[0]</code> set to anything other than <code>'pipe'</code>,
then this will be <code>null</code>.</p>
<p><code>subprocess.stdin</code> is an alias for <code>subprocess.stdio[0]</code>. Both properties will
refer to the same value.</p>
<p>The <code>subprocess.stdin</code> property can be <code>null</code> or <code>undefined</code>
if the child process could not be successfully spawned.</p>
<h4><code>subprocess.stdio</code><span><a class="mark" href="#all_child_process_subprocessstdio" id="all_child_process_subprocessstdio">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_stdio"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.10</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>A sparse array of pipes to the child process, corresponding with positions in
the <a href="#all_child_process_optionsstdio"><code>stdio</code></a> option passed to <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> that have been set
to the value <code>'pipe'</code>. <code>subprocess.stdio[0]</code>, <code>subprocess.stdio[1]</code>, and
<code>subprocess.stdio[2]</code> are also available as <code>subprocess.stdin</code>,
<code>subprocess.stdout</code>, and <code>subprocess.stderr</code>, respectively.</p>
<p>In the following example, only the child's fd <code>1</code> (stdout) is configured as a
pipe, so only the parent's <code>subprocess.stdio[1]</code> is a stream, all other values
in the array are <code>null</code>.</p>
<pre class="with-38-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> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</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> child_process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> subprocess = child_process.<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, {
<span class="hljs-attr">stdio</span>: [
<span class="hljs-number">0</span>, <span class="hljs-comment">// Use parent's stdin for child.</span>
<span class="hljs-string">'pipe'</span>, <span class="hljs-comment">// Pipe child's stdout to parent.</span>
fs.<span class="hljs-title function_">openSync</span>(<span class="hljs-string">'err.out'</span>, <span class="hljs-string">'w'</span>), <span class="hljs-comment">// Direct child's stderr to a file.</span>
],
});
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">0</span>], <span class="hljs-literal">null</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">0</span>], subprocess.<span class="hljs-property">stdin</span>);
<span class="hljs-title function_">assert</span>(subprocess.<span class="hljs-property">stdout</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">1</span>], subprocess.<span class="hljs-property">stdout</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">2</span>], <span class="hljs-literal">null</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">2</span>], subprocess.<span class="hljs-property">stderr</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</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">import</span> child_process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> subprocess = child_process.<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, {
<span class="hljs-attr">stdio</span>: [
<span class="hljs-number">0</span>, <span class="hljs-comment">// Use parent's stdin for child.</span>
<span class="hljs-string">'pipe'</span>, <span class="hljs-comment">// Pipe child's stdout to parent.</span>
fs.<span class="hljs-title function_">openSync</span>(<span class="hljs-string">'err.out'</span>, <span class="hljs-string">'w'</span>), <span class="hljs-comment">// Direct child's stderr to a file.</span>
],
});
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">0</span>], <span class="hljs-literal">null</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">0</span>], subprocess.<span class="hljs-property">stdin</span>);
<span class="hljs-title function_">assert</span>(subprocess.<span class="hljs-property">stdout</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">1</span>], subprocess.<span class="hljs-property">stdout</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">2</span>], <span class="hljs-literal">null</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">2</span>], subprocess.<span class="hljs-property">stderr</span>);</code><button class="copy-button">copy</button></pre>
<p>The <code>subprocess.stdio</code> property can be <code>undefined</code> if the child process could
not be successfully spawned.</p>
<h4><code>subprocess.stdout</code><span><a class="mark" href="#all_child_process_subprocessstdout" id="all_child_process_subprocessstdout">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_stdout"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#all_stream_class-streamreadable" class="type"><stream.Readable></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#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>A <code>Readable Stream</code> that represents the child process's <code>stdout</code>.</p>
<p>If the child process was spawned with <code>stdio[1]</code> set to anything other than <code>'pipe'</code>,
then this will be <code>null</code>.</p>
<p><code>subprocess.stdout</code> is an alias for <code>subprocess.stdio[1]</code>. Both properties will
refer to the same value.</p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>);
subprocess.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received chunk <span class="hljs-subst">${data}</span>`</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>);
subprocess.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received chunk <span class="hljs-subst">${data}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<p>The <code>subprocess.stdout</code> property can be <code>null</code> or <code>undefined</code>
if the child process could not be successfully spawned.</p>
<h4><code>subprocess.unref()</code><span><a class="mark" href="#all_child_process_subprocessunref" id="all_child_process_subprocessunref">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.10</span>
</div>
<p>By default, the parent process will wait for the detached child process to exit.
To prevent the parent process from waiting for a given <code>subprocess</code> to exit, use the
<code>subprocess.unref()</code> method. Doing so will cause the parent's event loop to not
include the child process in its reference count, allowing the parent to exit
independently of the child, unless there is an established IPC channel between
the child and the parent processes.</p>
<pre class="with-48-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> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(process.<span class="hljs-property">argv</span>[<span class="hljs-number">0</span>], [<span class="hljs-string">'child_program.js'</span>], {
<span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">stdio</span>: <span class="hljs-string">'ignore'</span>,
});
subprocess.<span class="hljs-title function_">unref</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(process.<span class="hljs-property">argv</span>[<span class="hljs-number">0</span>], [<span class="hljs-string">'child_program.js'</span>], {
<span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">stdio</span>: <span class="hljs-string">'ignore'</span>,
});
subprocess.<span class="hljs-title function_">unref</span>();</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>maxBuffer</code> and Unicode<span><a class="mark" href="#all_child_process_maxbuffer-and-unicode" id="all_child_process_maxbuffer-and-unicode">#</a></span><a aria-hidden="true" class="legacy" id="child_process_maxbuffer_and_unicode"></a></h3>
<p>The <code>maxBuffer</code> option specifies the largest number of bytes allowed on <code>stdout</code>
or <code>stderr</code>. If this value is exceeded, then the child process is terminated.
This impacts output that includes multibyte character encodings such as UTF-8 or
UTF-16. For instance, <code>console.log('中文测试')</code> will send 13 UTF-8 encoded bytes
to <code>stdout</code> although there are only 4 characters.</p>
</section><section><h3>Shell requirements<span><a class="mark" href="#all_child_process_shell-requirements" id="all_child_process_shell-requirements">#</a></span><a aria-hidden="true" class="legacy" id="child_process_shell_requirements"></a></h3>
<p>The shell should understand the <code>-c</code> switch. If the shell is <code>'cmd.exe'</code>, it
should understand the <code>/d /s /c</code> switches and command-line parsing should be
compatible.</p>
</section><section><h3>Default Windows shell<span><a class="mark" href="#all_child_process_default-windows-shell" id="all_child_process_default-windows-shell">#</a></span><a aria-hidden="true" class="legacy" id="child_process_default_windows_shell"></a></h3>
<p>Although Microsoft specifies <code>%COMSPEC%</code> must contain the path to
<code>'cmd.exe'</code> in the root environment, child processes are not always subject to
the same requirement. Thus, in <code>child_process</code> functions where a shell can be
spawned, <code>'cmd.exe'</code> is used as a fallback if <code>process.env.ComSpec</code> is
unavailable.</p>
</section><section><h3>Advanced serialization<span><a class="mark" href="#all_child_process_advanced-serialization" id="all_child_process_advanced-serialization">#</a></span><a aria-hidden="true" class="legacy" id="child_process_advanced_serialization"></a></h3>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>Child processes support a serialization mechanism for IPC that is based on the
<a href="#all_v8_serialization-api">serialization API of the <code>node:v8</code> module</a>, based on the
<a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>. This is generally more powerful and
supports more built-in JavaScript object types, such as <code>BigInt</code>, <code>Map</code>
and <code>Set</code>, <code>ArrayBuffer</code> and <code>TypedArray</code>, <code>Buffer</code>, <code>Error</code>, <code>RegExp</code> etc.</p>
<p>However, this format is not a full superset of JSON, and e.g. properties set on
objects of such built-in types will not be passed on through the serialization
step. Additionally, performance may not be equivalent to that of JSON, depending
on the structure of the passed data.
Therefore, this feature requires opting in by setting the
<code>serialization</code> option to <code>'advanced'</code> when calling <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>
or <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>.</p></section>
</section>
<section><h2>Cluster<span><a class="mark" href="#all_cluster_cluster" id="all_cluster_cluster">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/cluster.js">lib/cluster.js</a></p>
<p>Clusters of Node.js processes can be used to run multiple instances of Node.js
that can distribute workloads among their application threads. When process
isolation is not needed, use the <a href="worker_threads.html"><code>worker_threads</code></a> module instead, which
allows running multiple application threads within a single Node.js instance.</p>
<p>The cluster module allows easy creation of child processes that all share
server ports.</p>
<pre class="with-40-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> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
<span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { availableParallelism } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-title function_">availableParallelism</span>();
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Primary <span class="hljs-subst">${process.pid}</span> is running`</span>);
<span class="hljs-comment">// Fork workers.</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < numCPUs; i++) {
cluster.<span class="hljs-title function_">fork</span>();
}
cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker <span class="hljs-subst">${worker.process.pid}</span> died`</span>);
});
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Workers can share any TCP connection</span>
<span class="hljs-comment">// In this case it is an HTTP server</span>
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Worker <span class="hljs-subst">${process.pid}</span> started`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</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> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>).<span class="hljs-title function_">availableParallelism</span>();
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Primary <span class="hljs-subst">${process.pid}</span> is running`</span>);
<span class="hljs-comment">// Fork workers.</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < numCPUs; i++) {
cluster.<span class="hljs-title function_">fork</span>();
}
cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker <span class="hljs-subst">${worker.process.pid}</span> died`</span>);
});
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Workers can share any TCP connection</span>
<span class="hljs-comment">// In this case it is an HTTP server</span>
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Worker <span class="hljs-subst">${process.pid}</span> started`</span>);
}</code><button class="copy-button">copy</button></pre>
<p>Running Node.js will now share port 8000 between the workers:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node server.js</span>
Primary 3596 is running
Worker 4324 started
Worker 4520 started
Worker 6056 started
Worker 5644 started</code> <button class="copy-button">copy</button></pre>
<p>On Windows, it is not yet possible to set up a named pipe server in a worker.</p>
<section><h3>How it works<span><a class="mark" href="#all_cluster_how-it-works" id="all_cluster_how-it-works">#</a></span><a aria-hidden="true" class="legacy" id="cluster_how_it_works"></a></h3>
<p>The worker processes are spawned using the <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a> method,
so that they can communicate with the parent via IPC and pass server
handles back and forth.</p>
<p>The cluster module supports two methods of distributing incoming
connections.</p>
<p>The first one (and the default one on all platforms except Windows)
is the round-robin approach, where the primary process listens on a
port, accepts new connections and distributes them across the workers
in a round-robin fashion, with some built-in smarts to avoid
overloading a worker process.</p>
<p>The second approach is where the primary process creates the listen
socket and sends it to interested workers. The workers then accept
incoming connections directly.</p>
<p>The second approach should, in theory, give the best performance.
In practice however, distribution tends to be very unbalanced due
to operating system scheduler vagaries. Loads have been observed
where over 70% of all connections ended up in just two processes,
out of a total of eight.</p>
<p>Because <code>server.listen()</code> hands off most of the work to the primary
process, there are three cases where the behavior between a normal
Node.js process and a cluster worker differs:</p>
<ol>
<li><code>server.listen({fd: 7})</code> Because the message is passed to the primary,
file descriptor 7 <strong>in the parent</strong> will be listened on, and the
handle passed to the worker, rather than listening to the worker's
idea of what the number 7 file descriptor references.</li>
<li><code>server.listen(handle)</code> Listening on handles explicitly will cause
the worker to use the supplied handle, rather than talk to the primary
process.</li>
<li><code>server.listen(0)</code> Normally, this will cause servers to listen on a
random port. However, in a cluster, each worker will receive the
same "random" port each time they do <code>listen(0)</code>. In essence, the
port is random the first time, but predictable thereafter. To listen
on a unique port, generate a port number based on the cluster worker ID.</li>
</ol>
<p>Node.js does not provide routing logic. It is therefore important to design an
application such that it does not rely too heavily on in-memory data objects for
things like sessions and login.</p>
<p>Because workers are all separate processes, they can be killed or
re-spawned depending on a program's needs, without affecting other
workers. As long as there are some workers still alive, the server will
continue to accept connections. If no workers are alive, existing connections
will be dropped and new connections will be refused. Node.js does not
automatically manage the number of workers, however. It is the application's
responsibility to manage the worker pool based on its own needs.</p>
<p>Although a primary use case for the <code>node:cluster</code> module is networking, it can
also be used for other use cases requiring worker processes.</p>
</section><section><h3>Class: <code>Worker</code><span><a class="mark" href="#all_cluster_class-worker" id="all_cluster_class-worker">#</a></span><a aria-hidden="true" class="legacy" id="cluster_class_worker"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>A <code>Worker</code> object contains all public information and method about a worker.
In the primary it can be obtained using <code>cluster.workers</code>. In a worker
it can be obtained using <code>cluster.worker</code>.</p>
<h4>Event: <code>'disconnect'</code><span><a class="mark" href="#all_cluster_event-disconnect" id="all_cluster_event-disconnect">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_disconnect"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<p>Similar to the <code>cluster.on('disconnect')</code> event, but specific to this worker.</p>
<pre><code class="language-js">cluster.<span class="hljs-title function_">fork</span>().<span class="hljs-title function_">on</span>(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Worker has disconnected</span>
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'error'</code><span><a class="mark" href="#all_cluster_event-error" id="all_cluster_event-error">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_error"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.3</span>
</div>
<p>This event is the same as the one provided by <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>.</p>
<p>Within a worker, <code>process.on('error')</code> may also be used.</p>
<h4>Event: <code>'exit'</code><span><a class="mark" href="#all_cluster_event-exit" id="all_cluster_event-exit">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_exit"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The exit code, if it exited normally.</li>
<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the signal (e.g. <code>'SIGHUP'</code>) that caused
the process to be killed.</li>
</ul>
<p>Similar to the <code>cluster.on('exit')</code> event, but specific to this worker.</p>
<pre class="with-40-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> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>();
worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code, signal</span>) =></span> {
<span class="hljs-keyword">if</span> (signal) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker was killed by signal: <span class="hljs-subst">${signal}</span>`</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker exited with error code: <span class="hljs-subst">${code}</span>`</span>);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker success!'</span>);
}
});
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>();
worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code, signal</span>) =></span> {
<span class="hljs-keyword">if</span> (signal) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker was killed by signal: <span class="hljs-subst">${signal}</span>`</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker exited with error code: <span class="hljs-subst">${code}</span>`</span>);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker success!'</span>);
}
});
}</code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'listening'</code><span><a class="mark" href="#all_cluster_event-listening" id="all_cluster_event-listening">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_listening"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Similar to the <code>cluster.on('listening')</code> event, but specific to this worker.</p>
<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs">cluster.<span class="hljs-title function_">fork</span>().<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">address</span>) =></span> {
<span class="hljs-comment">// Worker is listening</span>
});</code><code class="language-js cjs">cluster.<span class="hljs-title function_">fork</span>().<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">address</span>) =></span> {
<span class="hljs-comment">// Worker is listening</span>
});</code><button class="copy-button">copy</button></pre>
<p>It is not emitted in the worker.</p>
<h4>Event: <code>'message'</code><span><a class="mark" href="#all_cluster_event-message" id="all_cluster_event-message">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_message"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>handle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Similar to the <code>'message'</code> event of <code>cluster</code>, but specific to this worker.</p>
<p>Within a worker, <code>process.on('message')</code> may also be used.</p>
<p>See <a href="#all_process_event-message"><code>process</code> event: <code>'message'</code></a>.</p>
<p>Here is an example using the message system. It keeps a count in the primary
process of the number of HTTP requests received by the workers:</p>
<pre class="with-40-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> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
<span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { availableParallelism } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-comment">// Keep track of http requests</span>
<span class="hljs-keyword">let</span> numReqs = <span class="hljs-number">0</span>;
<span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`numReqs = <span class="hljs-subst">${numReqs}</span>`</span>);
}, <span class="hljs-number">1000</span>);
<span class="hljs-comment">// Count requests</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">messageHandler</span>(<span class="hljs-params">msg</span>) {
<span class="hljs-keyword">if</span> (msg.<span class="hljs-property">cmd</span> && msg.<span class="hljs-property">cmd</span> === <span class="hljs-string">'notifyRequest'</span>) {
numReqs += <span class="hljs-number">1</span>;
}
}
<span class="hljs-comment">// Start workers and listen for messages containing notifyRequest</span>
<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-title function_">availableParallelism</span>();
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < numCPUs; i++) {
cluster.<span class="hljs-title function_">fork</span>();
}
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> id <span class="hljs-keyword">in</span> cluster.<span class="hljs-property">workers</span>) {
cluster.<span class="hljs-property">workers</span>[id].<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, messageHandler);
}
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Worker processes have a http server.</span>
http.<span class="hljs-title class_">Server</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
<span class="hljs-comment">// Notify primary about the request</span>
process.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">cmd</span>: <span class="hljs-string">'notifyRequest'</span> });
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</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> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>).<span class="hljs-title function_">availableParallelism</span>();
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-comment">// Keep track of http requests</span>
<span class="hljs-keyword">let</span> numReqs = <span class="hljs-number">0</span>;
<span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`numReqs = <span class="hljs-subst">${numReqs}</span>`</span>);
}, <span class="hljs-number">1000</span>);
<span class="hljs-comment">// Count requests</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">messageHandler</span>(<span class="hljs-params">msg</span>) {
<span class="hljs-keyword">if</span> (msg.<span class="hljs-property">cmd</span> && msg.<span class="hljs-property">cmd</span> === <span class="hljs-string">'notifyRequest'</span>) {
numReqs += <span class="hljs-number">1</span>;
}
}
<span class="hljs-comment">// Start workers and listen for messages containing notifyRequest</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < numCPUs; i++) {
cluster.<span class="hljs-title function_">fork</span>();
}
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> id <span class="hljs-keyword">in</span> cluster.<span class="hljs-property">workers</span>) {
cluster.<span class="hljs-property">workers</span>[id].<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, messageHandler);
}
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Worker processes have a http server.</span>
http.<span class="hljs-title class_">Server</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
<span class="hljs-comment">// Notify primary about the request</span>
process.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">cmd</span>: <span class="hljs-string">'notifyRequest'</span> });
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
}</code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'online'</code><span><a class="mark" href="#all_cluster_event-online" id="all_cluster_event-online">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_online"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<p>Similar to the <code>cluster.on('online')</code> event, but specific to this worker.</p>
<pre><code class="language-js">cluster.<span class="hljs-title function_">fork</span>().<span class="hljs-title function_">on</span>(<span class="hljs-string">'online'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Worker is online</span>
});</code> <button class="copy-button">copy</button></pre>
<p>It is not emitted in the worker.</p>
<h4><code>worker.disconnect()</code><span><a class="mark" href="#all_cluster_workerdisconnect" id="all_cluster_workerdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_disconnect"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.3.0</td>
<td><p>This method now returns a reference to <code>worker</code>.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="#all_cluster_class-worker" class="type"><cluster.Worker></a> A reference to <code>worker</code>.</li>
</ul>
<p>In a worker, this function will close all servers, wait for the <code>'close'</code> event
on those servers, and then disconnect the IPC channel.</p>
<p>In the primary, an internal message is sent to the worker causing it to call
<code>.disconnect()</code> on itself.</p>
<p>Causes <code>.exitedAfterDisconnect</code> to be set.</p>
<p>After a server is closed, it will no longer accept new connections,
but connections may be accepted by any other listening worker. Existing
connections will be allowed to close as usual. When no more connections exist,
see <a href="#all_net_event-close"><code>server.close()</code></a>, the IPC channel to the worker will close allowing it
to die gracefully.</p>
<p>The above applies <em>only</em> to server connections, client connections are not
automatically closed by workers, and disconnect does not wait for them to close
before exiting.</p>
<p>In a worker, <code>process.disconnect</code> exists, but it is not this function;
it is <a href="#all_child_process_subprocessdisconnect"><code>disconnect()</code></a>.</p>
<p>Because long living server connections may block workers from disconnecting, it
may be useful to send a message, so application specific actions may be taken to
close them. It also may be useful to implement a timeout, killing a worker if
the <code>'disconnect'</code> event has not been emitted after some time.</p>
<pre><code class="language-js"><span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>();
<span class="hljs-keyword">let</span> timeout;
worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">address</span>) =></span> {
worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'shutdown'</span>);
worker.<span class="hljs-title function_">disconnect</span>();
timeout = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
worker.<span class="hljs-title function_">kill</span>();
}, <span class="hljs-number">2000</span>);
});
worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-built_in">clearTimeout</span>(timeout);
});
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) {
<span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
<span class="hljs-comment">// Connections never end</span>
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
<span class="hljs-keyword">if</span> (msg === <span class="hljs-string">'shutdown'</span>) {
<span class="hljs-comment">// Initiate graceful close of any connections to server</span>
}
});
}</code> <button class="copy-button">copy</button></pre>
<h4><code>worker.exitedAfterDisconnect</code><span><a class="mark" href="#all_cluster_workerexitedafterdisconnect" id="all_cluster_workerexitedafterdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_exitedafterdisconnect"></a></h4>
<div class="api_metadata">
<span>Added in: v6.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>This property is <code>true</code> if the worker exited due to <code>.disconnect()</code>.
If the worker exited any other way, it is <code>false</code>. If the
worker has not exited, it is <code>undefined</code>.</p>
<p>The boolean <a href="#all_cluster_workerexitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a> allows distinguishing between
voluntary and accidental exit, the primary may choose not to respawn a worker
based on this value.</p>
<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
<span class="hljs-keyword">if</span> (worker.<span class="hljs-property">exitedAfterDisconnect</span> === <span class="hljs-literal">true</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Oh, it was just voluntary – no need to worry'</span>);
}
});
<span class="hljs-comment">// kill worker</span>
worker.<span class="hljs-title function_">kill</span>();</code> <button class="copy-button">copy</button></pre>
<h4><code>worker.id</code><span><a class="mark" href="#all_cluster_workerid" id="all_cluster_workerid">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_id"></a></h4>
<div class="api_metadata">
<span>Added in: v0.8.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>Each new worker is given its own unique id, this id is stored in the
<code>id</code>.</p>
<p>While a worker is alive, this is the key that indexes it in
<code>cluster.workers</code>.</p>
<h4><code>worker.isConnected()</code><span><a class="mark" href="#all_cluster_workerisconnected" id="all_cluster_workerisconnected">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_isconnected"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<p>This function returns <code>true</code> if the worker is connected to its primary via its
IPC channel, <code>false</code> otherwise. A worker is connected to its primary after it
has been created. It is disconnected after the <code>'disconnect'</code> event is emitted.</p>
<h4><code>worker.isDead()</code><span><a class="mark" href="#all_cluster_workerisdead" id="all_cluster_workerisdead">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_isdead"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<p>This function returns <code>true</code> if the worker's process has terminated (either
because of exiting or being signaled). Otherwise, it returns <code>false</code>.</p>
<pre class="with-40-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> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
<span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { availableParallelism } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-title function_">availableParallelism</span>();
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Primary <span class="hljs-subst">${process.pid}</span> is running`</span>);
<span class="hljs-comment">// Fork workers.</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < numCPUs; i++) {
cluster.<span class="hljs-title function_">fork</span>();
}
cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'fork'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker is dead:'</span>, worker.<span class="hljs-title function_">isDead</span>());
});
cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker is dead:'</span>, worker.<span class="hljs-title function_">isDead</span>());
});
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Workers can share any TCP connection. In this case, it is an HTTP server.</span>
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Current process\n <span class="hljs-subst">${process.pid}</span>`</span>);
process.<span class="hljs-title function_">kill</span>(process.<span class="hljs-property">pid</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</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> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>).<span class="hljs-title function_">availableParallelism</span>();
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Primary <span class="hljs-subst">${process.pid}</span> is running`</span>);
<span class="hljs-comment">// Fork workers.</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < numCPUs; i++) {
cluster.<span class="hljs-title function_">fork</span>();
}
cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'fork'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker is dead:'</span>, worker.<span class="hljs-title function_">isDead</span>());
});
cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker is dead:'</span>, worker.<span class="hljs-title function_">isDead</span>());
});
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Workers can share any TCP connection. In this case, it is an HTTP server.</span>
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Current process\n <span class="hljs-subst">${process.pid}</span>`</span>);
process.<span class="hljs-title function_">kill</span>(process.<span class="hljs-property">pid</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
}</code><button class="copy-button">copy</button></pre>
<h4><code>worker.kill([signal])</code><span><a class="mark" href="#all_cluster_workerkillsignal" id="all_cluster_workerkillsignal">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_kill_signal"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.12</span>
</div>
<ul>
<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the kill signal to send to the worker
process. <strong>Default:</strong> <code>'SIGTERM'</code></li>
</ul>
<p>This function will kill the worker. In the primary worker, it does this by
disconnecting the <code>worker.process</code>, and once disconnected, killing with
<code>signal</code>. In the worker, it does it by killing the process with <code>signal</code>.</p>
<p>The <code>kill()</code> function kills the worker process without waiting for a graceful
disconnect, it has the same behavior as <code>worker.process.kill()</code>.</p>
<p>This method is aliased as <code>worker.destroy()</code> for backwards compatibility.</p>
<p>In a worker, <code>process.kill()</code> exists, but it is not this function;
it is <a href="#all_process_processkillpid-signal"><code>kill()</code></a>.</p>
<h4><code>worker.process</code><span><a class="mark" href="#all_cluster_workerprocess" id="all_cluster_workerprocess">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_process"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><a href="#all_child_process_class-childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>All workers are created using <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>, the returned object
from this function is stored as <code>.process</code>. In a worker, the global <code>process</code>
is stored.</p>
<p>See: <a href="#all_child_process_child_processforkmodulepath-args-options">Child Process module</a>.</p>
<p>Workers will call <code>process.exit(0)</code> if the <code>'disconnect'</code> event occurs
on <code>process</code> and <code>.exitedAfterDisconnect</code> is not <code>true</code>. This protects against
accidental disconnection.</p>
<h4><code>worker.send(message[, sendHandle[, options]][, callback])</code><span><a class="mark" href="#all_cluster_workersendmessage-sendhandle-options-callback" id="all_cluster_workersendmessage-sendhandle-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_send_message_sendhandle_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>v4.0.0</td>
<td><p>The <code>callback</code> parameter is supported now.</p></td></tr>
<tr><td>v0.7.0</td>
<td><p><span>Added in: v0.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>sendHandle</code> <a href="#all_net_serverlistenhandle-backlog-callback" class="type"><Handle></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> The <code>options</code> argument, if present, is an object used to
parameterize the sending of certain types of handles. <code>options</code> supports
the following properties:
<ul>
<li><code>keepOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> A value that can be used when passing instances of
<code>net.Socket</code>. When <code>true</code>, the socket is kept open in the sending process.
<strong>Default:</strong> <code>false</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></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>Send a message to a worker or primary, optionally with a handle.</p>
<p>In the primary, this sends a message to a specific worker. It is identical to
<a href="#all_child_process_subprocesssendmessage-sendhandle-options-callback"><code>ChildProcess.send()</code></a>.</p>
<p>In a worker, this sends a message to the primary. It is identical to
<code>process.send()</code>.</p>
<p>This example will echo back all messages from the primary:</p>
<pre><code class="language-js"><span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>();
worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'hi there'</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) {
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
process.<span class="hljs-title function_">send</span>(msg);
});
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Event: <code>'disconnect'</code><span><a class="mark" href="#all_cluster_event-disconnect_1" id="all_cluster_event-disconnect_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_disconnect_1"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.9</span>
</div>
<ul>
<li><code>worker</code> <a href="#all_cluster_class-worker" class="type"><cluster.Worker></a></li>
</ul>
<p>Emitted after the worker IPC channel has disconnected. This can occur when a
worker exits gracefully, is killed, or is disconnected manually (such as with
<code>worker.disconnect()</code>).</p>
<p>There may be a delay between the <code>'disconnect'</code> and <code>'exit'</code> events. These
events can be used to detect if the process is stuck in a cleanup or if there
are long-living connections.</p>
<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The worker #<span class="hljs-subst">${worker.id}</span> has disconnected`</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Event: <code>'exit'</code><span><a class="mark" href="#all_cluster_event-exit_1" id="all_cluster_event-exit_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_exit_1"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.9</span>
</div>
<ul>
<li><code>worker</code> <a href="#all_cluster_class-worker" class="type"><cluster.Worker></a></li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The exit code, if it exited normally.</li>
<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the signal (e.g. <code>'SIGHUP'</code>) that caused
the process to be killed.</li>
</ul>
<p>When any of the workers die the cluster module will emit the <code>'exit'</code> event.</p>
<p>This can be used to restart the worker by calling <a href="#all_cluster_clusterforkenv"><code>.fork()</code></a> again.</p>
<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker %d died (%s). restarting...'</span>,
worker.<span class="hljs-property">process</span>.<span class="hljs-property">pid</span>, signal || code);
cluster.<span class="hljs-title function_">fork</span>();
});</code> <button class="copy-button">copy</button></pre>
<p>See <a href="#all_child_process_event-exit"><code>child_process</code> event: <code>'exit'</code></a>.</p>
</section><section><h3>Event: <code>'fork'</code><span><a class="mark" href="#all_cluster_event-fork" id="all_cluster_event-fork">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_fork"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>worker</code> <a href="#all_cluster_class-worker" class="type"><cluster.Worker></a></li>
</ul>
<p>When a new worker is forked the cluster module will emit a <code>'fork'</code> event.
This can be used to log worker activity, and create a custom timeout.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> timeouts = [];
<span class="hljs-keyword">function</span> <span class="hljs-title function_">errorMsg</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Something must be wrong with the connection ...'</span>);
}
cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'fork'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
timeouts[worker.<span class="hljs-property">id</span>] = <span class="hljs-built_in">setTimeout</span>(errorMsg, <span class="hljs-number">2000</span>);
});
cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">worker, address</span>) =></span> {
<span class="hljs-built_in">clearTimeout</span>(timeouts[worker.<span class="hljs-property">id</span>]);
});
cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
<span class="hljs-built_in">clearTimeout</span>(timeouts[worker.<span class="hljs-property">id</span>]);
<span class="hljs-title function_">errorMsg</span>();
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Event: <code>'listening'</code><span><a class="mark" href="#all_cluster_event-listening_1" id="all_cluster_event-listening_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_listening_1"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>worker</code> <a href="#all_cluster_class-worker" class="type"><cluster.Worker></a></li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>After calling <code>listen()</code> from a worker, when the <code>'listening'</code> event is emitted
on the server, a <code>'listening'</code> event will also be emitted on <code>cluster</code> in the
primary.</p>
<p>The event handler is executed with two arguments, the <code>worker</code> contains the
worker object and the <code>address</code> object contains the following connection
properties: <code>address</code>, <code>port</code>, and <code>addressType</code>. This is very useful if the
worker is listening on more than one address.</p>
<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">worker, address</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
<span class="hljs-string">`A worker is now connected to <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>The <code>addressType</code> is one of:</p>
<ul>
<li><code>4</code> (TCPv4)</li>
<li><code>6</code> (TCPv6)</li>
<li><code>-1</code> (Unix domain socket)</li>
<li><code>'udp4'</code> or <code>'udp6'</code> (UDPv4 or UDPv6)</li>
</ul>
</section><section><h3>Event: <code>'message'</code><span><a class="mark" href="#all_cluster_event-message_1" id="all_cluster_event-message_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_message_1"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>worker</code> parameter is passed now; see below for details.</p></td></tr>
<tr><td>v2.5.0</td>
<td><p><span>Added in: v2.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>worker</code> <a href="#all_cluster_class-worker" class="type"><cluster.Worker></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>handle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Emitted when the cluster primary receives a message from any worker.</p>
<p>See <a href="#all_child_process_event-message"><code>child_process</code> event: <code>'message'</code></a>.</p>
</section><section><h3>Event: <code>'online'</code><span><a class="mark" href="#all_cluster_event-online_1" id="all_cluster_event-online_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_online_1"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>worker</code> <a href="#all_cluster_class-worker" class="type"><cluster.Worker></a></li>
</ul>
<p>After forking a new worker, the worker should respond with an online message.
When the primary receives an online message it will emit this event.
The difference between <code>'fork'</code> and <code>'online'</code> is that fork is emitted when the
primary forks a worker, and <code>'online'</code> is emitted when the worker is running.</p>
<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'online'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Yay, the worker responded after it was forked'</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Event: <code>'setup'</code><span><a class="mark" href="#all_cluster_event-setup" id="all_cluster_event-setup">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_setup"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.1</span>
</div>
<ul>
<li><code>settings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Emitted every time <a href="#all_cluster_clustersetupprimarysettings"><code>.setupPrimary()</code></a> is called.</p>
<p>The <code>settings</code> object is the <code>cluster.settings</code> object at the time
<a href="#all_cluster_clustersetupprimarysettings"><code>.setupPrimary()</code></a> was called and is advisory only, since multiple calls to
<a href="#all_cluster_clustersetupprimarysettings"><code>.setupPrimary()</code></a> can be made in a single tick.</p>
<p>If accuracy is important, use <code>cluster.settings</code>.</p>
</section><section><h3><code>cluster.disconnect([callback])</code><span><a class="mark" href="#all_cluster_clusterdisconnectcallback" id="all_cluster_clusterdisconnectcallback">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_disconnect_callback"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</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> Called when all workers are disconnected and handles are
closed.</li>
</ul>
<p>Calls <code>.disconnect()</code> on each worker in <code>cluster.workers</code>.</p>
<p>When they are disconnected all internal handles will be closed, allowing the
primary process to die gracefully if no other event is waiting.</p>
<p>The method takes an optional callback argument which will be called when
finished.</p>
<p>This can only be called from the primary process.</p>
</section><section><h3><code>cluster.fork([env])</code><span><a class="mark" href="#all_cluster_clusterforkenv" id="all_cluster_clusterforkenv">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_fork_env"></a></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
</div>
<ul>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Key/value pairs to add to worker process environment.</li>
<li>Returns: <a href="#all_cluster_class-worker" class="type"><cluster.Worker></a></li>
</ul>
<p>Spawn a new worker process.</p>
<p>This can only be called from the primary process.</p>
</section><section><h3><code>cluster.isMaster</code><span><a class="mark" href="#all_cluster_clusterismaster" id="all_cluster_clusterismaster">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_ismaster"></a></h3>
<div class="api_metadata">
<span>Added in: v0.8.1</span><span>Deprecated since: v16.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p>Deprecated alias for <a href="#all_cluster_clusterisprimary"><code>cluster.isPrimary</code></a>.</p>
</section><section><h3><code>cluster.isPrimary</code><span><a class="mark" href="#all_cluster_clusterisprimary" id="all_cluster_clusterisprimary">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_isprimary"></a></h3>
<div class="api_metadata">
<span>Added in: v16.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>True if the process is a primary. This is determined
by the <code>process.env.NODE_UNIQUE_ID</code>. If <code>process.env.NODE_UNIQUE_ID</code> is
undefined, then <code>isPrimary</code> is <code>true</code>.</p>
</section><section><h3><code>cluster.isWorker</code><span><a class="mark" href="#all_cluster_clusterisworker" id="all_cluster_clusterisworker">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_isworker"></a></h3>
<div class="api_metadata">
<span>Added in: v0.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>True if the process is not a primary (it is the negation of <code>cluster.isPrimary</code>).</p>
</section><section><h3><code>cluster.schedulingPolicy</code><span><a class="mark" href="#all_cluster_clusterschedulingpolicy" id="all_cluster_clusterschedulingpolicy">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_schedulingpolicy"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div>
<p>The scheduling policy, either <code>cluster.SCHED_RR</code> for round-robin or
<code>cluster.SCHED_NONE</code> to leave it to the operating system. This is a
global setting and effectively frozen once either the first worker is spawned,
or <a href="#all_cluster_clustersetupprimarysettings"><code>.setupPrimary()</code></a> is called, whichever comes first.</p>
<p><code>SCHED_RR</code> is the default on all operating systems except Windows.
Windows will change to <code>SCHED_RR</code> once libuv is able to effectively
distribute IOCP handles without incurring a large performance hit.</p>
<p><code>cluster.schedulingPolicy</code> can also be set through the
<code>NODE_CLUSTER_SCHED_POLICY</code> environment variable. Valid
values are <code>'rr'</code> and <code>'none'</code>.</p>
</section><section><h3><code>cluster.settings</code><span><a class="mark" href="#all_cluster_clustersettings" id="all_cluster_clustersettings">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_settings"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>The <code>serialization</code> option is supported now.</p></td></tr>
<tr><td>v9.5.0</td>
<td><p>The <code>cwd</code> option is supported now.</p></td></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v8.2.0</td>
<td><p>The <code>inspectPort</code> option is supported now.</p></td></tr>
<tr><td>v6.4.0</td>
<td><p>The <code>stdio</code> option is supported now.</p></td></tr>
<tr><td>v0.7.1</td>
<td><p><span>Added in: v0.7.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments passed to the Node.js
executable. <strong>Default:</strong> <code>process.execArgv</code>.</li>
<li><code>exec</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> File path to worker file. <strong>Default:</strong> <code>process.argv[1]</code>.</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> String arguments passed to worker.
<strong>Default:</strong> <code>process.argv.slice(2)</code>.</li>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Current working directory of the worker process. <strong>Default:</strong>
<code>undefined</code> (inherits from parent process).</li>
<li><code>serialization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specify the kind of serialization used for sending
messages between processes. Possible values are <code>'json'</code> and <code>'advanced'</code>.
See <a href="#all_child_process_advanced-serialization">Advanced serialization for <code>child_process</code></a> for more details.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>silent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not to send output to parent's stdio.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Configures the stdio of forked processes. Because the
cluster module relies on IPC to function, this configuration must contain an
<code>'ipc'</code> entry. When this option is provided, it overrides <code>silent</code>. See
<a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s <a href="#all_child_process_optionsstdio"><code>stdio</code></a>.</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>.)</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>.)</li>
<li><code>inspectPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Sets inspector port of worker.
This can be a number, or a function that takes no arguments and returns a
number. By default each worker gets its own port, incremented from the
primary's <code>process.debugPort</code>.</li>
<li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the forked processes console window that would
normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>After calling <a href="#all_cluster_clustersetupprimarysettings"><code>.setupPrimary()</code></a> (or <a href="#all_cluster_clusterforkenv"><code>.fork()</code></a>) this settings object will
contain the settings, including the default values.</p>
<p>This object is not intended to be changed or set manually.</p>
</section><section><h3><code>cluster.setupMaster([settings])</code><span><a class="mark" href="#all_cluster_clustersetupmastersettings" id="all_cluster_clustersetupmastersettings">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_setupmaster_settings"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p><span>Deprecated since: v16.0.0</span></p></td></tr>
<tr><td>v6.4.0</td>
<td><p>The <code>stdio</code> option is supported now.</p></td></tr>
<tr><td>v0.7.1</td>
<td><p><span>Added in: v0.7.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p>Deprecated alias for <a href="#all_cluster_clustersetupprimarysettings"><code>.setupPrimary()</code></a>.</p>
</section><section><h3><code>cluster.setupPrimary([settings])</code><span><a class="mark" href="#all_cluster_clustersetupprimarysettings" id="all_cluster_clustersetupprimarysettings">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_setupprimary_settings"></a></h3>
<div class="api_metadata">
<span>Added in: v16.0.0</span>
</div>
<ul>
<li><code>settings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See <a href="#all_cluster_clustersettings"><code>cluster.settings</code></a>.</li>
</ul>
<p><code>setupPrimary</code> is used to change the default 'fork' behavior. Once called,
the settings will be present in <code>cluster.settings</code>.</p>
<p>Any settings changes only affect future calls to <a href="#all_cluster_clusterforkenv"><code>.fork()</code></a> and have no
effect on workers that are already running.</p>
<p>The only attribute of a worker that cannot be set via <code>.setupPrimary()</code> is
the <code>env</code> passed to <a href="#all_cluster_clusterforkenv"><code>.fork()</code></a>.</p>
<p>The defaults above apply to the first call only; the defaults for later
calls are the current values at the time of <code>cluster.setupPrimary()</code> is called.</p>
<pre class="with-40-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> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
cluster.<span class="hljs-title function_">setupPrimary</span>({
<span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>,
<span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'https'</span>],
<span class="hljs-attr">silent</span>: <span class="hljs-literal">true</span>,
});
cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// https worker</span>
cluster.<span class="hljs-title function_">setupPrimary</span>({
<span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>,
<span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'http'</span>],
});
cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// http worker</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
cluster.<span class="hljs-title function_">setupPrimary</span>({
<span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>,
<span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'https'</span>],
<span class="hljs-attr">silent</span>: <span class="hljs-literal">true</span>,
});
cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// https worker</span>
cluster.<span class="hljs-title function_">setupPrimary</span>({
<span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>,
<span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'http'</span>],
});
cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// http worker</span></code><button class="copy-button">copy</button></pre>
<p>This can only be called from the primary process.</p>
</section><section><h3><code>cluster.worker</code><span><a class="mark" href="#all_cluster_clusterworker" id="all_cluster_clusterworker">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_worker"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>A reference to the current worker object. Not available in the primary process.</p>
<pre class="with-40-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> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'I am primary'</span>);
cluster.<span class="hljs-title function_">fork</span>();
cluster.<span class="hljs-title function_">fork</span>();
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`I am worker #<span class="hljs-subst">${cluster.worker.id}</span>`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'I am primary'</span>);
cluster.<span class="hljs-title function_">fork</span>();
cluster.<span class="hljs-title function_">fork</span>();
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`I am worker #<span class="hljs-subst">${cluster.worker.id}</span>`</span>);
}</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>cluster.workers</code><span><a class="mark" href="#all_cluster_clusterworkers" id="all_cluster_clusterworkers">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_workers"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>A hash that stores the active worker objects, keyed by <code>id</code> field. This makes it
easy to loop through all the workers. It is only available in the primary
process.</p>
<p>A worker is removed from <code>cluster.workers</code> after the worker has disconnected
<em>and</em> exited. The order between these two events cannot be determined in
advance. However, it is guaranteed that the removal from the <code>cluster.workers</code>
list happens before the last <code>'disconnect'</code> or <code>'exit'</code> event is emitted.</p>
<pre class="with-40-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> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">values</span>(cluster.<span class="hljs-property">workers</span>)) {
worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'big announcement to all workers'</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">values</span>(cluster.<span class="hljs-property">workers</span>)) {
worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'big announcement to all workers'</span>);
}</code><button class="copy-button">copy</button></pre></section>
</section>
<section><h2>Command-line API<span><a class="mark" href="#all_cli_command-line-api" id="all_cli_command-line-api">#</a></span><a aria-hidden="true" class="legacy" id="cli_command_line_api"></a></h2>
<p>Node.js comes with a variety of CLI options. These options expose built-in
debugging, multiple ways to execute scripts, and other helpful runtime options.</p>
<p>To view this documentation as a manual page in a terminal, run <code>man node</code>.</p>
<section><h3>Synopsis<span><a class="mark" href="#all_cli_synopsis" id="all_cli_synopsis">#</a></span><a aria-hidden="true" class="legacy" id="cli_synopsis"></a></h3>
<p><code>node [options] [V8 options] [<program-entry-point> | -e "script" | -] [--] [arguments]</code></p>
<p><code>node inspect [<program-entry-point> | -e "script" | <host>:<port>] …</code></p>
<p><code>node --v8-options</code></p>
<p>Execute without arguments to start the <a href="repl.html">REPL</a>.</p>
<p>For more info about <code>node inspect</code>, see the <a href="debugger.html">debugger</a> documentation.</p>
</section><section><h3>Program entry point<span><a class="mark" href="#all_cli_program-entry-point" id="all_cli_program-entry-point">#</a></span><a aria-hidden="true" class="legacy" id="cli_program_entry_point"></a></h3>
<p>The program entry point is a specifier-like string. If the string is not an
absolute path, it's resolved as a relative path from the current working
directory. That path is then resolved by <a href="modules.html">CommonJS</a> module loader, or by the
<a href="#all_packages_modules-loaders">ES module loader</a> if <a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type=module</code></a>
is passed. If no corresponding file is found, an error is thrown.</p>
<p>If a file is found, its path will be passed to the
<a href="#all_packages_modules-loaders">ES module loader</a> under any of the following conditions:</p>
<ul>
<li>The program was started with a command-line flag that forces the entry
point to be loaded with ECMAScript module loader, such as <code>--import</code> or
<a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type=module</code></a>.</li>
<li>The file has an <code>.mjs</code> extension.</li>
<li>The file does not have a <code>.cjs</code> extension, and the nearest parent
<code>package.json</code> file contains a top-level <a href="#all_packages_type"><code>"type"</code></a> field with a value of
<code>"module"</code>.</li>
</ul>
<p>Otherwise, the file is loaded using the CommonJS module loader. See
<a href="#all_packages_modules-loaders">Modules loaders</a> for more details.</p>
<h4>ECMAScript modules loader entry point caveat<span><a class="mark" href="#all_cli_ecmascript-modules-loader-entry-point-caveat" id="all_cli_ecmascript-modules-loader-entry-point-caveat">#</a></span><a aria-hidden="true" class="legacy" id="cli_ecmascript_modules_loader_entry_point_caveat"></a></h4>
<p>When loading, the <a href="#all_packages_modules-loaders">ES module loader</a> loads the program
entry point, the <code>node</code> command will accept as input only files with <code>.js</code>,
<code>.mjs</code>, or <code>.cjs</code> extensions; with <code>.wasm</code> extensions when
<a href="#all_cli_--experimental-wasm-modules"><code>--experimental-wasm-modules</code></a> is enabled; and with no extension when
<a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type=module</code></a> is passed.</p>
</section><section><h3>Options<span><a class="mark" href="#all_cli_options" id="all_cli_options">#</a></span><a aria-hidden="true" class="legacy" id="cli_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.12.0</td>
<td><p>Underscores instead of dashes are now allowed for Node.js options as well, in addition to V8 options.</p></td></tr>
</tbody></table>
</details>
</div>
<p>All options, including V8 options, allow words to be separated by both
dashes (<code>-</code>) or underscores (<code>_</code>). For example, <code>--pending-deprecation</code> is
equivalent to <code>--pending_deprecation</code>.</p>
<p>If an option that takes a single value (such as <code>--max-http-header-size</code>) is
passed more than once, then the last passed value is used. Options from the
command line take precedence over options passed through the <a href="#all_cli_node_optionsoptions"><code>NODE_OPTIONS</code></a>
environment variable.</p>
<h4><code>-</code><span><a class="mark" href="#all_cli_-" id="all_cli_-">#</a></span><a aria-hidden="true" class="legacy" id="cli"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Alias for stdin. Analogous to the use of <code>-</code> in other command-line utilities,
meaning that the script is read from stdin, and the rest of the options
are passed to that script.</p>
<h4><code>--</code><span><a class="mark" href="#all_cli_--" id="all_cli_--">#</a></span><a aria-hidden="true" class="legacy" id="cli_1"></a></h4>
<div class="api_metadata">
<span>Added in: v6.11.0</span>
</div>
<p>Indicate the end of node options. Pass the rest of the arguments to the script.
If no script filename or eval/print script is supplied prior to this, then
the next argument is used as a script filename.</p>
<h4><code>--abort-on-uncaught-exception</code><span><a class="mark" href="#all_cli_--abort-on-uncaught-exception" id="all_cli_--abort-on-uncaught-exception">#</a></span><a aria-hidden="true" class="legacy" id="cli_abort_on_uncaught_exception"></a></h4>
<div class="api_metadata">
<span>Added in: v0.10.8</span>
</div>
<p>Aborting instead of exiting causes a core file to be generated for post-mortem
analysis using a debugger (such as <code>lldb</code>, <code>gdb</code>, and <code>mdb</code>).</p>
<p>If this flag is passed, the behavior can still be set to not abort through
<a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> (and through usage of the
<code>node:domain</code> module that uses it).</p>
<h4><code>--allow-addons</code><span><a class="mark" href="#all_cli_--allow-addons" id="all_cli_--allow-addons">#</a></span><a aria-hidden="true" class="legacy" id="cli_allow_addons"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>When using the <a href="#all_permissions_permission-model">Permission Model</a>, the process will not be able to use
native addons by default.
Attempts to do so will throw an <code>ERR_DLOPEN_DISABLED</code> unless the
user explicitly passes the <code>--allow-addons</code> flag when starting Node.js.</p>
<p>Example:</p>
<pre><code class="language-js cjs"><span class="hljs-comment">// Attempt to require an native addon</span>
<span class="hljs-built_in">require</span>(<span class="hljs-string">'nodejs-addon-example'</span>);</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission --allow-fs-read=* index.js</span>
node:internal/modules/cjs/loader:1319
return process.dlopen(module, path.toNamespacedPath(filename));
^
Error: Cannot load native addon because loading addons is disabled.
at Module._extensions..node (node:internal/modules/cjs/loader:1319:18)
at Module.load (node:internal/modules/cjs/loader:1091:32)
at Module._load (node:internal/modules/cjs/loader:938:12)
at Module.require (node:internal/modules/cjs/loader:1115:19)
at require (node:internal/modules/helpers:130:18)
at Object.<anonymous> (/home/index.js:1:15)
at Module._compile (node:internal/modules/cjs/loader:1233:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1287:10)
at Module.load (node:internal/modules/cjs/loader:1091:32)
at Module._load (node:internal/modules/cjs/loader:938:12) {
code: 'ERR_DLOPEN_DISABLED'
}</code> <button class="copy-button">copy</button></pre>
<h4><code>--allow-child-process</code><span><a class="mark" href="#all_cli_--allow-child-process" id="all_cli_--allow-child-process">#</a></span><a aria-hidden="true" class="legacy" id="cli_allow_child_process"></a></h4>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>When using the <a href="#all_permissions_permission-model">Permission Model</a>, the process will not be able to spawn any
child process by default.
Attempts to do so will throw an <code>ERR_ACCESS_DENIED</code> unless the
user explicitly passes the <code>--allow-child-process</code> flag when starting Node.js.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> childProcess = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-comment">// Attempt to bypass the permission</span>
childProcess.<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'-e'</span>, <span class="hljs-string">'require("fs").writeFileSync("/new-file", "example")'</span>]);</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission --allow-fs-read=* index.js</span>
node:internal/child_process:388
const err = this._handle.spawn(options);
^
Error: Access to this API has been restricted
at ChildProcess.spawn (node:internal/child_process:388:28)
at Object.spawn (node:child_process:723:9)
at Object.<anonymous> (/home/index.js:3:14)
at Module._compile (node:internal/modules/cjs/loader:1120:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1174:10)
at Module.load (node:internal/modules/cjs/loader:998:32)
at Module._load (node:internal/modules/cjs/loader:839:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
code: 'ERR_ACCESS_DENIED',
permission: 'ChildProcess'
}</code> <button class="copy-button">copy</button></pre>
<h4><code>--allow-fs-read</code><span><a class="mark" href="#all_cli_--allow-fs-read" id="all_cli_--allow-fs-read">#</a></span><a aria-hidden="true" class="legacy" id="cli_allow_fs_read"></a></h4>
<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</td>
<td><p>Paths delimited by comma (<code>,</code>) are no longer allowed.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p><span>Added in: v20.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>This flag configures file system read permissions using
the <a href="#all_permissions_permission-model">Permission Model</a>.</p>
<p>The valid arguments for the <code>--allow-fs-read</code> flag are:</p>
<ul>
<li><code>*</code> - To allow all <code>FileSystemRead</code> operations.</li>
<li>Multiple paths can be allowed using multiple <code>--allow-fs-read</code> flags.
Example <code>--allow-fs-read=/folder1/ --allow-fs-read=/folder1/</code></li>
</ul>
<p>Paths delimited by comma (<code>,</code>) are no longer allowed.
When passing a single flag with a comma a warning will be displayed.</p>
<p>Examples can be found in the <a href="#all_permissions_file-system-permissions">File System Permissions</a> documentation.</p>
<p>Relative paths are NOT yet supported by the CLI flag.</p>
<p>The initializer module also needs to be allowed. Consider the following example:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission t.js</span>
node:internal/modules/cjs/loader:162
const result = internalModuleStat(filename);
^
Error: Access to this API has been restricted
at stat (node:internal/modules/cjs/loader:162:18)
at Module._findPath (node:internal/modules/cjs/loader:640:16)
at resolveMainPath (node:internal/modules/run_main:15:25)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:53:24)
at node:internal/main/run_main_module:23:47 {
code: 'ERR_ACCESS_DENIED',
permission: 'FileSystemRead',
resource: '/Users/rafaelgss/repos/os/node/t.js'
}</code> <button class="copy-button">copy</button></pre>
<p>The process needs to have access to the <code>index.js</code> module:</p>
<pre><code class="language-bash">node --experimental-permission --allow-fs-read=/path/to/index.js index.js</code> <button class="copy-button">copy</button></pre>
<h4><code>--allow-fs-write</code><span><a class="mark" href="#all_cli_--allow-fs-write" id="all_cli_--allow-fs-write">#</a></span><a aria-hidden="true" class="legacy" id="cli_allow_fs_write"></a></h4>
<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</td>
<td><p>Paths delimited by comma (<code>,</code>) are no longer allowed.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p><span>Added in: v20.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>This flag configures file system write permissions using
the <a href="#all_permissions_permission-model">Permission Model</a>.</p>
<p>The valid arguments for the <code>--allow-fs-write</code> flag are:</p>
<ul>
<li><code>*</code> - To allow all <code>FileSystemWrite</code> operations.</li>
<li>Multiple paths can be allowed using multiple <code>--allow-fs-write</code> flags.
Example <code>--allow-fs-write=/folder1/ --allow-fs-write=/folder1/</code></li>
</ul>
<p>Paths delimited by comma (<code>,</code>) are no longer allowed.
When passing a single flag with a comma a warning will be displayed.</p>
<p>Examples can be found in the <a href="#all_permissions_file-system-permissions">File System Permissions</a> documentation.</p>
<p>Relative paths are NOT supported through the CLI flag.</p>
<h4><code>--allow-wasi</code><span><a class="mark" href="#all_cli_--allow-wasi" id="all_cli_--allow-wasi">#</a></span><a aria-hidden="true" class="legacy" id="cli_allow_wasi"></a></h4>
<div class="api_metadata">
<span>Added in: v20.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>When using the <a href="#all_permissions_permission-model">Permission Model</a>, the process will not be capable of creating
any WASI instances by default.
For security reasons, the call will throw an <code>ERR_ACCESS_DENIED</code> unless the
user explicitly passes the flag <code>--allow-wasi</code> in the main Node.js process.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-variable constant_">WASI</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:wasi'</span>);
<span class="hljs-comment">// Attempt to bypass the permission</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">WASI</span>({
<span class="hljs-attr">version</span>: <span class="hljs-string">'preview1'</span>,
<span class="hljs-comment">// Attempt to mount the whole filesystem</span>
<span class="hljs-attr">preopens</span>: {
<span class="hljs-string">'/'</span>: <span class="hljs-string">'/'</span>,
},
});</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission --allow-fs-read=* index.js</span>
node:wasi:99
const wrap = new _WASI(args, env, preopens, stdio);
^
Error: Access to this API has been restricted
at new WASI (node:wasi:99:18)
at Object.<anonymous> (/home/index.js:3:1)
at Module._compile (node:internal/modules/cjs/loader:1476:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1555:10)
at Module.load (node:internal/modules/cjs/loader:1288:32)
at Module._load (node:internal/modules/cjs/loader:1104:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:191:14)
at node:internal/main/run_main_module:30:49 {
code: 'ERR_ACCESS_DENIED',
permission: 'WASI',
}</code> <button class="copy-button">copy</button></pre>
<h4><code>--allow-worker</code><span><a class="mark" href="#all_cli_--allow-worker" id="all_cli_--allow-worker">#</a></span><a aria-hidden="true" class="legacy" id="cli_allow_worker"></a></h4>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>When using the <a href="#all_permissions_permission-model">Permission Model</a>, the process will not be able to create any
worker threads by default.
For security reasons, the call will throw an <code>ERR_ACCESS_DENIED</code> unless the
user explicitly pass the flag <code>--allow-worker</code> in the main Node.js process.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-comment">// Attempt to bypass the permission</span>
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission --allow-fs-read=* index.js</span>
node:internal/worker:188
this[kHandle] = new WorkerImpl(url,
^
Error: Access to this API has been restricted
at new Worker (node:internal/worker:188:21)
at Object.<anonymous> (/home/index.js.js:3:1)
at Module._compile (node:internal/modules/cjs/loader:1120:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1174:10)
at Module.load (node:internal/modules/cjs/loader:998:32)
at Module._load (node:internal/modules/cjs/loader:839:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
code: 'ERR_ACCESS_DENIED',
permission: 'WorkerThreads'
}</code> <button class="copy-button">copy</button></pre>
<h4><code>--build-snapshot</code><span><a class="mark" href="#all_cli_--build-snapshot" id="all_cli_--build-snapshot">#</a></span><a aria-hidden="true" class="legacy" id="cli_build_snapshot"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Generates a snapshot blob when the process exits and writes it to
disk, which can be loaded later with <code>--snapshot-blob</code>.</p>
<p>When building the snapshot, if <code>--snapshot-blob</code> is not specified,
the generated blob will be written, by default, to <code>snapshot.blob</code>
in the current working directory. Otherwise it will be written to
the path specified by <code>--snapshot-blob</code>.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"globalThis.foo = 'I am from the snapshot'"</span> > snapshot.js</span>
<span class="hljs-meta prompt_">
# </span><span class="language-bash">Run snapshot.js to initialize the application and snapshot the</span>
<span class="hljs-meta prompt_"># </span><span class="language-bash">state of it into snapshot.blob.</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node --snapshot-blob snapshot.blob --build-snapshot snapshot.js</span>
<span class="hljs-meta prompt_">
$ </span><span class="language-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"console.log(globalThis.foo)"</span> > index.js</span>
<span class="hljs-meta prompt_">
# </span><span class="language-bash">Load the generated snapshot and start the application from index.js.</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node --snapshot-blob snapshot.blob index.js</span>
I am from the snapshot</code> <button class="copy-button">copy</button></pre>
<p>The <a href="#all_v8_startup-snapshot-api"><code>v8.startupSnapshot</code> API</a> can be used to specify an entry point at
snapshot building time, thus avoiding the need of an additional entry
script at deserialization time:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"require('v8').startupSnapshot.setDeserializeMainFunction(() => console.log('I am from the snapshot'))"</span> > snapshot.js</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node --snapshot-blob snapshot.blob --build-snapshot snapshot.js</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node --snapshot-blob snapshot.blob</span>
I am from the snapshot</code> <button class="copy-button">copy</button></pre>
<p>For more information, check out the <a href="#all_v8_startup-snapshot-api"><code>v8.startupSnapshot</code> API</a> documentation.</p>
<p>Currently the support for run-time snapshot is experimental in that:</p>
<ol>
<li>User-land modules are not yet supported in the snapshot, so only
one single file can be snapshotted. Users can bundle their applications
into a single script with their bundler of choice before building
a snapshot, however.</li>
<li>Only a subset of the built-in modules work in the snapshot, though the
Node.js core test suite checks that a few fairly complex applications
can be snapshotted. Support for more modules are being added. If any
crashes or buggy behaviors occur when building a snapshot, please file
a report in the <a href="https://github.com/nodejs/node/issues">Node.js issue tracker</a> and link to it in the
<a href="https://github.com/nodejs/node/issues/44014">tracking issue for user-land snapshots</a>.</li>
</ol>
<h4><code>--build-snapshot-config</code><span><a class="mark" href="#all_cli_--build-snapshot-config" id="all_cli_--build-snapshot-config">#</a></span><a aria-hidden="true" class="legacy" id="cli_build_snapshot_config"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Specifies the path to a JSON configuration file which configures snapshot
creation behavior.</p>
<p>The following options are currently supported:</p>
<ul>
<li><code>builder</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Required. Provides the name to the script that is executed
before building the snapshot, as if <a href="#all_cli_--build-snapshot"><code>--build-snapshot</code></a> had been passed
with <code>builder</code> as the main script name.</li>
<li><code>withoutCodeCache</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Optional. Including the code cache reduces the
time spent on compiling functions included in the snapshot at the expense
of a bigger snapshot size and potentially breaking portability of the
snapshot.</li>
</ul>
<p>When using this flag, additional script files provided on the command line will
not be executed and instead be interpreted as regular command line arguments.</p>
<h4><code>-c</code>, <code>--check</code><span><a class="mark" href="#all_cli_-c---check" id="all_cli_-c---check">#</a></span><a aria-hidden="true" class="legacy" id="cli_c_check"></a></h4>
<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>--require</code> option is now supported when checking a file.</p></td></tr>
<tr><td>v5.0.0, v4.2.0</td>
<td><p><span>Added in: v5.0.0, v4.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Syntax check the script without executing.</p>
<h4><code>--completion-bash</code><span><a class="mark" href="#all_cli_--completion-bash" id="all_cli_--completion-bash">#</a></span><a aria-hidden="true" class="legacy" id="cli_completion_bash"></a></h4>
<div class="api_metadata">
<span>Added in: v10.12.0</span>
</div>
<p>Print source-able bash completion script for Node.js.</p>
<pre><code class="language-bash">node --completion-bash > node_bash_completion
<span class="hljs-built_in">source</span> node_bash_completion</code> <button class="copy-button">copy</button></pre>
<h4><code>-C condition</code>, <code>--conditions=condition</code><span><a class="mark" href="#all_cli_-c-condition---conditionscondition" id="all_cli_-c-condition---conditionscondition">#</a></span><a aria-hidden="true" class="legacy" id="cli_c_condition_conditions_condition"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>The flag is no longer experimental.</p></td></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p><span>Added in: v14.9.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Provide custom <a href="#all_packages_conditional-exports">conditional exports</a> resolution conditions.</p>
<p>Any number of custom string condition names are permitted.</p>
<p>The default Node.js conditions of <code>"node"</code>, <code>"default"</code>, <code>"import"</code>, and
<code>"require"</code> will always apply as defined.</p>
<p>For example, to run a module with "development" resolutions:</p>
<pre><code class="language-bash">node -C development app.js</code> <button class="copy-button">copy</button></pre>
<h4><code>--cpu-prof</code><span><a class="mark" href="#all_cli_--cpu-prof" id="all_cli_--cpu-prof">#</a></span><a aria-hidden="true" class="legacy" id="cli_cpu_prof"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--cpu-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p><span>Added in: v12.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Starts the V8 CPU profiler on start up, and writes the CPU profile to disk
before exit.</p>
<p>If <code>--cpu-prof-dir</code> is not specified, the generated profile is placed
in the current working directory.</p>
<p>If <code>--cpu-prof-name</code> is not specified, the generated profile is
named <code>CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile</code>.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --cpu-prof index.js</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">ls</span> *.cpuprofile</span>
CPU.20190409.202950.15293.0.0.cpuprofile</code> <button class="copy-button">copy</button></pre>
<h4><code>--cpu-prof-dir</code><span><a class="mark" href="#all_cli_--cpu-prof-dir" id="all_cli_--cpu-prof-dir">#</a></span><a aria-hidden="true" class="legacy" id="cli_cpu_prof_dir"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--cpu-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p><span>Added in: v12.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Specify the directory where the CPU profiles generated by <code>--cpu-prof</code> will
be placed.</p>
<p>The default value is controlled by the
<a href="#all_cli_--diagnostic-dirdirectory"><code>--diagnostic-dir</code></a> command-line option.</p>
<h4><code>--cpu-prof-interval</code><span><a class="mark" href="#all_cli_--cpu-prof-interval" id="all_cli_--cpu-prof-interval">#</a></span><a aria-hidden="true" class="legacy" id="cli_cpu_prof_interval"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--cpu-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.2.0</td>
<td><p><span>Added in: v12.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Specify the sampling interval in microseconds for the CPU profiles generated
by <code>--cpu-prof</code>. The default is 1000 microseconds.</p>
<h4><code>--cpu-prof-name</code><span><a class="mark" href="#all_cli_--cpu-prof-name" id="all_cli_--cpu-prof-name">#</a></span><a aria-hidden="true" class="legacy" id="cli_cpu_prof_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--cpu-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p><span>Added in: v12.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Specify the file name of the CPU profile generated by <code>--cpu-prof</code>.</p>
<h4><code>--diagnostic-dir=directory</code><span><a class="mark" href="#all_cli_--diagnostic-dirdirectory" id="all_cli_--diagnostic-dirdirectory">#</a></span><a aria-hidden="true" class="legacy" id="cli_diagnostic_dir_directory"></a></h4>
<p>Set the directory to which all diagnostic output files are written.
Defaults to current working directory.</p>
<p>Affects the default output directory of:</p>
<ul>
<li><a href="#all_cli_--cpu-prof-dir"><code>--cpu-prof-dir</code></a></li>
<li><a href="#all_cli_--heap-prof-dir"><code>--heap-prof-dir</code></a></li>
<li><a href="#all_cli_--redirect-warningsfile"><code>--redirect-warnings</code></a></li>
</ul>
<h4><code>--disable-warning=code-or-type</code><span><a class="mark" href="#all_cli_--disable-warningcode-or-type" id="all_cli_--disable-warningcode-or-type">#</a></span><a aria-hidden="true" class="legacy" id="cli_disable_warning_code_or_type"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<div class="api_metadata">
<span>Added in: v20.11.0</span>
</div>
<p>Disable specific process warnings by <code>code</code> or <code>type</code>.</p>
<p>Warnings emitted from <a href="#all_process_processemitwarningwarning-options"><code>process.emitWarning()</code></a> may contain a
<code>code</code> and a <code>type</code>. This option will not-emit warnings that have a matching
<code>code</code> or <code>type</code>.</p>
<p>List of <a href="#all_deprecations_list-of-deprecated-apis">deprecation warnings</a>.</p>
<p>The Node.js core warning types are: <code>DeprecationWarning</code> and
<code>ExperimentalWarning</code></p>
<p>For example, the following script will not emit
<a href="#all_deprecations_dep0025-requirenodesys">DEP0025 <code>require('node:sys')</code></a> when executed with
<code>node --disable-warning=DEP0025</code>:</p>
<pre class="with-32-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> sys <span class="hljs-keyword">from</span> <span class="hljs-string">'node:sys'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> sys = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:sys'</span>);</code><button class="copy-button">copy</button></pre>
<p>For example, the following script will emit the
<a href="#all_deprecations_dep0025-requirenodesys">DEP0025 <code>require('node:sys')</code></a>, but not any Experimental
Warnings (such as
<a href="#all_vm_vmmeasurememoryoptions">ExperimentalWarning: <code>vm.measureMemory</code> is an experimental feature</a>
in <=v21) when executed with <code>node --disable-warning=ExperimentalWarning</code>:</p>
<pre class="with-32-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> sys <span class="hljs-keyword">from</span> <span class="hljs-string">'node:sys'</span>;
<span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;
vm.<span class="hljs-title function_">measureMemory</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> sys = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:sys'</span>);
<span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
vm.<span class="hljs-title function_">measureMemory</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>--disable-wasm-trap-handler</code><span><a class="mark" href="#all_cli_--disable-wasm-trap-handler" id="all_cli_--disable-wasm-trap-handler">#</a></span><a aria-hidden="true" class="legacy" id="cli_disable_wasm_trap_handler"></a></h4>
<div class="api_metadata">
<span>Added in: v20.15.0</span>
</div>
<p>By default, Node.js enables trap-handler-based WebAssembly bound
checks. As a result, V8 does not need to insert inline bound checks
int the code compiled from WebAssembly which may speedup WebAssembly
execution significantly, but this optimization requires allocating
a big virtual memory cage (currently 10GB). If the Node.js process
does not have access to a large enough virtual memory address space
due to system configurations or hardware limitations, users won't
be able to run any WebAssembly that involves allocation in this
virtual memory cage and will see an out-of-memory error.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">ulimit</span> -v 5000000</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p <span class="hljs-string">"new WebAssembly.Memory({ initial: 10, maximum: 100 });"</span></span>
[eval]:1
new WebAssembly.Memory({ initial: 10, maximum: 100 });
^
RangeError: WebAssembly.Memory(): could not allocate memory
at [eval]:1:1
at runScriptInThisContext (node:internal/vm:209:10)
at node:internal/process/execution:118:14
at [eval]-wrapper:6:24
at runScript (node:internal/process/execution:101:62)
at evalScript (node:internal/process/execution:136:3)
at node:internal/main/eval_string:49:3
</code> <button class="copy-button">copy</button></pre>
<p><code>--disable-wasm-trap-handler</code> disables this optimization so that
users can at least run WebAssembly (with less optimal performance)
when the virtual memory address space available to their Node.js
process is lower than what the V8 WebAssembly memory cage needs.</p>
<h4><code>--disable-proto=mode</code><span><a class="mark" href="#all_cli_--disable-protomode" id="all_cli_--disable-protomode">#</a></span><a aria-hidden="true" class="legacy" id="cli_disable_proto_mode"></a></h4>
<div class="api_metadata">
<span>Added in: v13.12.0, v12.17.0</span>
</div>
<p>Disable the <code>Object.prototype.__proto__</code> property. If <code>mode</code> is <code>delete</code>, the
property is removed entirely. If <code>mode</code> is <code>throw</code>, accesses to the
property throw an exception with the code <code>ERR_PROTO_ACCESS</code>.</p>
<h4><code>--disallow-code-generation-from-strings</code><span><a class="mark" href="#all_cli_--disallow-code-generation-from-strings" id="all_cli_--disallow-code-generation-from-strings">#</a></span><a aria-hidden="true" class="legacy" id="cli_disallow_code_generation_from_strings"></a></h4>
<div class="api_metadata">
<span>Added in: v9.8.0</span>
</div>
<p>Make built-in language features like <code>eval</code> and <code>new Function</code> that generate
code from strings throw an exception instead. This does not affect the Node.js
<code>node:vm</code> module.</p>
<h4><code>--expose-gc</code><span><a class="mark" href="#all_cli_--expose-gc" id="all_cli_--expose-gc">#</a></span><a aria-hidden="true" class="legacy" id="cli_expose_gc"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. This flag is inherited from V8 and is subject to
change upstream.</div><p></p>
<p>This flag will expose the gc extension from V8.</p>
<pre><code class="language-js"><span class="hljs-keyword">if</span> (globalThis.<span class="hljs-property">gc</span>) {
globalThis.<span class="hljs-title function_">gc</span>();
}</code> <button class="copy-button">copy</button></pre>
<h4><code>--dns-result-order=order</code><span><a class="mark" href="#all_cli_--dns-result-orderorder" id="all_cli_--dns-result-orderorder">#</a></span><a aria-hidden="true" class="legacy" id="cli_dns_result_order_order"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>ipv6first</code> is supported now.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p>Changed default value to <code>verbatim</code>.</p></td></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p><span>Added in: v16.4.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Set the default value of <code>order</code> in <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> and
<a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup()</code></a>. The value could be:</p>
<ul>
<li><code>ipv4first</code>: sets default <code>order</code> to <code>ipv4first</code>.</li>
<li><code>ipv6first</code>: sets default <code>order</code> to <code>ipv6first</code>.</li>
<li><code>verbatim</code>: sets default <code>order</code> to <code>verbatim</code>.</li>
</ul>
<p>The default is <code>verbatim</code> and <a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> have higher
priority than <code>--dns-result-order</code>.</p>
<h4><code>--enable-fips</code><span><a class="mark" href="#all_cli_--enable-fips" id="all_cli_--enable-fips">#</a></span><a aria-hidden="true" class="legacy" id="cli_enable_fips"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<p>Enable FIPS-compliant crypto at startup. (Requires Node.js to be built
against FIPS-compatible OpenSSL.)</p>
<h4><code>--enable-source-maps</code><span><a class="mark" href="#all_cli_--enable-source-maps" id="all_cli_--enable-source-maps">#</a></span><a aria-hidden="true" class="legacy" id="cli_enable_source_maps"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.11.0, v14.18.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v12.12.0</td>
<td><p><span>Added in: v12.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enable <a href="https://sourcemaps.info/spec.html">Source Map v3</a> support for stack traces.</p>
<p>When using a transpiler, such as TypeScript, stack traces thrown by an
application reference the transpiled code, not the original source position.
<code>--enable-source-maps</code> enables caching of Source Maps and makes a best
effort to report stack traces relative to the original source file.</p>
<p>Overriding <code>Error.prepareStackTrace</code> may prevent <code>--enable-source-maps</code> from
modifying the stack trace. Call and return the results of the original
<code>Error.prepareStackTrace</code> in the overriding function to modify the stack trace
with source maps.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> originalPrepareStackTrace = <span class="hljs-title class_">Error</span>.<span class="hljs-property">prepareStackTrace</span>;
<span class="hljs-title class_">Error</span>.<span class="hljs-property">prepareStackTrace</span> = <span class="hljs-function">(<span class="hljs-params">error, trace</span>) =></span> {
<span class="hljs-comment">// Modify error and trace and format stack trace with</span>
<span class="hljs-comment">// original Error.prepareStackTrace.</span>
<span class="hljs-keyword">return</span> <span class="hljs-title function_">originalPrepareStackTrace</span>(error, trace);
};</code> <button class="copy-button">copy</button></pre>
<p>Note, enabling source maps can introduce latency to your application
when <code>Error.stack</code> is accessed. If you access <code>Error.stack</code> frequently
in your application, take into account the performance implications
of <code>--enable-source-maps</code>.</p>
<h4><code>--env-file=config</code><span><a class="mark" href="#all_cli_--env-fileconfig" id="all_cli_--env-fileconfig">#</a></span><a aria-hidden="true" class="legacy" id="cli_env_file_config"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Add support to multi-line values.</p></td></tr>
<tr><td>v20.6.0</td>
<td><p><span>Added in: v20.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Loads environment variables from a file relative to the current directory,
making them available to applications on <code>process.env</code>. The <a href="#all_cli_environment-variables">environment
variables which configure Node.js</a>, such as <code>NODE_OPTIONS</code>,
are parsed and applied. If the same variable is defined in the environment and
in the file, the value from the environment takes precedence.</p>
<p>You can pass multiple <code>--env-file</code> arguments. Subsequent files override
pre-existing variables defined in previous files.</p>
<p>An error is thrown if the file does not exist.</p>
<pre><code class="language-bash">node --env-file=.<span class="hljs-built_in">env</span> --env-file=.development.env index.js</code> <button class="copy-button">copy</button></pre>
<p>The format of the file should be one line per key-value pair of environment
variable name and value separated by <code>=</code>:</p>
<pre><code class="language-text">PORT=3000</code> <button class="copy-button">copy</button></pre>
<p>Any text after a <code>#</code> is treated as a comment:</p>
<pre><code class="language-text"># This is a comment
PORT=3000 # This is also a comment</code> <button class="copy-button">copy</button></pre>
<p>Values can start and end with the following quotes: <code>`</code>, <code>"</code> or <code>'</code>.
They are omitted from the values.</p>
<pre><code class="language-text">USERNAME="nodejs" # will result in `nodejs` as the value.</code> <button class="copy-button">copy</button></pre>
<p>Multi-line values are supported:</p>
<pre><code class="language-text">MULTI_LINE="THIS IS
A MULTILINE"
# will result in `THIS IS\nA MULTILINE` as the value.</code> <button class="copy-button">copy</button></pre>
<p>Export keyword before a key is ignored:</p>
<pre><code class="language-text">export USERNAME="nodejs" # will result in `nodejs` as the value.</code> <button class="copy-button">copy</button></pre>
<p>If you want to load environment variables from a file that may not exist, you
can use the <a href="#all_cli_--env-file-if-existsconfig"><code>--env-file-if-exists</code></a> flag instead.</p>
<h4><code>-e</code>, <code>--eval "script"</code><span><a class="mark" href="#all_cli_-e---eval-script" id="all_cli_-e---eval-script">#</a></span><a aria-hidden="true" class="legacy" id="cli_e_eval_script"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.11.0</td>
<td><p>Built-in libraries are now available as predefined variables.</p></td></tr>
<tr><td>v0.5.2</td>
<td><p><span>Added in: v0.5.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Evaluate the following argument as JavaScript. The modules which are
predefined in the REPL can also be used in <code>script</code>.</p>
<p>On Windows, using <code>cmd.exe</code> a single quote will not work correctly because it
only recognizes double <code>"</code> for quoting. In Powershell or Git bash, both <code>'</code>
and <code>"</code> are usable.</p>
<h4><code>--experimental-default-type=type</code><span><a class="mark" href="#all_cli_--experimental-default-typetype" id="all_cli_--experimental-default-typetype">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_default_type_type"></a></h4>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.0 - Early development</div><p></p>
<p>Define which module system, <code>module</code> or <code>commonjs</code>, to use for the following:</p>
<ul>
<li>
<p>String input provided via <code>--eval</code> or STDIN, if <code>--input-type</code> is unspecified.</p>
</li>
<li>
<p>Files ending in <code>.js</code> or with no extension, if there is no <code>package.json</code> file
present in the same folder or any parent folder.</p>
</li>
<li>
<p>Files ending in <code>.js</code> or with no extension, if the nearest parent
<code>package.json</code> field lacks a <code>"type"</code> field; unless the <code>package.json</code> folder
or any parent folder is inside a <code>node_modules</code> folder.</p>
</li>
</ul>
<p>In other words, <code>--experimental-default-type=module</code> flips all the places where
Node.js currently defaults to CommonJS to instead default to ECMAScript modules,
with the exception of folders and subfolders below <code>node_modules</code>, for backward
compatibility.</p>
<p>Under <code>--experimental-default-type=module</code> and <code>--experimental-wasm-modules</code>,
files with no extension will be treated as WebAssembly if they begin with the
WebAssembly magic number (<code>\0asm</code>); otherwise they will be treated as ES module
JavaScript.</p>
<h4><code>--experimental-eventsource</code><span><a class="mark" href="#all_cli_--experimental-eventsource" id="all_cli_--experimental-eventsource">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_eventsource"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p>Enable exposition of <a href="https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events">EventSource Web API</a> on the global scope.</p>
<h4><code>--experimental-import-meta-resolve</code><span><a class="mark" href="#all_cli_--experimental-import-meta-resolve" id="all_cli_--experimental-import-meta-resolve">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_import_meta_resolve"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>synchronous import.meta.resolve made available by default, with the flag retained for enabling the experimental second argument as previously supported.</p></td></tr>
<tr><td>v13.9.0, v12.16.2</td>
<td><p><span>Added in: v13.9.0, v12.16.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enable experimental <code>import.meta.resolve()</code> parent URL support, which allows
passing a second <code>parentURL</code> argument for contextual resolution.</p>
<p>Previously gated the entire <code>import.meta.resolve</code> feature.</p>
<h4><code>--experimental-loader=module</code><span><a class="mark" href="#all_cli_--experimental-loadermodule" id="all_cli_--experimental-loadermodule">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_loader_module"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.2</td>
<td><p>Using this feature with the permission model enabled requires passing <code>--allow-worker</code>.</p></td></tr>
<tr><td>v12.11.1</td>
<td><p>This flag was renamed from <code>--loader</code> to <code>--experimental-loader</code>.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p><span>Added in: v8.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<blockquote>
<p>This flag is discouraged and may be removed in a future version of Node.js.
Please use
<a href="#all_module_enabling"><code>--import</code> with <code>register()</code></a> instead.</p>
</blockquote>
<p>Specify the <code>module</code> containing exported <a href="#all_module_customization-hooks">module customization hooks</a>.
<code>module</code> may be any string accepted as an <a href="#all_esm_import-specifiers"><code>import</code> specifier</a>.</p>
<p>This feature requires <code>--allow-worker</code> if used with the <a href="#all_permissions_permission-model">Permission Model</a>.</p>
<h4><code>--experimental-network-imports</code><span><a class="mark" href="#all_cli_--experimental-network-imports" id="all_cli_--experimental-network-imports">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_network_imports"></a></h4>
<div class="api_metadata">
<span>Added in: v17.6.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Enable experimental support for the <code>https:</code> protocol in <code>import</code> specifiers.</p>
<h4><code>--experimental-network-inspection</code><span><a class="mark" href="#all_cli_--experimental-network-inspection" id="all_cli_--experimental-network-inspection">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_network_inspection"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Enable experimental support for the network inspection with Chrome DevTools.</p>
<h4><code>--experimental-permission</code><span><a class="mark" href="#all_cli_--experimental-permission" id="all_cli_--experimental-permission">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_permission"></a></h4>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>Enable the Permission Model for current process. When enabled, the
following permissions are restricted:</p>
<ul>
<li>File System - manageable through
<a href="#all_cli_--allow-fs-read"><code>--allow-fs-read</code></a>, <a href="#all_cli_--allow-fs-write"><code>--allow-fs-write</code></a> flags</li>
<li>Child Process - manageable through <a href="#all_cli_--allow-child-process"><code>--allow-child-process</code></a> flag</li>
<li>Worker Threads - manageable through <a href="#all_cli_--allow-worker"><code>--allow-worker</code></a> flag</li>
<li>WASI - manageable through <a href="#all_cli_--allow-wasi"><code>--allow-wasi</code></a> flag</li>
<li>Addons - manageable through <a href="#all_cli_--allow-addons"><code>--allow-addons</code></a> flag</li>
</ul>
<h4><code>--experimental-policy</code><span><a class="mark" href="#all_cli_--experimental-policy" id="all_cli_--experimental-policy">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_policy"></a></h4>
<div class="api_metadata">
<span>Added in: v11.8.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Will be removed shortly.</div><p></p>
<p>Use the specified file as a security policy.</p>
<h4><code>--experimental-require-module</code><span><a class="mark" href="#all_cli_--experimental-require-module" id="all_cli_--experimental-require-module">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_require_module"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.19.0</td>
<td><p>This is now true by default.</p></td></tr>
<tr><td>v22.0.0, v20.17.0</td>
<td><p><span>Added in: v22.0.0, v20.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active Development</div><p></p>
<p>Supports loading a synchronous ES module graph in <code>require()</code>.</p>
<p>See <a href="#all_modules_loading-ecmascript-modules-using-require">Loading ECMAScript modules using <code>require()</code></a>.</p>
<h4><code>--experimental-sea-config</code><span><a class="mark" href="#all_cli_--experimental-sea-config" id="all_cli_--experimental-sea-config">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_sea_config"></a></h4>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Use this flag to generate a blob that can be injected into the Node.js
binary to produce a <a href="single-executable-applications.html">single executable application</a>. See the documentation
about <a href="#all_single-executable-applications_generating-single-executable-preparation-blobs">this configuration</a> for details.</p>
<h4><code>--experimental-shadow-realm</code><span><a class="mark" href="#all_cli_--experimental-shadow-realm" id="all_cli_--experimental-shadow-realm">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_shadow_realm"></a></h4>
<div class="api_metadata">
<span>Added in: v19.0.0, v18.13.0</span>
</div>
<p>Use this flag to enable <a href="https://github.com/tc39/proposal-shadowrealm">ShadowRealm</a> support.</p>
<h4><code>--experimental-test-coverage</code><span><a class="mark" href="#all_cli_--experimental-test-coverage" id="all_cli_--experimental-test-coverage">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_test_coverage"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>This option can be used with <code>--test</code>.</p></td></tr>
<tr><td>v19.7.0, v18.15.0</td>
<td><p><span>Added in: v19.7.0, v18.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>When used in conjunction with the <code>node:test</code> module, a code coverage report is
generated as part of the test runner output. If no tests are run, a coverage
report is not generated. See the documentation on
<a href="#all_test_collecting-code-coverage">collecting code coverage from tests</a> for more details.</p>
<h4><code>--experimental-test-module-mocks</code><span><a class="mark" href="#all_cli_--experimental-test-module-mocks" id="all_cli_--experimental-test-module-mocks">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_test_module_mocks"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.2</td>
<td><p>Using this feature with the permission model enabled requires passing <code>--allow-worker</code>.</p></td></tr>
<tr><td>v20.18.0</td>
<td><p><span>Added in: v20.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.0 - Early development</div><p></p>
<p>Enable module mocking in the test runner.</p>
<p>This feature requires <code>--allow-worker</code> if used with the <a href="#all_permissions_permission-model">Permission Model</a>.</p>
<h4><code>--experimental-vm-modules</code><span><a class="mark" href="#all_cli_--experimental-vm-modules" id="all_cli_--experimental-vm-modules">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_vm_modules"></a></h4>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
</div>
<p>Enable experimental ES Module support in the <code>node:vm</code> module.</p>
<h4><code>--experimental-wasi-unstable-preview1</code><span><a class="mark" href="#all_cli_--experimental-wasi-unstable-preview1" id="all_cli_--experimental-wasi-unstable-preview1">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_wasi_unstable_preview1"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>This option is no longer required as WASI is enabled by default, but can still be passed.</p></td></tr>
<tr><td>v13.6.0</td>
<td><p>changed from <code>--experimental-wasi-unstable-preview0</code> to <code>--experimental-wasi-unstable-preview1</code>.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p><span>Added in: v13.3.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enable experimental WebAssembly System Interface (WASI) support.</p>
<h4><code>--experimental-wasm-modules</code><span><a class="mark" href="#all_cli_--experimental-wasm-modules" id="all_cli_--experimental-wasm-modules">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_wasm_modules"></a></h4>
<div class="api_metadata">
<span>Added in: v12.3.0</span>
</div>
<p>Enable experimental WebAssembly module support.</p>
<h4><code>--experimental-websocket</code><span><a class="mark" href="#all_cli_--experimental-websocket" id="all_cli_--experimental-websocket">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_websocket"></a></h4>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p>Enable experimental <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket"><code>WebSocket</code></a> support.</p>
<h4><code>--force-context-aware</code><span><a class="mark" href="#all_cli_--force-context-aware" id="all_cli_--force-context-aware">#</a></span><a aria-hidden="true" class="legacy" id="cli_force_context_aware"></a></h4>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<p>Disable loading native addons that are not <a href="#all_addons_context-aware-addons">context-aware</a>.</p>
<h4><code>--force-fips</code><span><a class="mark" href="#all_cli_--force-fips" id="all_cli_--force-fips">#</a></span><a aria-hidden="true" class="legacy" id="cli_force_fips"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<p>Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.)
(Same requirements as <code>--enable-fips</code>.)</p>
<h4><code>--force-node-api-uncaught-exceptions-policy</code><span><a class="mark" href="#all_cli_--force-node-api-uncaught-exceptions-policy" id="all_cli_--force-node-api-uncaught-exceptions-policy">#</a></span><a aria-hidden="true" class="legacy" id="cli_force_node_api_uncaught_exceptions_policy"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<p>Enforces <code>uncaughtException</code> event on Node-API asynchronous callbacks.</p>
<p>To prevent from an existing add-on from crashing the process, this flag is not
enabled by default. In the future, this flag will be enabled by default to
enforce the correct behavior.</p>
<h4><code>--frozen-intrinsics</code><span><a class="mark" href="#all_cli_--frozen-intrinsics" id="all_cli_--frozen-intrinsics">#</a></span><a aria-hidden="true" class="legacy" id="cli_frozen_intrinsics"></a></h4>
<div class="api_metadata">
<span>Added in: v11.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Enable experimental frozen intrinsics like <code>Array</code> and <code>Object</code>.</p>
<p>Only the root context is supported. There is no guarantee that
<code>globalThis.Array</code> is indeed the default intrinsic reference. Code may break
under this flag.</p>
<p>To allow polyfills to be added,
<a href="#all_cli_-r---require-module"><code>--require</code></a> and <a href="#all_cli_--importmodule"><code>--import</code></a> both run before freezing intrinsics.</p>
<h4><code>--heap-prof</code><span><a class="mark" href="#all_cli_--heap-prof" id="all_cli_--heap-prof">#</a></span><a aria-hidden="true" class="legacy" id="cli_heap_prof"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--heap-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.4.0</td>
<td><p><span>Added in: v12.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Starts the V8 heap profiler on start up, and writes the heap profile to disk
before exit.</p>
<p>If <code>--heap-prof-dir</code> is not specified, the generated profile is placed
in the current working directory.</p>
<p>If <code>--heap-prof-name</code> is not specified, the generated profile is
named <code>Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile</code>.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --heap-prof index.js</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">ls</span> *.heapprofile</span>
Heap.20190409.202950.15293.0.001.heapprofile</code> <button class="copy-button">copy</button></pre>
<h4><code>--heap-prof-dir</code><span><a class="mark" href="#all_cli_--heap-prof-dir" id="all_cli_--heap-prof-dir">#</a></span><a aria-hidden="true" class="legacy" id="cli_heap_prof_dir"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--heap-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.4.0</td>
<td><p><span>Added in: v12.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Specify the directory where the heap profiles generated by <code>--heap-prof</code> will
be placed.</p>
<p>The default value is controlled by the
<a href="#all_cli_--diagnostic-dirdirectory"><code>--diagnostic-dir</code></a> command-line option.</p>
<h4><code>--heap-prof-interval</code><span><a class="mark" href="#all_cli_--heap-prof-interval" id="all_cli_--heap-prof-interval">#</a></span><a aria-hidden="true" class="legacy" id="cli_heap_prof_interval"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--heap-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.4.0</td>
<td><p><span>Added in: v12.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Specify the average sampling interval in bytes for the heap profiles generated
by <code>--heap-prof</code>. The default is 512 * 1024 bytes.</p>
<h4><code>--heap-prof-name</code><span><a class="mark" href="#all_cli_--heap-prof-name" id="all_cli_--heap-prof-name">#</a></span><a aria-hidden="true" class="legacy" id="cli_heap_prof_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--heap-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.4.0</td>
<td><p><span>Added in: v12.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Specify the file name of the heap profile generated by <code>--heap-prof</code>.</p>
<h4><code>--heapsnapshot-near-heap-limit=max_count</code><span><a class="mark" href="#all_cli_--heapsnapshot-near-heap-limitmax_count" id="all_cli_--heapsnapshot-near-heap-limitmax_count">#</a></span><a aria-hidden="true" class="legacy" id="cli_heapsnapshot_near_heap_limit_max_count"></a></h4>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Writes a V8 heap snapshot to disk when the V8 heap usage is approaching the
heap limit. <code>count</code> should be a non-negative integer (in which case
Node.js will write no more than <code>max_count</code> snapshots to disk).</p>
<p>When generating snapshots, garbage collection may be triggered and bring
the heap usage down. Therefore multiple snapshots may be written to disk
before the Node.js instance finally runs out of memory. These heap snapshots
can be compared to determine what objects are being allocated during the
time consecutive snapshots are taken. It's not guaranteed that Node.js will
write exactly <code>max_count</code> snapshots to disk, but it will try
its best to generate at least one and up to <code>max_count</code> snapshots before the
Node.js instance runs out of memory when <code>max_count</code> is greater than <code>0</code>.</p>
<p>Generating V8 snapshots takes time and memory (both memory managed by the
V8 heap and native memory outside the V8 heap). The bigger the heap is,
the more resources it needs. Node.js will adjust the V8 heap to accommodate
the additional V8 heap memory overhead, and try its best to avoid using up
all the memory available to the process. When the process uses
more memory than the system deems appropriate, the process may be terminated
abruptly by the system, depending on the system configuration.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --max-old-space-size=100 --heapsnapshot-near-heap-limit=3 index.js</span>
Wrote snapshot to Heap.20200430.100036.49580.0.001.heapsnapshot
Wrote snapshot to Heap.20200430.100037.49580.0.002.heapsnapshot
Wrote snapshot to Heap.20200430.100038.49580.0.003.heapsnapshot
<--- Last few GCs --->
[49580:0x110000000] 4826 ms: Mark-sweep 130.6 (147.8) -> 130.5 (147.8) MB, 27.4 / 0.0 ms (average mu = 0.126, current mu = 0.034) allocation failure scavenge might not succeed
[49580:0x110000000] 4845 ms: Mark-sweep 130.6 (147.8) -> 130.6 (147.8) MB, 18.8 / 0.0 ms (average mu = 0.088, current mu = 0.031) allocation failure scavenge might not succeed
<--- JS stacktrace --->
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
....</code> <button class="copy-button">copy</button></pre>
<h4><code>--heapsnapshot-signal=signal</code><span><a class="mark" href="#all_cli_--heapsnapshot-signalsignal" id="all_cli_--heapsnapshot-signalsignal">#</a></span><a aria-hidden="true" class="legacy" id="cli_heapsnapshot_signal_signal"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Enables a signal handler that causes the Node.js process to write a heap dump
when the specified signal is received. <code>signal</code> must be a valid signal name.
Disabled by default.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --heapsnapshot-signal=SIGUSR2 index.js &</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">ps aux</span>
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
node 1 5.5 6.1 787252 247004 ? Ssl 16:43 0:02 node --heapsnapshot-signal=SIGUSR2 index.js
<span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">kill</span> -USR2 1</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">ls</span></span>
Heap.20190718.133405.15554.0.001.heapsnapshot</code> <button class="copy-button">copy</button></pre>
<h4><code>-h</code>, <code>--help</code><span><a class="mark" href="#all_cli_-h---help" id="all_cli_-h---help">#</a></span><a aria-hidden="true" class="legacy" id="cli_h_help"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.3</span>
</div>
<p>Print node command-line options.
The output of this option is less detailed than this document.</p>
<h4><code>--icu-data-dir=file</code><span><a class="mark" href="#all_cli_--icu-data-dirfile" id="all_cli_--icu-data-dirfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_icu_data_dir_file"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</div>
<p>Specify ICU data load path. (Overrides <code>NODE_ICU_DATA</code>.)</p>
<h4><code>--import=module</code><span><a class="mark" href="#all_cli_--importmodule" id="all_cli_--importmodule">#</a></span><a aria-hidden="true" class="legacy" id="cli_import_module"></a></h4>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Preload the specified module at startup. If the flag is provided several times,
each module will be executed sequentially in the order they appear, starting
with the ones provided in <a href="#all_cli_node_optionsoptions"><code>NODE_OPTIONS</code></a>.</p>
<p>Follows <a href="#all_esm_modules-ecmascript-modules">ECMAScript module</a> resolution rules.
Use <a href="#all_cli_-r---require-module"><code>--require</code></a> to load a <a href="modules.html">CommonJS module</a>.
Modules preloaded with <code>--require</code> will run before modules preloaded with <code>--import</code>.</p>
<h4><code>--input-type=type</code><span><a class="mark" href="#all_cli_--input-typetype" id="all_cli_--input-typetype">#</a></span><a aria-hidden="true" class="legacy" id="cli_input_type_type"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>This configures Node.js to interpret <code>--eval</code> or <code>STDIN</code> input as CommonJS or
as an ES module. Valid values are <code>"commonjs"</code> or <code>"module"</code>. The default is
<code>"commonjs"</code> unless <a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type=module</code></a> is used.</p>
<p>The REPL does not support this option. Usage of <code>--input-type=module</code> with
<a href="#all_cli_-p---print-script"><code>--print</code></a> will throw an error, as <code>--print</code> does not support ES module
syntax.</p>
<h4><code>--insecure-http-parser</code><span><a class="mark" href="#all_cli_--insecure-http-parser" id="all_cli_--insecure-http-parser">#</a></span><a aria-hidden="true" class="legacy" id="cli_insecure_http_parser"></a></h4>
<div class="api_metadata">
<span>Added in: v13.4.0, v12.15.0, v10.19.0</span>
</div>
<p>Enable leniency flags on the HTTP parser. This may allow
interoperability with non-conformant HTTP implementations.</p>
<p>When enabled, the parser will accept the following:</p>
<ul>
<li>Invalid HTTP headers values.</li>
<li>Invalid HTTP versions.</li>
<li>Allow message containing both <code>Transfer-Encoding</code>
and <code>Content-Length</code> headers.</li>
<li>Allow extra data after message when <code>Connection: close</code> is present.</li>
<li>Allow extra trasfer encodings after <code>chunked</code> has been provided.</li>
<li>Allow <code>\n</code> to be used as token separator instead of <code>\r\n</code>.</li>
<li>Allow <code>\r\n</code> not to be provided after a chunk.</li>
<li>Allow spaces to be present after a chunk size and before <code>\r\n</code>.</li>
</ul>
<p>All the above will expose your application to request smuggling
or poisoning attack. Avoid using this option.</p>
<h4><code>--inspect[=[host:]port]</code><span><a class="mark" href="#all_cli_--inspecthostport" id="all_cli_--inspecthostport">#</a></span><a aria-hidden="true" class="legacy" id="cli_inspect_host_port"></a></h4>
<div class="api_metadata">
<span>Added in: v6.3.0</span>
</div>
<p>Activate inspector on <code>host:port</code>. Default is <code>127.0.0.1:9229</code>. If port <code>0</code> is
specified, a random available port will be used.</p>
<p>V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug
and profile Node.js instances. The tools attach to Node.js instances via a
tcp port and communicate using the <a href="https://chromedevtools.github.io/devtools-protocol/">Chrome DevTools Protocol</a>.
See <a href="#all_debugger_v8-inspector-integration-for-nodejs">V8 Inspector integration for Node.js</a> for further explanation on Node.js debugger.</p>
<!-- Anchor to make sure old links find a target -->
<p><a id="inspector_security"></a></p>
<h5>Warning: binding inspector to a public IP:port combination is insecure<span><a class="mark" href="#all_cli_warning-binding-inspector-to-a-public-ipport-combination-is-insecure" id="all_cli_warning-binding-inspector-to-a-public-ipport-combination-is-insecure">#</a></span><a aria-hidden="true" class="legacy" id="cli_warning_binding_inspector_to_a_public_ip_port_combination_is_insecure"></a></h5>
<p>Binding the inspector to a public IP (including <code>0.0.0.0</code>) with an open port is
insecure, as it allows external hosts to connect to the inspector and perform
a <a href="https://www.owasp.org/index.php/Code_Injection">remote code execution</a> attack.</p>
<p>If specifying a host, make sure that either:</p>
<ul>
<li>The host is not accessible from public networks.</li>
<li>A firewall disallows unwanted connections on the port.</li>
</ul>
<p><strong>More specifically, <code>--inspect=0.0.0.0</code> is insecure if the port (<code>9229</code> by
default) is not firewall-protected.</strong></p>
<p>See the <a href="https://nodejs.org/en/docs/guides/debugging-getting-started/#security-implications">debugging security implications</a> section for more information.</p>
<h4><code>--inspect-brk[=[host:]port]</code><span><a class="mark" href="#all_cli_--inspect-brkhostport" id="all_cli_--inspect-brkhostport">#</a></span><a aria-hidden="true" class="legacy" id="cli_inspect_brk_host_port"></a></h4>
<div class="api_metadata">
<span>Added in: v7.6.0</span>
</div>
<p>Activate inspector on <code>host:port</code> and break at start of user script.
Default <code>host:port</code> is <code>127.0.0.1:9229</code>. If port <code>0</code> is specified,
a random available port will be used.</p>
<p>See <a href="#all_debugger_v8-inspector-integration-for-nodejs">V8 Inspector integration for Node.js</a> for further explanation on Node.js debugger.</p>
<h4><code>--inspect-port=[host:]port</code><span><a class="mark" href="#all_cli_--inspect-porthostport" id="all_cli_--inspect-porthostport">#</a></span><a aria-hidden="true" class="legacy" id="cli_inspect_port_host_port"></a></h4>
<div class="api_metadata">
<span>Added in: v7.6.0</span>
</div>
<p>Set the <code>host:port</code> to be used when the inspector is activated.
Useful when activating the inspector by sending the <code>SIGUSR1</code> signal.</p>
<p>Default host is <code>127.0.0.1</code>. If port <code>0</code> is specified,
a random available port will be used.</p>
<p>See the <a href="#all_cli_warning-binding-inspector-to-a-public-ipport-combination-is-insecure">security warning</a> below regarding the <code>host</code>
parameter usage.</p>
<h4><code>--inspect-publish-uid=stderr,http</code><span><a class="mark" href="#all_cli_--inspect-publish-uidstderrhttp" id="all_cli_--inspect-publish-uidstderrhttp">#</a></span><a aria-hidden="true" class="legacy" id="cli_inspect_publish_uid_stderr_http"></a></h4>
<p>Specify ways of the inspector web socket url exposure.</p>
<p>By default inspector websocket url is available in stderr and under <code>/json/list</code>
endpoint on <code>http://host:port/json/list</code>.</p>
<h4><code>--inspect-wait[=[host:]port]</code><span><a class="mark" href="#all_cli_--inspect-waithostport" id="all_cli_--inspect-waithostport">#</a></span><a aria-hidden="true" class="legacy" id="cli_inspect_wait_host_port"></a></h4>
<div class="api_metadata">
<span>Added in: v20.15.0</span>
</div>
<p>Activate inspector on <code>host:port</code> and wait for debugger to be attached.
Default <code>host:port</code> is <code>127.0.0.1:9229</code>. If port <code>0</code> is specified,
a random available port will be used.</p>
<p>See <a href="#all_debugger_v8-inspector-integration-for-nodejs">V8 Inspector integration for Node.js</a> for further explanation on Node.js debugger.</p>
<h4><code>-i</code>, <code>--interactive</code><span><a class="mark" href="#all_cli_-i---interactive" id="all_cli_-i---interactive">#</a></span><a aria-hidden="true" class="legacy" id="cli_i_interactive"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<p>Opens the REPL even if stdin does not appear to be a terminal.</p>
<h4><code>--jitless</code><span><a class="mark" href="#all_cli_--jitless" id="all_cli_--jitless">#</a></span><a aria-hidden="true" class="legacy" id="cli_jitless"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. This flag is inherited from V8 and is subject to
change upstream.</div><p></p>
<p>Disable <a href="https://v8.dev/blog/jitless">runtime allocation of executable memory</a>. This may be
required on some platforms for security reasons. It can also reduce attack
surface on other platforms, but the performance impact may be severe.</p>
<h4><code>--max-http-header-size=size</code><span><a class="mark" href="#all_cli_--max-http-header-sizesize" id="all_cli_--max-http-header-sizesize">#</a></span><a aria-hidden="true" class="legacy" id="cli_max_http_header_size_size"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.13.0</td>
<td><p>Change maximum default size of HTTP headers from 8 KiB to 16 KiB.</p></td></tr>
<tr><td>v11.6.0, v10.15.0</td>
<td><p><span>Added in: v11.6.0, v10.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Specify the maximum size, in bytes, of HTTP headers. Defaults to 16 KiB.</p>
<h4><code>--napi-modules</code><span><a class="mark" href="#all_cli_--napi-modules" id="all_cli_--napi-modules">#</a></span><a aria-hidden="true" class="legacy" id="cli_napi_modules"></a></h4>
<div class="api_metadata">
<span>Added in: v7.10.0</span>
</div>
<p>This option is a no-op. It is kept for compatibility.</p>
<h4><code>--network-family-autoselection-attempt-timeout</code><span><a class="mark" href="#all_cli_--network-family-autoselection-attempt-timeout" id="all_cli_--network-family-autoselection-attempt-timeout">#</a></span><a aria-hidden="true" class="legacy" id="cli_network_family_autoselection_attempt_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p>Sets the default value for the network family autoselection attempt timeout.
For more information, see <a href="#all_net_netgetdefaultautoselectfamilyattempttimeout"><code>net.getDefaultAutoSelectFamilyAttemptTimeout()</code></a>.</p>
<h4><code>--no-addons</code><span><a class="mark" href="#all_cli_--no-addons" id="all_cli_--no-addons">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_addons"></a></h4>
<div class="api_metadata">
<span>Added in: v16.10.0, v14.19.0</span>
</div>
<p>Disable the <code>node-addons</code> exports condition as well as disable loading
native addons. When <code>--no-addons</code> is specified, calling <code>process.dlopen</code> or
requiring a native C++ addon will fail and throw an exception.</p>
<h4><code>--no-deprecation</code><span><a class="mark" href="#all_cli_--no-deprecation" id="all_cli_--no-deprecation">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_deprecation"></a></h4>
<div class="api_metadata">
<span>Added in: v0.8.0</span>
</div>
<p>Silence deprecation warnings.</p>
<h4><code>--no-experimental-detect-module</code><span><a class="mark" href="#all_cli_--no-experimental-detect-module" id="all_cli_--no-experimental-detect-module">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_experimental_detect_module"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.19.0</td>
<td><p>Syntax detection is enabled by default.</p></td></tr>
<tr><td>v21.1.0, v20.10.0</td>
<td><p><span>Added in: v21.1.0, v20.10.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Disable using <a href="#all_packages_syntax-detection">syntax detection</a> to determine module type.</p>
<h4><code>--no-experimental-fetch</code><span><a class="mark" href="#all_cli_--no-experimental-fetch" id="all_cli_--no-experimental-fetch">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_experimental_fetch"></a></h4>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p>Disable experimental support for the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch API</a>.</p>
<h4><code>--no-experimental-global-customevent</code><span><a class="mark" href="#all_cli_--no-experimental-global-customevent" id="all_cli_--no-experimental-global-customevent">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_experimental_global_customevent"></a></h4>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<p>Disable exposition of <a href="https://dom.spec.whatwg.org/#customevent">CustomEvent Web API</a> on the global scope.</p>
<h4><code>--no-experimental-global-webcrypto</code><span><a class="mark" href="#all_cli_--no-experimental-global-webcrypto" id="all_cli_--no-experimental-global-webcrypto">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_experimental_global_webcrypto"></a></h4>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<p>Disable exposition of <a href="webcrypto.html">Web Crypto API</a> on the global scope.</p>
<h4><code>--no-experimental-repl-await</code><span><a class="mark" href="#all_cli_--no-experimental-repl-await" id="all_cli_--no-experimental-repl-await">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_experimental_repl_await"></a></h4>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<p>Use this flag to disable top-level await in REPL.</p>
<h4><code>--no-experimental-require-module</code><span><a class="mark" href="#all_cli_--no-experimental-require-module" id="all_cli_--no-experimental-require-module">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_experimental_require_module"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.19.0</td>
<td><p>This is now false by default.</p></td></tr>
<tr><td>v22.0.0, v20.17.0</td>
<td><p><span>Added in: v22.0.0, v20.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active Development</div><p></p>
<p>Disable support for loading a synchronous ES module graph in <code>require()</code>.</p>
<p>See <a href="#all_modules_loading-ecmascript-modules-using-require">Loading ECMAScript modules using <code>require()</code></a>.</p>
<h4><code>--no-extra-info-on-fatal-exception</code><span><a class="mark" href="#all_cli_--no-extra-info-on-fatal-exception" id="all_cli_--no-extra-info-on-fatal-exception">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_extra_info_on_fatal_exception"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p>Hide extra information on fatal exception that causes exit.</p>
<h4><code>--no-force-async-hooks-checks</code><span><a class="mark" href="#all_cli_--no-force-async-hooks-checks" id="all_cli_--no-force-async-hooks-checks">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_force_async_hooks_checks"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span>
</div>
<p>Disables runtime checks for <code>async_hooks</code>. These will still be enabled
dynamically when <code>async_hooks</code> is enabled.</p>
<h4><code>--no-global-search-paths</code><span><a class="mark" href="#all_cli_--no-global-search-paths" id="all_cli_--no-global-search-paths">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_global_search_paths"></a></h4>
<div class="api_metadata">
<span>Added in: v16.10.0</span>
</div>
<p>Do not search modules from global paths like <code>$HOME/.node_modules</code> and
<code>$NODE_PATH</code>.</p>
<h4><code>--no-network-family-autoselection</code><span><a class="mark" href="#all_cli_--no-network-family-autoselection" id="all_cli_--no-network-family-autoselection">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_network_family_autoselection"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The flag was renamed from <code>--no-enable-network-family-autoselection</code> to <code>--no-network-family-autoselection</code>. The old name can still work as an alias.</p></td></tr>
<tr><td>v19.4.0</td>
<td><p><span>Added in: v19.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Disables the family autoselection algorithm unless connection options explicitly
enables it.</p>
<h4><code>--no-warnings</code><span><a class="mark" href="#all_cli_--no-warnings" id="all_cli_--no-warnings">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_warnings"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<p>Silence all process warnings (including deprecations).</p>
<h4><code>--node-memory-debug</code><span><a class="mark" href="#all_cli_--node-memory-debug" id="all_cli_--node-memory-debug">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_memory_debug"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<p>Enable extra debug checks for memory leaks in Node.js internals. This is
usually only useful for developers debugging Node.js itself.</p>
<h4><code>--openssl-config=file</code><span><a class="mark" href="#all_cli_--openssl-configfile" id="all_cli_--openssl-configfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_openssl_config_file"></a></h4>
<div class="api_metadata">
<span>Added in: v6.9.0</span>
</div>
<p>Load an OpenSSL configuration file on startup. Among other uses, this can be
used to enable FIPS-compliant crypto if Node.js is built
against FIPS-enabled OpenSSL.</p>
<h4><code>--openssl-legacy-provider</code><span><a class="mark" href="#all_cli_--openssl-legacy-provider" id="all_cli_--openssl-legacy-provider">#</a></span><a aria-hidden="true" class="legacy" id="cli_openssl_legacy_provider"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0, v16.17.0</span>
</div>
<p>Enable OpenSSL 3.0 legacy provider. For more information please see
<a href="https://www.openssl.org/docs/man3.0/man7/OSSL_PROVIDER-legacy.html">OSSL_PROVIDER-legacy</a>.</p>
<h4><code>--openssl-shared-config</code><span><a class="mark" href="#all_cli_--openssl-shared-config" id="all_cli_--openssl-shared-config">#</a></span><a aria-hidden="true" class="legacy" id="cli_openssl_shared_config"></a></h4>
<div class="api_metadata">
<span>Added in: v18.5.0, v16.17.0, v14.21.0</span>
</div>
<p>Enable OpenSSL default configuration section, <code>openssl_conf</code> to be read from
the OpenSSL configuration file. The default configuration file is named
<code>openssl.cnf</code> but this can be changed using the environment variable
<code>OPENSSL_CONF</code>, or by using the command line option <code>--openssl-config</code>.
The location of the default OpenSSL configuration file depends on how OpenSSL
is being linked to Node.js. Sharing the OpenSSL configuration may have unwanted
implications and it is recommended to use a configuration section specific to
Node.js which is <code>nodejs_conf</code> and is default when this option is not used.</p>
<h4><code>--env-file-if-exists=config</code><span><a class="mark" href="#all_cli_--env-file-if-existsconfig" id="all_cli_--env-file-if-existsconfig">#</a></span><a aria-hidden="true" class="legacy" id="cli_env_file_if_exists_config"></a></h4>
<div class="api_metadata">
<span>Added in: v20.19.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>Behavior is the same as <a href="#all_cli_--env-fileconfig"><code>--env-file</code></a>, but an error is not thrown if the file
does not exist.</p>
<h4><code>--pending-deprecation</code><span><a class="mark" href="#all_cli_--pending-deprecation" id="all_cli_--pending-deprecation">#</a></span><a aria-hidden="true" class="legacy" id="cli_pending_deprecation"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Emit pending deprecation warnings.</p>
<p>Pending deprecations are generally identical to a runtime deprecation with the
notable exception that they are turned <em>off</em> by default and will not be emitted
unless either the <code>--pending-deprecation</code> command-line flag, or the
<code>NODE_PENDING_DEPRECATION=1</code> environment variable, is set. Pending deprecations
are used to provide a kind of selective "early warning" mechanism that
developers may leverage to detect deprecated API usage.</p>
<h4><code>--policy-integrity=sri</code><span><a class="mark" href="#all_cli_--policy-integritysri" id="all_cli_--policy-integritysri">#</a></span><a aria-hidden="true" class="legacy" id="cli_policy_integrity_sri"></a></h4>
<div class="api_metadata">
<span>Added in: v12.7.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Will be removed shortly.</div><p></p>
<p>Instructs Node.js to error prior to running any code if the policy does not have
the specified integrity. It expects a <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity">Subresource Integrity</a> string as a
parameter.</p>
<h4><code>--preserve-symlinks</code><span><a class="mark" href="#all_cli_--preserve-symlinks" id="all_cli_--preserve-symlinks">#</a></span><a aria-hidden="true" class="legacy" id="cli_preserve_symlinks"></a></h4>
<div class="api_metadata">
<span>Added in: v6.3.0</span>
</div>
<p>Instructs the module loader to preserve symbolic links when resolving and
caching modules.</p>
<p>By default, when Node.js loads a module from a path that is symbolically linked
to a different on-disk location, Node.js will dereference the link and use the
actual on-disk "real path" of the module as both an identifier and as a root
path to locate other dependency modules. In most cases, this default behavior
is acceptable. However, when using symbolically linked peer dependencies, as
illustrated in the example below, the default behavior causes an exception to
be thrown if <code>moduleA</code> attempts to require <code>moduleB</code> as a peer dependency:</p>
<pre><code class="language-text">{appDir}
├── app
│ ├── index.js
│ └── node_modules
│ ├── moduleA -> {appDir}/moduleA
│ └── moduleB
│ ├── index.js
│ └── package.json
└── moduleA
├── index.js
└── package.json</code> <button class="copy-button">copy</button></pre>
<p>The <code>--preserve-symlinks</code> command-line flag instructs Node.js to use the
symlink path for modules as opposed to the real path, allowing symbolically
linked peer dependencies to be found.</p>
<p>Note, however, that using <code>--preserve-symlinks</code> can have other side effects.
Specifically, symbolically linked <em>native</em> modules can fail to load if those
are linked from more than one location in the dependency tree (Node.js would
see those as two separate modules and would attempt to load the module multiple
times, causing an exception to be thrown).</p>
<p>The <code>--preserve-symlinks</code> flag does not apply to the main module, which allows
<code>node --preserve-symlinks node_module/.bin/<foo></code> to work. To apply the same
behavior for the main module, also use <code>--preserve-symlinks-main</code>.</p>
<h4><code>--preserve-symlinks-main</code><span><a class="mark" href="#all_cli_--preserve-symlinks-main" id="all_cli_--preserve-symlinks-main">#</a></span><a aria-hidden="true" class="legacy" id="cli_preserve_symlinks_main"></a></h4>
<div class="api_metadata">
<span>Added in: v10.2.0</span>
</div>
<p>Instructs the module loader to preserve symbolic links when resolving and
caching the main module (<code>require.main</code>).</p>
<p>This flag exists so that the main module can be opted-in to the same behavior
that <code>--preserve-symlinks</code> gives to all other imports; they are separate flags,
however, for backward compatibility with older Node.js versions.</p>
<p><code>--preserve-symlinks-main</code> does not imply <code>--preserve-symlinks</code>; use
<code>--preserve-symlinks-main</code> in addition to
<code>--preserve-symlinks</code> when it is not desirable to follow symlinks before
resolving relative paths.</p>
<p>See <a href="#all_cli_--preserve-symlinks"><code>--preserve-symlinks</code></a> for more information.</p>
<h4><code>-p</code>, <code>--print "script"</code><span><a class="mark" href="#all_cli_-p---print-script" id="all_cli_-p---print-script">#</a></span><a aria-hidden="true" class="legacy" id="cli_p_print_script"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.11.0</td>
<td><p>Built-in libraries are now available as predefined variables.</p></td></tr>
<tr><td>v0.6.4</td>
<td><p><span>Added in: v0.6.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Identical to <code>-e</code> but prints the result.</p>
<h4><code>--experimental-print-required-tla</code><span><a class="mark" href="#all_cli_--experimental-print-required-tla" id="all_cli_--experimental-print-required-tla">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_print_required_tla"></a></h4>
<div class="api_metadata">
<span>Added in: v20.17.0</span>
</div>
<p>If the ES module being <code>require()</code>'d contains top-level <code>await</code>, this flag
allows Node.js to evaluate the module, try to locate the
top-level awaits, and print their location to help users find them.</p>
<h4><code>--prof</code><span><a class="mark" href="#all_cli_--prof" id="all_cli_--prof">#</a></span><a aria-hidden="true" class="legacy" id="cli_prof"></a></h4>
<div class="api_metadata">
<span>Added in: v2.0.0</span>
</div>
<p>Generate V8 profiler output.</p>
<h4><code>--prof-process</code><span><a class="mark" href="#all_cli_--prof-process" id="all_cli_--prof-process">#</a></span><a aria-hidden="true" class="legacy" id="cli_prof_process"></a></h4>
<div class="api_metadata">
<span>Added in: v5.2.0</span>
</div>
<p>Process V8 profiler output generated using the V8 option <code>--prof</code>.</p>
<h4><code>--redirect-warnings=file</code><span><a class="mark" href="#all_cli_--redirect-warningsfile" id="all_cli_--redirect-warningsfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_redirect_warnings_file"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Write process warnings to the given file instead of printing to stderr. The
file will be created if it does not exist, and will be appended to if it does.
If an error occurs while attempting to write the warning to the file, the
warning will be written to stderr instead.</p>
<p>The <code>file</code> name may be an absolute path. If it is not, the default directory it
will be written to is controlled by the
<a href="#all_cli_--diagnostic-dirdirectory"><code>--diagnostic-dir</code></a> command-line option.</p>
<h4><code>--report-compact</code><span><a class="mark" href="#all_cli_--report-compact" id="all_cli_--report-compact">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_compact"></a></h4>
<div class="api_metadata">
<span>Added in: v13.12.0, v12.17.0</span>
</div>
<p>Write reports in a compact format, single-line JSON, more easily consumable
by log processing systems than the default multi-line format designed for
human consumption.</p>
<h4><code>--report-dir=directory</code>, <code>report-directory=directory</code><span><a class="mark" href="#all_cli_--report-dirdirectory-report-directorydirectory" id="all_cli_--report-dirdirectory-report-directorydirectory">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_dir_directory_report_directory_directory"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This option is no longer experimental.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Changed from <code>--diagnostic-report-directory</code> to <code>--report-directory</code>.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Location at which the report will be generated.</p>
<h4><code>--report-filename=filename</code><span><a class="mark" href="#all_cli_--report-filenamefilename" id="all_cli_--report-filenamefilename">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_filename_filename"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This option is no longer experimental.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>changed from <code>--diagnostic-report-filename</code> to <code>--report-filename</code>.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Name of the file to which the report will be written.</p>
<p>If the filename is set to <code>'stdout'</code> or <code>'stderr'</code>, the report is written to
the stdout or stderr of the process respectively.</p>
<h4><code>--report-on-fatalerror</code><span><a class="mark" href="#all_cli_--report-on-fatalerror" id="all_cli_--report-on-fatalerror">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_on_fatalerror"></a></h4>
<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, v13.14.0, v12.17.0</td>
<td><p>This option is no longer experimental.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>changed from <code>--diagnostic-report-on-fatalerror</code> to <code>--report-on-fatalerror</code>.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enables the report to be triggered on fatal errors (internal errors within
the Node.js runtime such as out of memory) that lead to termination of the
application. Useful to inspect various diagnostic data elements such as heap,
stack, event loop state, resource consumption etc. to reason about the fatal
error.</p>
<h4><code>--report-on-signal</code><span><a class="mark" href="#all_cli_--report-on-signal" id="all_cli_--report-on-signal">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_on_signal"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This option is no longer experimental.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>changed from <code>--diagnostic-report-on-signal</code> to <code>--report-on-signal</code>.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enables report to be generated upon receiving the specified (or predefined)
signal to the running Node.js process. The signal to trigger the report is
specified through <code>--report-signal</code>.</p>
<h4><code>--report-signal=signal</code><span><a class="mark" href="#all_cli_--report-signalsignal" id="all_cli_--report-signalsignal">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_signal_signal"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This option is no longer experimental.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>changed from <code>--diagnostic-report-signal</code> to <code>--report-signal</code>.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Sets or resets the signal for report generation (not supported on Windows).
Default signal is <code>SIGUSR2</code>.</p>
<h4><code>--report-uncaught-exception</code><span><a class="mark" href="#all_cli_--report-uncaught-exception" id="all_cli_--report-uncaught-exception">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_uncaught_exception"></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.8.0, v16.18.0</td>
<td><p>Report is not generated if the uncaught exception is handled.</p></td></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This option is no longer experimental.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>changed from <code>--diagnostic-report-uncaught-exception</code> to <code>--report-uncaught-exception</code>.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enables report to be generated when the process exits due to an uncaught
exception. Useful when inspecting the JavaScript stack in conjunction with
native stack and other runtime environment data.</p>
<h4><code>--report-exclude-network</code><span><a class="mark" href="#all_cli_--report-exclude-network" id="all_cli_--report-exclude-network">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_exclude_network"></a></h4>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p>Exclude <code>header.networkInterfaces</code> from the diagnostic report. By default
this is not set and the network interfaces are included.</p>
<h4><code>-r</code>, <code>--require module</code><span><a class="mark" href="#all_cli_-r---require-module" id="all_cli_-r---require-module">#</a></span><a aria-hidden="true" class="legacy" id="cli_r_require_module"></a></h4>
<div class="api_metadata">
<span>Added in: v1.6.0</span>
</div>
<p>Preload the specified module at startup.</p>
<p>Follows <code>require()</code>'s module resolution
rules. <code>module</code> may be either a path to a file, or a node module name.</p>
<p>Only CommonJS modules are supported.
Use <a href="#all_cli_--importmodule"><code>--import</code></a> to preload an <a href="#all_esm_modules-ecmascript-modules">ECMAScript module</a>.
Modules preloaded with <code>--require</code> will run before modules preloaded with <code>--import</code>.</p>
<h4><code>--secure-heap=n</code><span><a class="mark" href="#all_cli_--secure-heapn" id="all_cli_--secure-heapn">#</a></span><a aria-hidden="true" class="legacy" id="cli_secure_heap_n"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<p>Initializes an OpenSSL secure heap of <code>n</code> bytes. When initialized, the
secure heap is used for selected types of allocations within OpenSSL
during key generation and other operations. This is useful, for instance,
to prevent sensitive information from leaking due to pointer overruns
or underruns.</p>
<p>The secure heap is a fixed size and cannot be resized at runtime so,
if used, it is important to select a large enough heap to cover all
application uses.</p>
<p>The heap size given must be a power of two. Any value less than 2
will disable the secure heap.</p>
<p>The secure heap is disabled by default.</p>
<p>The secure heap is not available on Windows.</p>
<p>See <a href="https://www.openssl.org/docs/man3.0/man3/CRYPTO_secure_malloc_init.html"><code>CRYPTO_secure_malloc_init</code></a> for more details.</p>
<h4><code>--secure-heap-min=n</code><span><a class="mark" href="#all_cli_--secure-heap-minn" id="all_cli_--secure-heap-minn">#</a></span><a aria-hidden="true" class="legacy" id="cli_secure_heap_min_n"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<p>When using <code>--secure-heap</code>, the <code>--secure-heap-min</code> flag specifies the
minimum allocation from the secure heap. The minimum value is <code>2</code>.
The maximum value is the lesser of <code>--secure-heap</code> or <code>2147483647</code>.
The value given must be a power of two.</p>
<h4><code>--snapshot-blob=path</code><span><a class="mark" href="#all_cli_--snapshot-blobpath" id="all_cli_--snapshot-blobpath">#</a></span><a aria-hidden="true" class="legacy" id="cli_snapshot_blob_path"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>When used with <code>--build-snapshot</code>, <code>--snapshot-blob</code> specifies the path
where the generated snapshot blob is written to. If not specified, the
generated blob is written to <code>snapshot.blob</code> in the current working directory.</p>
<p>When used without <code>--build-snapshot</code>, <code>--snapshot-blob</code> specifies the
path to the blob that is used to restore the application state.</p>
<p>When loading a snapshot, Node.js checks that:</p>
<ol>
<li>The version, architecture, and platform of the running Node.js binary
are exactly the same as that of the binary that generates the snapshot.</li>
<li>The V8 flags and CPU features are compatible with that of the binary
that generates the snapshot.</li>
</ol>
<p>If they don't match, Node.js refuses to load the snapshot and exits with
status code 1.</p>
<h4><code>--test</code><span><a class="mark" href="#all_cli_--test" id="all_cli_--test">#</a></span><a aria-hidden="true" class="legacy" id="cli_test"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The test runner is now stable.</p></td></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p>Test runner now supports running in watch mode.</p></td></tr>
<tr><td>v18.1.0, v16.17.0</td>
<td><p><span>Added in: v18.1.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Starts the Node.js command line test runner. This flag cannot be combined with
<code>--watch-path</code>, <code>--check</code>, <code>--eval</code>, <code>--interactive</code>, or the inspector.
See the documentation on <a href="#all_test_running-tests-from-the-command-line">running tests from the command line</a>
for more details.</p>
<h4><code>--test-concurrency</code><span><a class="mark" href="#all_cli_--test-concurrency" id="all_cli_--test-concurrency">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_concurrency"></a></h4>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p>The maximum number of test files that the test runner CLI will execute
concurrently. The default value is <code>os.availableParallelism() - 1</code>.</p>
<h4><code>--test-coverage-exclude</code><span><a class="mark" href="#all_cli_--test-coverage-exclude" id="all_cli_--test-coverage-exclude">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_coverage_exclude"></a></h4>
<div class="api_metadata">
<span>Added in: v22.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Excludes specific files from code coverage using a glob pattern, which can match
both absolute and relative file paths.</p>
<p>This option may be specified multiple times to exclude multiple glob patterns.</p>
<p>If both <code>--test-coverage-exclude</code> and <code>--test-coverage-include</code> are provided,
files must meet <strong>both</strong> criteria to be included in the coverage report.</p>
<h4><code>--test-coverage-include</code><span><a class="mark" href="#all_cli_--test-coverage-include" id="all_cli_--test-coverage-include">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_coverage_include"></a></h4>
<div class="api_metadata">
<span>Added in: v22.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Includes specific files in code coverage using a glob pattern, which can match
both absolute and relative file paths.</p>
<p>This option may be specified multiple times to include multiple glob patterns.</p>
<p>If both <code>--test-coverage-exclude</code> and <code>--test-coverage-include</code> are provided,
files must meet <strong>both</strong> criteria to be included in the coverage report.</p>
<h4><code>--test-force-exit</code><span><a class="mark" href="#all_cli_--test-force-exit" id="all_cli_--test-force-exit">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_force_exit"></a></h4>
<div class="api_metadata">
<span>Added in: v20.14.0</span>
</div>
<p>Configures the test runner to exit the process once all known tests have
finished executing even if the event loop would otherwise remain active.</p>
<h4><code>--test-name-pattern</code><span><a class="mark" href="#all_cli_--test-name-pattern" id="all_cli_--test-name-pattern">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_name_pattern"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The test runner is now stable.</p></td></tr>
<tr><td>v18.11.0</td>
<td><p><span>Added in: v18.11.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>A regular expression that configures the test runner to only execute tests
whose name matches the provided pattern. See the documentation on
<a href="#all_test_filtering-tests-by-name">filtering tests by name</a> for more details.</p>
<h4><code>--test-only</code><span><a class="mark" href="#all_cli_--test-only" id="all_cli_--test-only">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_only"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The test runner is now stable.</p></td></tr>
<tr><td>v18.0.0, v16.17.0</td>
<td><p><span>Added in: v18.0.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Configures the test runner to only execute top level tests that have the <code>only</code>
option set.</p>
<h4><code>--test-reporter</code><span><a class="mark" href="#all_cli_--test-reporter" id="all_cli_--test-reporter">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_reporter"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The test runner is now stable.</p></td></tr>
<tr><td>v19.6.0, v18.15.0</td>
<td><p><span>Added in: v19.6.0, v18.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>A test reporter to use when running tests. See the documentation on
<a href="#all_test_test-reporters">test reporters</a> for more details.</p>
<h4><code>--test-reporter-destination</code><span><a class="mark" href="#all_cli_--test-reporter-destination" id="all_cli_--test-reporter-destination">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_reporter_destination"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The test runner is now stable.</p></td></tr>
<tr><td>v19.6.0, v18.15.0</td>
<td><p><span>Added in: v19.6.0, v18.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The destination for the corresponding test reporter. See the documentation on
<a href="#all_test_test-reporters">test reporters</a> for more details.</p>
<h4><code>--test-shard</code><span><a class="mark" href="#all_cli_--test-shard" id="all_cli_--test-shard">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_shard"></a></h4>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p>Test suite shard to execute in a format of <code><index>/<total></code>, where</p>
<p><code>index</code> is a positive integer, index of divided parts
<code>total</code> is a positive integer, total of divided part
This command will divide all tests files into <code>total</code> equal parts,
and will run only those that happen to be in an <code>index</code> part.</p>
<p>For example, to split your tests suite into three parts, use this:</p>
<pre><code class="language-bash">node --<span class="hljs-built_in">test</span> --test-shard=1/3
node --<span class="hljs-built_in">test</span> --test-shard=2/3
node --<span class="hljs-built_in">test</span> --test-shard=3/3</code> <button class="copy-button">copy</button></pre>
<h4><code>--test-timeout</code><span><a class="mark" href="#all_cli_--test-timeout" id="all_cli_--test-timeout">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v20.11.0</span>
</div>
<p>A number of milliseconds the test execution will fail after. If unspecified,
subtests inherit this value from their parent. The default value is <code>Infinity</code>.</p>
<h4><code>--throw-deprecation</code><span><a class="mark" href="#all_cli_--throw-deprecation" id="all_cli_--throw-deprecation">#</a></span><a aria-hidden="true" class="legacy" id="cli_throw_deprecation"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<p>Throw errors for deprecations.</p>
<h4><code>--title=title</code><span><a class="mark" href="#all_cli_--titletitle" id="all_cli_--titletitle">#</a></span><a aria-hidden="true" class="legacy" id="cli_title_title"></a></h4>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
</div>
<p>Set <code>process.title</code> on startup.</p>
<h4><code>--tls-cipher-list=list</code><span><a class="mark" href="#all_cli_--tls-cipher-listlist" id="all_cli_--tls-cipher-listlist">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_cipher_list_list"></a></h4>
<div class="api_metadata">
<span>Added in: v4.0.0</span>
</div>
<p>Specify an alternative default TLS cipher list. Requires Node.js to be built
with crypto support (default).</p>
<h4><code>--tls-keylog=file</code><span><a class="mark" href="#all_cli_--tls-keylogfile" id="all_cli_--tls-keylogfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_keylog_file"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>Log TLS key material to a file. The key material is in NSS <code>SSLKEYLOGFILE</code>
format and can be used by software (such as Wireshark) to decrypt the TLS
traffic.</p>
<h4><code>--tls-max-v1.2</code><span><a class="mark" href="#all_cli_--tls-max-v12" id="all_cli_--tls-max-v12">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_max_v1_2"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.0</span>
</div>
<p>Set <a href="#all_tls_tlsdefault_max_version"><code>tls.DEFAULT_MAX_VERSION</code></a> to 'TLSv1.2'. Use to disable support for
TLSv1.3.</p>
<h4><code>--tls-max-v1.3</code><span><a class="mark" href="#all_cli_--tls-max-v13" id="all_cli_--tls-max-v13">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_max_v1_3"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Set default <a href="#all_tls_tlsdefault_max_version"><code>tls.DEFAULT_MAX_VERSION</code></a> to 'TLSv1.3'. Use to enable support
for TLSv1.3.</p>
<h4><code>--tls-min-v1.0</code><span><a class="mark" href="#all_cli_--tls-min-v10" id="all_cli_--tls-min-v10">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_min_v1_0"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.0</span>
</div>
<p>Set default <a href="#all_tls_tlsdefault_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a> to 'TLSv1'. Use for compatibility with
old TLS clients or servers.</p>
<h4><code>--tls-min-v1.1</code><span><a class="mark" href="#all_cli_--tls-min-v11" id="all_cli_--tls-min-v11">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_min_v1_1"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.0</span>
</div>
<p>Set default <a href="#all_tls_tlsdefault_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a> to 'TLSv1.1'. Use for compatibility
with old TLS clients or servers.</p>
<h4><code>--tls-min-v1.2</code><span><a class="mark" href="#all_cli_--tls-min-v12" id="all_cli_--tls-min-v12">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_min_v1_2"></a></h4>
<div class="api_metadata">
<span>Added in: v12.2.0, v10.20.0</span>
</div>
<p>Set default <a href="#all_tls_tlsdefault_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a> to 'TLSv1.2'. This is the default for
12.x and later, but the option is supported for compatibility with older Node.js
versions.</p>
<h4><code>--tls-min-v1.3</code><span><a class="mark" href="#all_cli_--tls-min-v13" id="all_cli_--tls-min-v13">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_min_v1_3"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Set default <a href="#all_tls_tlsdefault_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a> to 'TLSv1.3'. Use to disable support
for TLSv1.2, which is not as secure as TLSv1.3.</p>
<h4><code>--trace-atomics-wait</code><span><a class="mark" href="#all_cli_--trace-atomics-wait" id="all_cli_--trace-atomics-wait">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_atomics_wait"></a></h4>
<div class="api_metadata">
<span>Added in: v14.3.0</span><span>Deprecated since: v18.8.0, v16.18.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p>Print short summaries of calls to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/wait"><code>Atomics.wait()</code></a> to stderr.
The output could look like this:</p>
<pre><code class="language-text">(node:15701) [Thread 0] Atomics.wait(&lt;address> + 0, 1, inf) started
(node:15701) [Thread 0] Atomics.wait(&lt;address> + 0, 1, inf) did not wait because the values mismatched
(node:15701) [Thread 0] Atomics.wait(&lt;address> + 0, 0, 10) started
(node:15701) [Thread 0] Atomics.wait(&lt;address> + 0, 0, 10) timed out
(node:15701) [Thread 0] Atomics.wait(&lt;address> + 4, 0, inf) started
(node:15701) [Thread 1] Atomics.wait(&lt;address> + 4, -1, inf) started
(node:15701) [Thread 0] Atomics.wait(&lt;address> + 4, 0, inf) was woken up by another thread
(node:15701) [Thread 1] Atomics.wait(&lt;address> + 4, -1, inf) was woken up by another thread</code> <button class="copy-button">copy</button></pre>
<p>The fields here correspond to:</p>
<ul>
<li>The thread id as given by <a href="#all_worker_threads_workerthreadid"><code>worker_threads.threadId</code></a></li>
<li>The base address of the <code>SharedArrayBuffer</code> in question, as well as the
byte offset corresponding to the index passed to <code>Atomics.wait()</code></li>
<li>The expected value that was passed to <code>Atomics.wait()</code></li>
<li>The timeout passed to <code>Atomics.wait</code></li>
</ul>
<h4><code>--trace-deprecation</code><span><a class="mark" href="#all_cli_--trace-deprecation" id="all_cli_--trace-deprecation">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_deprecation"></a></h4>
<div class="api_metadata">
<span>Added in: v0.8.0</span>
</div>
<p>Print stack traces for deprecations.</p>
<h4><code>--trace-event-categories</code><span><a class="mark" href="#all_cli_--trace-event-categories" id="all_cli_--trace-event-categories">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_event_categories"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<p>A comma separated list of categories that should be traced when trace event
tracing is enabled using <code>--trace-events-enabled</code>.</p>
<h4><code>--trace-event-file-pattern</code><span><a class="mark" href="#all_cli_--trace-event-file-pattern" id="all_cli_--trace-event-file-pattern">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_event_file_pattern"></a></h4>
<div class="api_metadata">
<span>Added in: v9.8.0</span>
</div>
<p>Template string specifying the filepath for the trace event data, it
supports <code>${rotation}</code> and <code>${pid}</code>.</p>
<h4><code>--trace-events-enabled</code><span><a class="mark" href="#all_cli_--trace-events-enabled" id="all_cli_--trace-events-enabled">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_events_enabled"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<p>Enables the collection of trace event tracing information.</p>
<h4><code>--trace-exit</code><span><a class="mark" href="#all_cli_--trace-exit" id="all_cli_--trace-exit">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_exit"></a></h4>
<div class="api_metadata">
<span>Added in: v13.5.0, v12.16.0</span>
</div>
<p>Prints a stack trace whenever an environment is exited proactively,
i.e. invoking <code>process.exit()</code>.</p>
<h4><code>--trace-require-module=mode</code><span><a class="mark" href="#all_cli_--trace-require-modulemode" id="all_cli_--trace-require-modulemode">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_require_module_mode"></a></h4>
<div class="api_metadata">
<span>Added in: v20.19.0</span>
</div>
<p>Prints information about usage of <a href="#all_modules_loading-ecmascript-modules-using-require">Loading ECMAScript modules using <code>require()</code></a>.</p>
<p>When <code>mode</code> is <code>all</code>, all usage is printed. When <code>mode</code> is <code>no-node-modules</code>, usage
from the <code>node_modules</code> folder is excluded.</p>
<h4><code>--trace-sigint</code><span><a class="mark" href="#all_cli_--trace-sigint" id="all_cli_--trace-sigint">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_sigint"></a></h4>
<div class="api_metadata">
<span>Added in: v13.9.0, v12.17.0</span>
</div>
<p>Prints a stack trace on SIGINT.</p>
<h4><code>--trace-sync-io</code><span><a class="mark" href="#all_cli_--trace-sync-io" id="all_cli_--trace-sync-io">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_sync_io"></a></h4>
<div class="api_metadata">
<span>Added in: v2.1.0</span>
</div>
<p>Prints a stack trace whenever synchronous I/O is detected after the first turn
of the event loop.</p>
<h4><code>--trace-tls</code><span><a class="mark" href="#all_cli_--trace-tls" id="all_cli_--trace-tls">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_tls"></a></h4>
<div class="api_metadata">
<span>Added in: v12.2.0</span>
</div>
<p>Prints TLS packet trace information to <code>stderr</code>. This can be used to debug TLS
connection problems.</p>
<h4><code>--trace-uncaught</code><span><a class="mark" href="#all_cli_--trace-uncaught" id="all_cli_--trace-uncaught">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_uncaught"></a></h4>
<div class="api_metadata">
<span>Added in: v13.1.0</span>
</div>
<p>Print stack traces for uncaught exceptions; usually, the stack trace associated
with the creation of an <code>Error</code> is printed, whereas this makes Node.js also
print the stack trace associated with throwing the value (which does not need
to be an <code>Error</code> instance).</p>
<p>Enabling this option may affect garbage collection behavior negatively.</p>
<h4><code>--trace-warnings</code><span><a class="mark" href="#all_cli_--trace-warnings" id="all_cli_--trace-warnings">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_warnings"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<p>Print stack traces for process warnings (including deprecations).</p>
<h4><code>--track-heap-objects</code><span><a class="mark" href="#all_cli_--track-heap-objects" id="all_cli_--track-heap-objects">#</a></span><a aria-hidden="true" class="legacy" id="cli_track_heap_objects"></a></h4>
<div class="api_metadata">
<span>Added in: v2.4.0</span>
</div>
<p>Track heap object allocations for heap snapshots.</p>
<h4><code>--unhandled-rejections=mode</code><span><a class="mark" href="#all_cli_--unhandled-rejectionsmode" id="all_cli_--unhandled-rejectionsmode">#</a></span><a aria-hidden="true" class="legacy" id="cli_unhandled_rejections_mode"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Changed default mode to <code>throw</code>. Previously, a warning was emitted.</p></td></tr>
<tr><td>v12.0.0, v10.17.0</td>
<td><p><span>Added in: v12.0.0, v10.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Using this flag allows to change what should happen when an unhandled rejection
occurs. One of the following modes can be chosen:</p>
<ul>
<li><code>throw</code>: Emit <a href="#all_process_event-unhandledrejection"><code>unhandledRejection</code></a>. If this hook is not set, raise the
unhandled rejection as an uncaught exception. This is the default.</li>
<li><code>strict</code>: Raise the unhandled rejection as an uncaught exception. If the
exception is handled, <a href="#all_process_event-unhandledrejection"><code>unhandledRejection</code></a> is emitted.</li>
<li><code>warn</code>: Always trigger a warning, no matter if the <a href="#all_process_event-unhandledrejection"><code>unhandledRejection</code></a>
hook is set or not but do not print the deprecation warning.</li>
<li><code>warn-with-error-code</code>: Emit <a href="#all_process_event-unhandledrejection"><code>unhandledRejection</code></a>. If this hook is not
set, trigger a warning, and set the process exit code to 1.</li>
<li><code>none</code>: Silence all warnings.</li>
</ul>
<p>If a rejection happens during the command line entry point's ES module static
loading phase, it will always raise it as an uncaught exception.</p>
<h4><code>--use-bundled-ca</code>, <code>--use-openssl-ca</code><span><a class="mark" href="#all_cli_--use-bundled-ca---use-openssl-ca" id="all_cli_--use-bundled-ca---use-openssl-ca">#</a></span><a aria-hidden="true" class="legacy" id="cli_use_bundled_ca_use_openssl_ca"></a></h4>
<div class="api_metadata">
<span>Added in: v6.11.0</span>
</div>
<p>Use bundled Mozilla CA store as supplied by current Node.js version
or use OpenSSL's default CA store. The default store is selectable
at build-time.</p>
<p>The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store
that is fixed at release time. It is identical on all supported platforms.</p>
<p>Using OpenSSL store allows for external modifications of the store. For most
Linux and BSD distributions, this store is maintained by the distribution
maintainers and system administrators. OpenSSL CA store location is dependent on
configuration of the OpenSSL library but this can be altered at runtime using
environment variables.</p>
<p>See <code>SSL_CERT_DIR</code> and <code>SSL_CERT_FILE</code>.</p>
<h4><code>--use-largepages=mode</code><span><a class="mark" href="#all_cli_--use-largepagesmode" id="all_cli_--use-largepagesmode">#</a></span><a aria-hidden="true" class="legacy" id="cli_use_largepages_mode"></a></h4>
<div class="api_metadata">
<span>Added in: v13.6.0, v12.17.0</span>
</div>
<p>Re-map the Node.js static code to large memory pages at startup. If supported on
the target system, this will cause the Node.js static code to be moved onto 2
MiB pages instead of 4 KiB pages.</p>
<p>The following values are valid for <code>mode</code>:</p>
<ul>
<li><code>off</code>: No mapping will be attempted. This is the default.</li>
<li><code>on</code>: If supported by the OS, mapping will be attempted. Failure to map will
be ignored and a message will be printed to standard error.</li>
<li><code>silent</code>: If supported by the OS, mapping will be attempted. Failure to map
will be ignored and will not be reported.</li>
</ul>
<h4><code>--v8-options</code><span><a class="mark" href="#all_cli_--v8-options" id="all_cli_--v8-options">#</a></span><a aria-hidden="true" class="legacy" id="cli_v8_options"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.3</span>
</div>
<p>Print V8 command-line options.</p>
<h4><code>--v8-pool-size=num</code><span><a class="mark" href="#all_cli_--v8-pool-sizenum" id="all_cli_--v8-pool-sizenum">#</a></span><a aria-hidden="true" class="legacy" id="cli_v8_pool_size_num"></a></h4>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<p>Set V8's thread pool size which will be used to allocate background jobs.</p>
<p>If set to <code>0</code> then Node.js will choose an appropriate size of the thread pool
based on an estimate of the amount of parallelism.</p>
<p>The amount of parallelism refers to the number of computations that can be
carried out simultaneously in a given machine. In general, it's the same as the
amount of CPUs, but it may diverge in environments such as VMs or containers.</p>
<h4><code>-v</code>, <code>--version</code><span><a class="mark" href="#all_cli_-v---version" id="all_cli_-v---version">#</a></span><a aria-hidden="true" class="legacy" id="cli_v_version"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.3</span>
</div>
<p>Print node's version.</p>
<h4><code>--watch</code><span><a class="mark" href="#all_cli_--watch" id="all_cli_--watch">#</a></span><a aria-hidden="true" class="legacy" id="cli_watch"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Watch mode is now stable.</p></td></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p>Test runner now supports running in watch mode.</p></td></tr>
<tr><td>v18.11.0, v16.19.0</td>
<td><p><span>Added in: v18.11.0, v16.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Starts Node.js in watch mode.
When in watch mode, changes in the watched files cause the Node.js process to
restart.
By default, watch mode will watch the entry point
and any required or imported module.
Use <code>--watch-path</code> to specify what paths to watch.</p>
<p>This flag cannot be combined with
<code>--check</code>, <code>--eval</code>, <code>--interactive</code>, or the REPL.</p>
<pre><code class="language-bash">node --watch index.js</code> <button class="copy-button">copy</button></pre>
<h4><code>--watch-path</code><span><a class="mark" href="#all_cli_--watch-path" id="all_cli_--watch-path">#</a></span><a aria-hidden="true" class="legacy" id="cli_watch_path"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Watch mode is now stable.</p></td></tr>
<tr><td>v18.11.0, v16.19.0</td>
<td><p><span>Added in: v18.11.0, v16.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Starts Node.js in watch mode and specifies what paths to watch.
When in watch mode, changes in the watched paths cause the Node.js process to
restart.
This will turn off watching of required or imported modules, even when used in
combination with <code>--watch</code>.</p>
<p>This flag cannot be combined with
<code>--check</code>, <code>--eval</code>, <code>--interactive</code>, <code>--test</code>, or the REPL.</p>
<pre><code class="language-bash">node --watch-path=./src --watch-path=./tests index.js</code> <button class="copy-button">copy</button></pre>
<p>This option is only supported on macOS and Windows.
An <code>ERR_FEATURE_UNAVAILABLE_ON_PLATFORM</code> exception will be thrown
when the option is used on a platform that does not support it.</p>
<h4><code>--watch-preserve-output</code><span><a class="mark" href="#all_cli_--watch-preserve-output" id="all_cli_--watch-preserve-output">#</a></span><a aria-hidden="true" class="legacy" id="cli_watch_preserve_output"></a></h4>
<div class="api_metadata">
<span>Added in: v19.3.0, v18.13.0</span>
</div>
<p>Disable the clearing of the console when watch mode restarts the process.</p>
<pre><code class="language-bash">node --watch --watch-preserve-output test.js</code> <button class="copy-button">copy</button></pre>
<h4><code>--zero-fill-buffers</code><span><a class="mark" href="#all_cli_--zero-fill-buffers" id="all_cli_--zero-fill-buffers">#</a></span><a aria-hidden="true" class="legacy" id="cli_zero_fill_buffers"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<p>Automatically zero-fills all newly allocated <a href="#all_buffer_class-buffer"><code>Buffer</code></a> and <a href="#all_buffer_class-slowbuffer"><code>SlowBuffer</code></a>
instances.</p>
</section><section><h3>Environment variables<span><a class="mark" href="#all_cli_environment-variables" id="all_cli_environment-variables">#</a></span><a aria-hidden="true" class="legacy" id="cli_environment_variables"></a></h3>
<h4><code>FORCE_COLOR=[1, 2, 3]</code><span><a class="mark" href="#all_cli_force_color1-2-3" id="all_cli_force_color1-2-3">#</a></span><a aria-hidden="true" class="legacy" id="cli_force_color_1_2_3"></a></h4>
<p>The <code>FORCE_COLOR</code> environment variable is used to
enable ANSI colorized output. The value may be:</p>
<ul>
<li><code>1</code>, <code>true</code>, or the empty string <code>''</code> indicate 16-color support,</li>
<li><code>2</code> to indicate 256-color support, or</li>
<li><code>3</code> to indicate 16 million-color support.</li>
</ul>
<p>When <code>FORCE_COLOR</code> is used and set to a supported value, both the <code>NO_COLOR</code>,
and <code>NODE_DISABLE_COLORS</code> environment variables are ignored.</p>
<p>Any other value will result in colorized output being disabled.</p>
<h4><code>NO_COLOR=<any></code><span><a class="mark" href="#all_cli_no_colorany" id="all_cli_no_colorany">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_color_any"></a></h4>
<p><a href="https://no-color.org"><code>NO_COLOR</code></a> is an alias for <code>NODE_DISABLE_COLORS</code>. The value of the
environment variable is arbitrary.</p>
<h4><code>NODE_DEBUG=module[,…]</code><span><a class="mark" href="#all_cli_node_debugmodule" id="all_cli_node_debugmodule">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_debug_module"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.32</span>
</div>
<p><code>','</code>-separated list of core modules that should print debug information.</p>
<h4><code>NODE_DEBUG_NATIVE=module[,…]</code><span><a class="mark" href="#all_cli_node_debug_nativemodule" id="all_cli_node_debug_nativemodule">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_debug_native_module"></a></h4>
<p><code>','</code>-separated list of core C++ modules that should print debug information.</p>
<h4><code>NODE_DISABLE_COLORS=1</code><span><a class="mark" href="#all_cli_node_disable_colors1" id="all_cli_node_disable_colors1">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_disable_colors_1"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<p>When set, colors will not be used in the REPL.</p>
<h4><code>NODE_EXTRA_CA_CERTS=file</code><span><a class="mark" href="#all_cli_node_extra_ca_certsfile" id="all_cli_node_extra_ca_certsfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_extra_ca_certs_file"></a></h4>
<div class="api_metadata">
<span>Added in: v7.3.0</span>
</div>
<p>When set, the well known "root" CAs (like VeriSign) will be extended with the
extra certificates in <code>file</code>. The file should consist of one or more trusted
certificates in PEM format. A message will be emitted (once) with
<a href="#all_process_processemitwarningwarning-options"><code>process.emitWarning()</code></a> if the file is missing or
malformed, but any errors are otherwise ignored.</p>
<p>Neither the well known nor extra certificates are used when the <code>ca</code>
options property is explicitly specified for a TLS or HTTPS client or server.</p>
<p>This environment variable is ignored when <code>node</code> runs as setuid root or
has Linux file capabilities set.</p>
<p>The <code>NODE_EXTRA_CA_CERTS</code> environment variable is only read when the Node.js
process is first launched. Changing the value at runtime using
<code>process.env.NODE_EXTRA_CA_CERTS</code> has no effect on the current process.</p>
<h4><code>NODE_ICU_DATA=file</code><span><a class="mark" href="#all_cli_node_icu_datafile" id="all_cli_node_icu_datafile">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_icu_data_file"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</div>
<p>Data path for ICU (<code>Intl</code> object) data. Will extend linked-in data when compiled
with small-icu support.</p>
<h4><code>NODE_NO_WARNINGS=1</code><span><a class="mark" href="#all_cli_node_no_warnings1" id="all_cli_node_no_warnings1">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_no_warnings_1"></a></h4>
<div class="api_metadata">
<span>Added in: v6.11.0</span>
</div>
<p>When set to <code>1</code>, process warnings are silenced.</p>
<h4><code>NODE_OPTIONS=options...</code><span><a class="mark" href="#all_cli_node_optionsoptions" id="all_cli_node_optionsoptions">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_options_options"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>A space-separated list of command-line options. <code>options...</code> are interpreted
before command-line options, so command-line options will override or
compound after anything in <code>options...</code>. Node.js will exit with an error if
an option that is not allowed in the environment is used, such as <code>-p</code> or a
script file.</p>
<p>If an option value contains a space, it can be escaped using double quotes:</p>
<pre><code class="language-bash">NODE_OPTIONS=<span class="hljs-string">'--require "./my path/file.js"'</span></code> <button class="copy-button">copy</button></pre>
<p>A singleton flag passed as a command-line option will override the same flag
passed into <code>NODE_OPTIONS</code>:</p>
<pre><code class="language-bash"><span class="hljs-comment"># The inspector will be available on port 5555</span>
NODE_OPTIONS=<span class="hljs-string">'--inspect=localhost:4444'</span> node --inspect=localhost:5555</code> <button class="copy-button">copy</button></pre>
<p>A flag that can be passed multiple times will be treated as if its
<code>NODE_OPTIONS</code> instances were passed first, and then its command-line
instances afterwards:</p>
<pre><code class="language-bash">NODE_OPTIONS=<span class="hljs-string">'--require "./a.js"'</span> node --require <span class="hljs-string">"./b.js"</span>
<span class="hljs-comment"># is equivalent to:</span>
node --require <span class="hljs-string">"./a.js"</span> --require <span class="hljs-string">"./b.js"</span></code> <button class="copy-button">copy</button></pre>
<p>Node.js options that are allowed are in the following list. If an option
supports both --XX and --no-XX variants, they are both supported but only
one is included in the list below.</p>
<!-- node-options-node start -->
<ul>
<li><code>--allow-addons</code></li>
<li><code>--allow-child-process</code></li>
<li><code>--allow-fs-read</code></li>
<li><code>--allow-fs-write</code></li>
<li><code>--allow-wasi</code></li>
<li><code>--allow-worker</code></li>
<li><code>--conditions</code>, <code>-C</code></li>
<li><code>--diagnostic-dir</code></li>
<li><code>--disable-proto</code></li>
<li><code>--disable-warning</code></li>
<li><code>--disable-wasm-trap-handler</code></li>
<li><code>--dns-result-order</code></li>
<li><code>--enable-fips</code></li>
<li><code>--enable-network-family-autoselection</code></li>
<li><code>--enable-source-maps</code></li>
<li><code>--experimental-abortcontroller</code></li>
<li><code>--experimental-default-type</code></li>
<li><code>--experimental-detect-module</code></li>
<li><code>--experimental-eventsource</code></li>
<li><code>--experimental-import-meta-resolve</code></li>
<li><code>--experimental-json-modules</code></li>
<li><code>--experimental-loader</code></li>
<li><code>--experimental-modules</code></li>
<li><code>--experimental-network-imports</code></li>
<li><code>--experimental-permission</code></li>
<li><code>--experimental-policy</code></li>
<li><code>--experimental-print-required-tla</code></li>
<li><code>--experimental-require-module</code></li>
<li><code>--experimental-shadow-realm</code></li>
<li><code>--experimental-specifier-resolution</code></li>
<li><code>--experimental-top-level-await</code></li>
<li><code>--experimental-vm-modules</code></li>
<li><code>--experimental-wasi-unstable-preview1</code></li>
<li><code>--experimental-wasm-modules</code></li>
<li><code>--experimental-websocket</code></li>
<li><code>--force-context-aware</code></li>
<li><code>--force-fips</code></li>
<li><code>--force-node-api-uncaught-exceptions-policy</code></li>
<li><code>--frozen-intrinsics</code></li>
<li><code>--heap-prof-dir</code></li>
<li><code>--heap-prof-interval</code></li>
<li><code>--heap-prof-name</code></li>
<li><code>--heap-prof</code></li>
<li><code>--heapsnapshot-near-heap-limit</code></li>
<li><code>--heapsnapshot-signal</code></li>
<li><code>--http-parser</code></li>
<li><code>--icu-data-dir</code></li>
<li><code>--import</code></li>
<li><code>--input-type</code></li>
<li><code>--insecure-http-parser</code></li>
<li><code>--inspect-brk</code></li>
<li><code>--inspect-port</code>, <code>--debug-port</code></li>
<li><code>--inspect-publish-uid</code></li>
<li><code>--inspect-wait</code></li>
<li><code>--inspect</code></li>
<li><code>--max-http-header-size</code></li>
<li><code>--napi-modules</code></li>
<li><code>--network-family-autoselection-attempt-timeout</code></li>
<li><code>--no-addons</code></li>
<li><code>--no-deprecation</code></li>
<li><code>--no-experimental-fetch</code></li>
<li><code>--no-experimental-global-customevent</code></li>
<li><code>--no-experimental-global-webcrypto</code></li>
<li><code>--no-experimental-repl-await</code></li>
<li><code>--no-extra-info-on-fatal-exception</code></li>
<li><code>--no-force-async-hooks-checks</code></li>
<li><code>--no-global-search-paths</code></li>
<li><code>--no-network-family-autoselection</code></li>
<li><code>--no-warnings</code></li>
<li><code>--node-memory-debug</code></li>
<li><code>--openssl-config</code></li>
<li><code>--openssl-legacy-provider</code></li>
<li><code>--openssl-shared-config</code></li>
<li><code>--pending-deprecation</code></li>
<li><code>--policy-integrity</code></li>
<li><code>--preserve-symlinks-main</code></li>
<li><code>--preserve-symlinks</code></li>
<li><code>--prof-process</code></li>
<li><code>--redirect-warnings</code></li>
<li><code>--report-compact</code></li>
<li><code>--report-dir</code>, <code>--report-directory</code></li>
<li><code>--report-exclude-network</code></li>
<li><code>--report-filename</code></li>
<li><code>--report-on-fatalerror</code></li>
<li><code>--report-on-signal</code></li>
<li><code>--report-signal</code></li>
<li><code>--report-uncaught-exception</code></li>
<li><code>--require</code>, <code>-r</code></li>
<li><code>--secure-heap-min</code></li>
<li><code>--secure-heap</code></li>
<li><code>--snapshot-blob</code></li>
<li><code>--test-only</code></li>
<li><code>--test-reporter-destination</code></li>
<li><code>--test-reporter</code></li>
<li><code>--test-shard</code></li>
<li><code>--throw-deprecation</code></li>
<li><code>--title</code></li>
<li><code>--tls-cipher-list</code></li>
<li><code>--tls-keylog</code></li>
<li><code>--tls-max-v1.2</code></li>
<li><code>--tls-max-v1.3</code></li>
<li><code>--tls-min-v1.0</code></li>
<li><code>--tls-min-v1.1</code></li>
<li><code>--tls-min-v1.2</code></li>
<li><code>--tls-min-v1.3</code></li>
<li><code>--trace-atomics-wait</code></li>
<li><code>--trace-deprecation</code></li>
<li><code>--trace-event-categories</code></li>
<li><code>--trace-event-file-pattern</code></li>
<li><code>--trace-events-enabled</code></li>
<li><code>--trace-exit</code></li>
<li><code>--trace-require-module</code></li>
<li><code>--trace-sigint</code></li>
<li><code>--trace-sync-io</code></li>
<li><code>--trace-tls</code></li>
<li><code>--trace-uncaught</code></li>
<li><code>--trace-warnings</code></li>
<li><code>--track-heap-objects</code></li>
<li><code>--unhandled-rejections</code></li>
<li><code>--use-bundled-ca</code></li>
<li><code>--use-largepages</code></li>
<li><code>--use-openssl-ca</code></li>
<li><code>--v8-pool-size</code></li>
<li><code>--watch-path</code></li>
<li><code>--watch-preserve-output</code></li>
<li><code>--watch</code></li>
<li><code>--zero-fill-buffers</code></li>
</ul>
<!-- node-options-node end -->
<p>V8 options that are allowed are:</p>
<!-- node-options-v8 start -->
<ul>
<li><code>--abort-on-uncaught-exception</code></li>
<li><code>--disallow-code-generation-from-strings</code></li>
<li><code>--enable-etw-stack-walking</code></li>
<li><code>--expose-gc</code></li>
<li><code>--huge-max-old-generation-size</code></li>
<li><code>--interpreted-frames-native-stack</code></li>
<li><code>--jitless</code></li>
<li><code>--max-old-space-size</code></li>
<li><code>--max-semi-space-size</code></li>
<li><code>--perf-basic-prof-only-functions</code></li>
<li><code>--perf-basic-prof</code></li>
<li><code>--perf-prof-unwinding-info</code></li>
<li><code>--perf-prof</code></li>
<li><code>--stack-trace-limit</code></li>
</ul>
<!-- node-options-v8 end -->
<!-- node-options-others start -->
<p><code>--perf-basic-prof-only-functions</code>, <code>--perf-basic-prof</code>,
<code>--perf-prof-unwinding-info</code>, and <code>--perf-prof</code> are only available on Linux.</p>
<p><code>--enable-etw-stack-walking</code> is only available on Windows.</p>
<!-- node-options-others end -->
<h4><code>NODE_PATH=path[:…]</code><span><a class="mark" href="#all_cli_node_pathpath" id="all_cli_node_pathpath">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_path_path"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.32</span>
</div>
<p><code>':'</code>-separated list of directories prefixed to the module search path.</p>
<p>On Windows, this is a <code>';'</code>-separated list instead.</p>
<h4><code>NODE_PENDING_DEPRECATION=1</code><span><a class="mark" href="#all_cli_node_pending_deprecation1" id="all_cli_node_pending_deprecation1">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_pending_deprecation_1"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>When set to <code>1</code>, emit pending deprecation warnings.</p>
<p>Pending deprecations are generally identical to a runtime deprecation with the
notable exception that they are turned <em>off</em> by default and will not be emitted
unless either the <code>--pending-deprecation</code> command-line flag, or the
<code>NODE_PENDING_DEPRECATION=1</code> environment variable, is set. Pending deprecations
are used to provide a kind of selective "early warning" mechanism that
developers may leverage to detect deprecated API usage.</p>
<h4><code>NODE_PENDING_PIPE_INSTANCES=instances</code><span><a class="mark" href="#all_cli_node_pending_pipe_instancesinstances" id="all_cli_node_pending_pipe_instancesinstances">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_pending_pipe_instances_instances"></a></h4>
<p>Set the number of pending pipe instance handles when the pipe server is waiting
for connections. This setting applies to Windows only.</p>
<h4><code>NODE_PRESERVE_SYMLINKS=1</code><span><a class="mark" href="#all_cli_node_preserve_symlinks1" id="all_cli_node_preserve_symlinks1">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_preserve_symlinks_1"></a></h4>
<div class="api_metadata">
<span>Added in: v7.1.0</span>
</div>
<p>When set to <code>1</code>, instructs the module loader to preserve symbolic links when
resolving and caching modules.</p>
<h4><code>NODE_REDIRECT_WARNINGS=file</code><span><a class="mark" href="#all_cli_node_redirect_warningsfile" id="all_cli_node_redirect_warningsfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_redirect_warnings_file"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>When set, process warnings will be emitted to the given file instead of
printing to stderr. The file will be created if it does not exist, and will be
appended to if it does. If an error occurs while attempting to write the
warning to the file, the warning will be written to stderr instead. This is
equivalent to using the <code>--redirect-warnings=file</code> command-line flag.</p>
<h4><code>NODE_REPL_EXTERNAL_MODULE=file</code><span><a class="mark" href="#all_cli_node_repl_external_modulefile" id="all_cli_node_repl_external_modulefile">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_repl_external_module_file"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>Remove the possibility to use this env var with kDisableNodeOptionsEnv for embedders.</p></td></tr>
<tr><td>v13.0.0, v12.16.0</td>
<td><p><span>Added in: v13.0.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Path to a Node.js module which will be loaded in place of the built-in REPL.
Overriding this value to an empty string (<code>''</code>) will use the built-in REPL.</p>
<h4><code>NODE_REPL_HISTORY=file</code><span><a class="mark" href="#all_cli_node_repl_historyfile" id="all_cli_node_repl_historyfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_repl_history_file"></a></h4>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div>
<p>Path to the file used to store the persistent REPL history. The default path is
<code>~/.node_repl_history</code>, which is overridden by this variable. Setting the value
to an empty string (<code>''</code> or <code>' '</code>) disables persistent REPL history.</p>
<h4><code>NODE_SKIP_PLATFORM_CHECK=value</code><span><a class="mark" href="#all_cli_node_skip_platform_checkvalue" id="all_cli_node_skip_platform_checkvalue">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_skip_platform_check_value"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p>If <code>value</code> equals <code>'1'</code>, the check for a supported platform is skipped during
Node.js startup. Node.js might not execute correctly. Any issues encountered
on unsupported platforms will not be fixed.</p>
<h4><code>NODE_TEST_CONTEXT=value</code><span><a class="mark" href="#all_cli_node_test_contextvalue" id="all_cli_node_test_contextvalue">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_test_context_value"></a></h4>
<p>If <code>value</code> equals <code>'child'</code>, test reporter options will be overridden and test
output will be sent to stdout in the TAP format. If any other value is provided,
Node.js makes no guarantees about the reporter format used or its stability.</p>
<h4><code>NODE_TLS_REJECT_UNAUTHORIZED=value</code><span><a class="mark" href="#all_cli_node_tls_reject_unauthorizedvalue" id="all_cli_node_tls_reject_unauthorizedvalue">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_tls_reject_unauthorized_value"></a></h4>
<p>If <code>value</code> equals <code>'0'</code>, certificate validation is disabled for TLS connections.
This makes TLS, and HTTPS by extension, insecure. The use of this environment
variable is strongly discouraged.</p>
<h4><code>NODE_V8_COVERAGE=dir</code><span><a class="mark" href="#all_cli_node_v8_coveragedir" id="all_cli_node_v8_coveragedir">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_v8_coverage_dir"></a></h4>
<p>When set, Node.js will begin outputting <a href="https://v8project.blogspot.com/2017/12/javascript-code-coverage.html">V8 JavaScript code coverage</a> and
<a href="https://sourcemaps.info/spec.html">Source Map</a> data to the directory provided as an argument (coverage
information is written as JSON to files with a <code>coverage</code> prefix).</p>
<p><code>NODE_V8_COVERAGE</code> will automatically propagate to subprocesses, making it
easier to instrument applications that call the <code>child_process.spawn()</code> family
of functions. <code>NODE_V8_COVERAGE</code> can be set to an empty string, to prevent
propagation.</p>
<h5>Coverage output<span><a class="mark" href="#all_cli_coverage-output" id="all_cli_coverage-output">#</a></span><a aria-hidden="true" class="legacy" id="cli_coverage_output"></a></h5>
<p>Coverage is output as an array of <a href="https://chromedevtools.github.io/devtools-protocol/tot/Profiler#type-ScriptCoverage">ScriptCoverage</a> objects on the top-level
key <code>result</code>:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"result"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"scriptId"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"67"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"url"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"internal/tty.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"functions"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h5>Source map cache<span><a class="mark" href="#all_cli_source-map-cache" id="all_cli_source-map-cache">#</a></span><a aria-hidden="true" class="legacy" id="cli_source_map_cache"></a></h5>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>If found, source map data is appended to the top-level key <code>source-map-cache</code>
on the JSON coverage object.</p>
<p><code>source-map-cache</code> is an object with keys representing the files source maps
were extracted from, and values which include the raw source-map URL
(in the key <code>url</code>), the parsed Source Map v3 information (in the key <code>data</code>),
and the line lengths of the source file (in the key <code>lineLengths</code>).</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"result"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"scriptId"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"68"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"url"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"file:///absolute/path/to/source.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"functions"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"source-map-cache"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"file:///absolute/path/to/source.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"url"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./path-to-map.json"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"data"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"version"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-string">"file:///absolute/path/to/original.js"</span>
<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"names"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-string">"Foo"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"console"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"info"</span>
<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"mappings"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"MAAMA,IACJC,YAAaC"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"sourceRoot"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"lineLengths"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-number">13</span><span class="hljs-punctuation">,</span>
<span class="hljs-number">62</span><span class="hljs-punctuation">,</span>
<span class="hljs-number">38</span><span class="hljs-punctuation">,</span>
<span class="hljs-number">27</span>
<span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h4><code>OPENSSL_CONF=file</code><span><a class="mark" href="#all_cli_openssl_conffile" id="all_cli_openssl_conffile">#</a></span><a aria-hidden="true" class="legacy" id="cli_openssl_conf_file"></a></h4>
<div class="api_metadata">
<span>Added in: v6.11.0</span>
</div>
<p>Load an OpenSSL configuration file on startup. Among other uses, this can be
used to enable FIPS-compliant crypto if Node.js is built with
<code>./configure --openssl-fips</code>.</p>
<p>If the <a href="#all_cli_--openssl-configfile"><code>--openssl-config</code></a> command-line option is used, the environment
variable is ignored.</p>
<h4><code>SSL_CERT_DIR=dir</code><span><a class="mark" href="#all_cli_ssl_cert_dirdir" id="all_cli_ssl_cert_dirdir">#</a></span><a aria-hidden="true" class="legacy" id="cli_ssl_cert_dir_dir"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<p>If <code>--use-openssl-ca</code> is enabled, this overrides and sets OpenSSL's directory
containing trusted certificates.</p>
<p>Be aware that unless the child environment is explicitly set, this environment
variable will be inherited by any child processes, and if they use OpenSSL, it
may cause them to trust the same CAs as node.</p>
<h4><code>SSL_CERT_FILE=file</code><span><a class="mark" href="#all_cli_ssl_cert_filefile" id="all_cli_ssl_cert_filefile">#</a></span><a aria-hidden="true" class="legacy" id="cli_ssl_cert_file_file"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<p>If <code>--use-openssl-ca</code> is enabled, this overrides and sets OpenSSL's file
containing trusted certificates.</p>
<p>Be aware that unless the child environment is explicitly set, this environment
variable will be inherited by any child processes, and if they use OpenSSL, it
may cause them to trust the same CAs as node.</p>
<h4><code>TZ</code><span><a class="mark" href="#all_cli_tz" id="all_cli_tz">#</a></span><a aria-hidden="true" class="legacy" id="cli_tz"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.2.0</td>
<td><p>Changing the TZ variable using process.env.TZ = changes the timezone on Windows as well.</p></td></tr>
<tr><td>v13.0.0</td>
<td><p>Changing the TZ variable using process.env.TZ = changes the timezone on POSIX systems.</p></td></tr>
<tr><td>v0.0.1</td>
<td><p><span>Added in: v0.0.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>TZ</code> environment variable is used to specify the timezone configuration.</p>
<p>While Node.js does not support all of the various <a href="https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html">ways that <code>TZ</code> is handled in
other environments</a>, it does support basic <a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">timezone IDs</a> (such as
<code>'Etc/UTC'</code>, <code>'Europe/Paris'</code>, or <code>'America/New_York'</code>).
It may support a few other abbreviations or aliases, but these are strongly
discouraged and not guaranteed.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">TZ=Europe/Dublin node -pe <span class="hljs-string">"new Date().toString()"</span></span>
Wed May 12 2021 20:30:48 GMT+0100 (Irish Standard Time)</code> <button class="copy-button">copy</button></pre>
<h4><code>UV_THREADPOOL_SIZE=size</code><span><a class="mark" href="#all_cli_uv_threadpool_sizesize" id="all_cli_uv_threadpool_sizesize">#</a></span><a aria-hidden="true" class="legacy" id="cli_uv_threadpool_size_size"></a></h4>
<p>Set the number of threads used in libuv's threadpool to <code>size</code> threads.</p>
<p>Asynchronous system APIs are used by Node.js whenever possible, but where they
do not exist, libuv's threadpool is used to create asynchronous node APIs based
on synchronous system APIs. Node.js APIs that use the threadpool are:</p>
<ul>
<li>all <code>fs</code> APIs, other than the file watcher APIs and those that are explicitly
synchronous</li>
<li>asynchronous crypto APIs such as <code>crypto.pbkdf2()</code>, <code>crypto.scrypt()</code>,
<code>crypto.randomBytes()</code>, <code>crypto.randomFill()</code>, <code>crypto.generateKeyPair()</code></li>
<li><code>dns.lookup()</code></li>
<li>all <code>zlib</code> APIs, other than those that are explicitly synchronous</li>
</ul>
<p>Because libuv's threadpool has a fixed size, it means that if for whatever
reason any of these APIs takes a long time, other (seemingly unrelated) APIs
that run in libuv's threadpool will experience degraded performance. In order to
mitigate this issue, one potential solution is to increase the size of libuv's
threadpool by setting the <code>'UV_THREADPOOL_SIZE'</code> environment variable to a value
greater than <code>4</code> (its current default value). However, setting this from inside
the process using <code>process.env.UV_THREADPOOL_SIZE=size</code> is not guranteed to work
as the threadpool would have been created as part of the runtime initialisation
much before user code is run. For more information, see the <a href="https://docs.libuv.org/en/latest/threadpool.html">libuv threadpool documentation</a>.</p>
<h4><code>UV_USE_IO_URING=value</code><span><a class="mark" href="#all_cli_uv_use_io_uringvalue" id="all_cli_uv_use_io_uringvalue">#</a></span><a aria-hidden="true" class="legacy" id="cli_uv_use_io_uring_value"></a></h4>
<p>Enable or disable libuv's use of <code>io_uring</code> on supported platforms.</p>
<p>On supported platforms, <code>io_uring</code> can significantly improve the performance of
various asynchronous I/O operations.</p>
<p><code>io_uring</code> is disabled by default due to security concerns. When <code>io_uring</code>
is enabled, applications must not change the user identity of the process at
runtime. In this case, JavaScript functions such as <a href="#all_process_processsetuidid"><code>process.setuid()</code></a> are
unavailable, and native addons must not invoke system functions such as
<a href="https://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>.</p>
<p>This environment variable is implemented by a dependency of Node.js and may be
removed in future versions of Node.js. No stability guarantees are provided for
the behavior of this environment variable.</p>
</section><section><h3>Useful V8 options<span><a class="mark" href="#all_cli_useful-v8-options" id="all_cli_useful-v8-options">#</a></span><a aria-hidden="true" class="legacy" id="cli_useful_v8_options"></a></h3>
<p>V8 has its own set of CLI options. Any V8 CLI option that is provided to <code>node</code>
will be passed on to V8 to handle. V8's options have <em>no stability guarantee</em>.
The V8 team themselves don't consider them to be part of their formal API,
and reserve the right to change them at any time. Likewise, they are not
covered by the Node.js stability guarantees. Many of the V8
options are of interest only to V8 developers. Despite this, there is a small
set of V8 options that are widely applicable to Node.js, and they are
documented here:</p>
<!-- v8-options start -->
<h4><code>--abort-on-uncaught-exception</code><span><a class="mark" href="#all_cli_--abort-on-uncaught-exception_1" id="all_cli_--abort-on-uncaught-exception_1">#</a></span><a aria-hidden="true" class="legacy" id="cli_abort_on_uncaught_exception_1"></a></h4>
<h4><code>--disallow-code-generation-from-strings</code><span><a class="mark" href="#all_cli_--disallow-code-generation-from-strings_1" id="all_cli_--disallow-code-generation-from-strings_1">#</a></span><a aria-hidden="true" class="legacy" id="cli_disallow_code_generation_from_strings_1"></a></h4>
<h4><code>--enable-etw-stack-walking</code><span><a class="mark" href="#all_cli_--enable-etw-stack-walking" id="all_cli_--enable-etw-stack-walking">#</a></span><a aria-hidden="true" class="legacy" id="cli_enable_etw_stack_walking"></a></h4>
<h4><code>--expose-gc</code><span><a class="mark" href="#all_cli_--expose-gc_1" id="all_cli_--expose-gc_1">#</a></span><a aria-hidden="true" class="legacy" id="cli_expose_gc_1"></a></h4>
<h4><code>--harmony-shadow-realm</code><span><a class="mark" href="#all_cli_--harmony-shadow-realm" id="all_cli_--harmony-shadow-realm">#</a></span><a aria-hidden="true" class="legacy" id="cli_harmony_shadow_realm"></a></h4>
<h4><code>--huge-max-old-generation-size</code><span><a class="mark" href="#all_cli_--huge-max-old-generation-size" id="all_cli_--huge-max-old-generation-size">#</a></span><a aria-hidden="true" class="legacy" id="cli_huge_max_old_generation_size"></a></h4>
<h4><code>--jitless</code><span><a class="mark" href="#all_cli_--jitless_1" id="all_cli_--jitless_1">#</a></span><a aria-hidden="true" class="legacy" id="cli_jitless_1"></a></h4>
<h4><code>--interpreted-frames-native-stack</code><span><a class="mark" href="#all_cli_--interpreted-frames-native-stack" id="all_cli_--interpreted-frames-native-stack">#</a></span><a aria-hidden="true" class="legacy" id="cli_interpreted_frames_native_stack"></a></h4>
<h4><code>--prof</code><span><a class="mark" href="#all_cli_--prof_1" id="all_cli_--prof_1">#</a></span><a aria-hidden="true" class="legacy" id="cli_prof_1"></a></h4>
<h4><code>--perf-basic-prof</code><span><a class="mark" href="#all_cli_--perf-basic-prof" id="all_cli_--perf-basic-prof">#</a></span><a aria-hidden="true" class="legacy" id="cli_perf_basic_prof"></a></h4>
<h4><code>--perf-basic-prof-only-functions</code><span><a class="mark" href="#all_cli_--perf-basic-prof-only-functions" id="all_cli_--perf-basic-prof-only-functions">#</a></span><a aria-hidden="true" class="legacy" id="cli_perf_basic_prof_only_functions"></a></h4>
<h4><code>--perf-prof</code><span><a class="mark" href="#all_cli_--perf-prof" id="all_cli_--perf-prof">#</a></span><a aria-hidden="true" class="legacy" id="cli_perf_prof"></a></h4>
<h4><code>--perf-prof-unwinding-info</code><span><a class="mark" href="#all_cli_--perf-prof-unwinding-info" id="all_cli_--perf-prof-unwinding-info">#</a></span><a aria-hidden="true" class="legacy" id="cli_perf_prof_unwinding_info"></a></h4>
<!-- Anchor to make sure old links find a target -->
<p><a id="--max-old-space-sizesize-in-megabytes"></a></p>
<h4><code>--max-old-space-size=SIZE</code> (in MiB)<span><a class="mark" href="#all_cli_--max-old-space-sizesize-in-mib" id="all_cli_--max-old-space-sizesize-in-mib">#</a></span><a aria-hidden="true" class="legacy" id="cli_max_old_space_size_size_in_mib"></a></h4>
<p>Sets the max memory size of V8's old memory section. As memory
consumption approaches the limit, V8 will spend more time on
garbage collection in an effort to free unused memory.</p>
<p>On a machine with 2 GiB of memory, consider setting this to
1536 (1.5 GiB) to leave some memory for other uses and avoid swapping.</p>
<pre><code class="language-bash">node --max-old-space-size=1536 index.js</code> <button class="copy-button">copy</button></pre>
<!-- Anchor to make sure old links find a target -->
<p><a id="--max-semi-space-sizesize-in-megabytes"></a></p>
<h4><code>--max-semi-space-size=SIZE</code> (in MiB)<span><a class="mark" href="#all_cli_--max-semi-space-sizesize-in-mib" id="all_cli_--max-semi-space-sizesize-in-mib">#</a></span><a aria-hidden="true" class="legacy" id="cli_max_semi_space_size_size_in_mib"></a></h4>
<p>Sets the maximum <a href="https://www.memorymanagement.org/glossary/s.html#semi.space">semi-space</a> size for V8's <a href="https://v8.dev/blog/orinoco-parallel-scavenger">scavenge garbage collector</a> in
MiB (mebibytes).
Increasing the max size of a semi-space may improve throughput for Node.js at
the cost of more memory consumption.</p>
<p>Since the young generation size of the V8 heap is three times (see
<a href="https://chromium.googlesource.com/v8/v8.git/+/refs/tags/10.3.129/src/heap/heap.cc#328"><code>YoungGenerationSizeFromSemiSpaceSize</code></a> in V8) the size of the semi-space,
an increase of 1 MiB to semi-space applies to each of the three individual
semi-spaces and causes the heap size to increase by 3 MiB. The throughput
improvement depends on your workload (see <a href="https://github.com/nodejs/node/issues/42511">#42511</a>).</p>
<p>The default value depends on the memory limit. For example, on 64-bit systems
with a memory limit of 512 MiB, the max size of a semi-space defaults to 1 MiB.
For memory limits up to and including 2GiB, the default max size of a
semi-space will be less than 16 MiB on 64-bit systems.</p>
<p>To get the best configuration for your application, you should try different
max-semi-space-size values when running benchmarks for your application.</p>
<p>For example, benchmark on a 64-bit systems:</p>
<pre><code class="language-bash"><span class="hljs-keyword">for</span> MiB <span class="hljs-keyword">in</span> 16 32 64 128; <span class="hljs-keyword">do</span>
node --max-semi-space-size=<span class="hljs-variable">$MiB</span> index.js
<span class="hljs-keyword">done</span></code> <button class="copy-button">copy</button></pre>
<h4><code>--security-revert</code><span><a class="mark" href="#all_cli_--security-revert" id="all_cli_--security-revert">#</a></span><a aria-hidden="true" class="legacy" id="cli_security_revert"></a></h4>
<h4><code>--stack-trace-limit=limit</code><span><a class="mark" href="#all_cli_--stack-trace-limitlimit" id="all_cli_--stack-trace-limitlimit">#</a></span><a aria-hidden="true" class="legacy" id="cli_stack_trace_limit_limit"></a></h4>
<p>The maximum number of stack frames to collect in an error's stack trace.
Setting it to 0 disables stack trace collection. The default value is 10.</p>
<pre><code class="language-bash">node --stack-trace-limit=12 -p -e <span class="hljs-string">"Error.stackTraceLimit"</span> <span class="hljs-comment"># prints 12</span></code> <button class="copy-button">copy</button></pre>
<!-- v8-options end --></section>
</section>
<section><h2>Console<span><a class="mark" href="#all_console_console" id="all_console_console">#</a></span><a aria-hidden="true" class="legacy" id="console_console"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/console.js">lib/console.js</a></p>
<p>The <code>node:console</code> module provides a simple debugging console that is similar to
the JavaScript console mechanism provided by web browsers.</p>
<p>The module exports two specific components:</p>
<ul>
<li>A <code>Console</code> class with methods such as <code>console.log()</code>, <code>console.error()</code>, and
<code>console.warn()</code> that can be used to write to any Node.js stream.</li>
<li>A global <code>console</code> instance configured to write to <a href="#all_process_processstdout"><code>process.stdout</code></a> and
<a href="#all_process_processstderr"><code>process.stderr</code></a>. The global <code>console</code> can be used without calling
<code>require('node:console')</code>.</li>
</ul>
<p><em><strong>Warning</strong></em>: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. Programs that desire to depend
on the synchronous / asynchronous behavior of the console functions should
first figure out the nature of console's backing stream. This is because the
stream is dependent on the underlying platform and standard stream
configuration of the current process. See the <a href="#all_process_a-note-on-process-io">note on process I/O</a> for
more information.</p>
<p>Example using the global <code>console</code>:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'hello world'</span>);
<span class="hljs-comment">// Prints: hello world, to stdout</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'hello %s'</span>, <span class="hljs-string">'world'</span>);
<span class="hljs-comment">// Prints: hello world, to stdout</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Whoops, something bad happened'</span>));
<span class="hljs-comment">// Prints error message and stack trace to stderr:</span>
<span class="hljs-comment">// Error: Whoops, something bad happened</span>
<span class="hljs-comment">// at [eval]:5:15</span>
<span class="hljs-comment">// at Script.runInThisContext (node:vm:132:18)</span>
<span class="hljs-comment">// at Object.runInThisContext (node:vm:309:38)</span>
<span class="hljs-comment">// at node:internal/process/execution:77:19</span>
<span class="hljs-comment">// at [eval]-wrapper:6:22</span>
<span class="hljs-comment">// at evalScript (node:internal/process/execution:76:60)</span>
<span class="hljs-comment">// at node:internal/main/eval_string:23:3</span>
<span class="hljs-keyword">const</span> name = <span class="hljs-string">'Will Robinson'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(<span class="hljs-string">`Danger <span class="hljs-subst">${name}</span>! Danger!`</span>);
<span class="hljs-comment">// Prints: Danger Will Robinson! Danger!, to stderr</span></code> <button class="copy-button">copy</button></pre>
<p>Example using the <code>Console</code> class:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> out = <span class="hljs-title function_">getStreamSomehow</span>();
<span class="hljs-keyword">const</span> err = <span class="hljs-title function_">getStreamSomehow</span>();
<span class="hljs-keyword">const</span> myConsole = <span class="hljs-keyword">new</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title class_">Console</span>(out, err);
myConsole.<span class="hljs-title function_">log</span>(<span class="hljs-string">'hello world'</span>);
<span class="hljs-comment">// Prints: hello world, to out</span>
myConsole.<span class="hljs-title function_">log</span>(<span class="hljs-string">'hello %s'</span>, <span class="hljs-string">'world'</span>);
<span class="hljs-comment">// Prints: hello world, to out</span>
myConsole.<span class="hljs-title function_">error</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Whoops, something bad happened'</span>));
<span class="hljs-comment">// Prints: [Error: Whoops, something bad happened], to err</span>
<span class="hljs-keyword">const</span> name = <span class="hljs-string">'Will Robinson'</span>;
myConsole.<span class="hljs-title function_">warn</span>(<span class="hljs-string">`Danger <span class="hljs-subst">${name}</span>! Danger!`</span>);
<span class="hljs-comment">// Prints: Danger Will Robinson! Danger!, to err</span></code> <button class="copy-button">copy</button></pre>
<section><h3>Class: <code>Console</code><span><a class="mark" href="#all_console_class-console" id="all_console_class-console">#</a></span><a aria-hidden="true" class="legacy" id="console_class_console"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Errors that occur while writing to the underlying streams will now be ignored by default.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>Console</code> class can be used to create a simple logger with configurable
output streams and can be accessed using either <code>require('node:console').Console</code>
or <code>console.Console</code> (or their destructured counterparts):</p>
<pre class="with-44-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_">Console</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:console'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Console</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:console'</span>);</code><button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Console</span> } = <span class="hljs-variable language_">console</span>;</code> <button class="copy-button">copy</button></pre>
<h4><code>new Console(stdout[, stderr][, ignoreErrors])</code><span><a class="mark" href="#all_console_new-consolestdout-stderr-ignoreerrors" id="all_console_new-consolestdout-stderr-ignoreerrors">#</a></span><a aria-hidden="true" class="legacy" id="console_new_console_stdout_stderr_ignoreerrors"></a></h4>
<h4><code>new Console(options)</code><span><a class="mark" href="#all_console_new-consoleoptions" id="all_console_new-consoleoptions">#</a></span><a aria-hidden="true" class="legacy" id="console_new_console_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>v14.2.0, v12.17.0</td>
<td><p>The <code>groupIndentation</code> option was introduced.</p></td></tr>
<tr><td>v11.7.0</td>
<td><p>The <code>inspectOptions</code> option is introduced.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>Console</code> constructor now supports an <code>options</code> argument, and the <code>colorMode</code> option was introduced.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>ignoreErrors</code> option was introduced.</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>stdout</code> <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a></li>
<li><code>stderr</code> <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a></li>
<li><code>ignoreErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Ignore errors when writing to the underlying
streams. <strong>Default:</strong> <code>true</code>.</li>
<li><code>colorMode</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#String_type" class="type"><string></a> Set color support for this <code>Console</code> instance.
Setting to <code>true</code> enables coloring while inspecting values. Setting to
<code>false</code> disables coloring while inspecting values. Setting to
<code>'auto'</code> makes color support depend on the value of the <code>isTTY</code> property
and the value returned by <code>getColorDepth()</code> on the respective stream. This
option can not be used, if <code>inspectOptions.colors</code> is set as well.
<strong>Default:</strong> <code>'auto'</code>.</li>
<li><code>inspectOptions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Specifies options that are passed along to
<a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a>.</li>
<li><code>groupIndentation</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Set group indentation.
<strong>Default:</strong> <code>2</code>.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>Console</code> with one or two writable stream instances. <code>stdout</code> is a
writable stream to print log or info output. <code>stderr</code> is used for warning or
error output. If <code>stderr</code> is not provided, <code>stdout</code> is used for <code>stderr</code>.</p>
<pre class="with-44-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> { createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Console</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:console'</span>;
<span class="hljs-comment">// Alternatively</span>
<span class="hljs-comment">// const { Console } = console;</span>
<span class="hljs-keyword">const</span> output = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./stdout.log'</span>);
<span class="hljs-keyword">const</span> errorOutput = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./stderr.log'</span>);
<span class="hljs-comment">// Custom simple logger</span>
<span class="hljs-keyword">const</span> logger = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Console</span>({ <span class="hljs-attr">stdout</span>: output, <span class="hljs-attr">stderr</span>: errorOutput });
<span class="hljs-comment">// use it like console</span>
<span class="hljs-keyword">const</span> count = <span class="hljs-number">5</span>;
logger.<span class="hljs-title function_">log</span>(<span class="hljs-string">'count: %d'</span>, count);
<span class="hljs-comment">// In stdout.log: count 5</span></code><code class="language-js cjs"><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> { <span class="hljs-title class_">Console</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:console'</span>);
<span class="hljs-comment">// Alternatively</span>
<span class="hljs-comment">// const { Console } = console;</span>
<span class="hljs-keyword">const</span> output = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./stdout.log'</span>);
<span class="hljs-keyword">const</span> errorOutput = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./stderr.log'</span>);
<span class="hljs-comment">// Custom simple logger</span>
<span class="hljs-keyword">const</span> logger = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Console</span>({ <span class="hljs-attr">stdout</span>: output, <span class="hljs-attr">stderr</span>: errorOutput });
<span class="hljs-comment">// use it like console</span>
<span class="hljs-keyword">const</span> count = <span class="hljs-number">5</span>;
logger.<span class="hljs-title function_">log</span>(<span class="hljs-string">'count: %d'</span>, count);
<span class="hljs-comment">// In stdout.log: count 5</span></code><button class="copy-button">copy</button></pre>
<p>The global <code>console</code> is a special <code>Console</code> whose output is sent to
<a href="#all_process_processstdout"><code>process.stdout</code></a> and <a href="#all_process_processstderr"><code>process.stderr</code></a>. It is equivalent to calling:</p>
<pre><code class="language-js"><span class="hljs-keyword">new</span> <span class="hljs-title class_">Console</span>({ <span class="hljs-attr">stdout</span>: process.<span class="hljs-property">stdout</span>, <span class="hljs-attr">stderr</span>: process.<span class="hljs-property">stderr</span> });</code> <button class="copy-button">copy</button></pre>
<h4><code>console.assert(value[, ...message])</code><span><a class="mark" href="#all_console_consoleassertvalue-message" id="all_console_consoleassertvalue-message">#</a></span><a aria-hidden="true" class="legacy" id="console_console_assert_value_message"></a></h4>
<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 implementation is now spec compliant and does not throw anymore.</p></td></tr>
<tr><td>v0.1.101</td>
<td><p><span>Added in: v0.1.101</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The value tested for being truthy.</li>
<li><code>...message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> All arguments besides <code>value</code> are used as error message.</li>
</ul>
<p><code>console.assert()</code> writes a message if <code>value</code> is <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">falsy</a> or omitted. It only
writes a message and does not otherwise affect execution. The output always
starts with <code>"Assertion failed"</code>. If provided, <code>message</code> is formatted using
<a href="#all_util_utilformatformat-args"><code>util.format()</code></a>.</p>
<p>If <code>value</code> is <a href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy">truthy</a>, nothing happens.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">assert</span>(<span class="hljs-literal">true</span>, <span class="hljs-string">'does nothing'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">assert</span>(<span class="hljs-literal">false</span>, <span class="hljs-string">'Whoops %s work'</span>, <span class="hljs-string">'didn\'t'</span>);
<span class="hljs-comment">// Assertion failed: Whoops didn't work</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">assert</span>();
<span class="hljs-comment">// Assertion failed</span></code> <button class="copy-button">copy</button></pre>
<h4><code>console.clear()</code><span><a class="mark" href="#all_console_consoleclear" id="all_console_consoleclear">#</a></span><a aria-hidden="true" class="legacy" id="console_console_clear"></a></h4>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
</div>
<p>When <code>stdout</code> is a TTY, calling <code>console.clear()</code> will attempt to clear the
TTY. When <code>stdout</code> is not a TTY, this method does nothing.</p>
<p>The specific operation of <code>console.clear()</code> can vary across operating systems
and terminal types. For most Linux operating systems, <code>console.clear()</code>
operates similarly to the <code>clear</code> shell command. On Windows, <code>console.clear()</code>
will clear only the output in the current terminal viewport for the Node.js
binary.</p>
<h4><code>console.count([label])</code><span><a class="mark" href="#all_console_consolecountlabel" id="all_console_consolecountlabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_count_label"></a></h4>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
</div>
<ul>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The display label for the counter. <strong>Default:</strong> <code>'default'</code>.</li>
</ul>
<p>Maintains an internal counter specific to <code>label</code> and outputs to <code>stdout</code> the
number of times <code>console.count()</code> has been called with the given <code>label</code>.</p>
<!-- eslint-skip -->
<pre><code class="language-js">> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>()
<span class="hljs-attr">default</span>: <span class="hljs-number">1</span>
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>(<span class="hljs-string">'default'</span>)
<span class="hljs-attr">default</span>: <span class="hljs-number">2</span>
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>(<span class="hljs-string">'abc'</span>)
<span class="hljs-attr">abc</span>: <span class="hljs-number">1</span>
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>(<span class="hljs-string">'xyz'</span>)
<span class="hljs-attr">xyz</span>: <span class="hljs-number">1</span>
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>(<span class="hljs-string">'abc'</span>)
<span class="hljs-attr">abc</span>: <span class="hljs-number">2</span>
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>()
<span class="hljs-attr">default</span>: <span class="hljs-number">3</span>
<span class="hljs-literal">undefined</span>
></code> <button class="copy-button">copy</button></pre>
<h4><code>console.countReset([label])</code><span><a class="mark" href="#all_console_consolecountresetlabel" id="all_console_consolecountresetlabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_countreset_label"></a></h4>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
</div>
<ul>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The display label for the counter. <strong>Default:</strong> <code>'default'</code>.</li>
</ul>
<p>Resets the internal counter specific to <code>label</code>.</p>
<!-- eslint-skip -->
<pre><code class="language-js">> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>(<span class="hljs-string">'abc'</span>);
<span class="hljs-attr">abc</span>: <span class="hljs-number">1</span>
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">countReset</span>(<span class="hljs-string">'abc'</span>);
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>(<span class="hljs-string">'abc'</span>);
<span class="hljs-attr">abc</span>: <span class="hljs-number">1</span>
<span class="hljs-literal">undefined</span>
></code> <button class="copy-button">copy</button></pre>
<h4><code>console.debug(data[, ...args])</code><span><a class="mark" href="#all_console_consoledebugdata-args" id="all_console_consoledebugdata-args">#</a></span><a aria-hidden="true" class="legacy" id="console_console_debug_data_args"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.10.0</td>
<td><p><code>console.debug</code> is now an alias for <code>console.log</code>.</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>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>The <code>console.debug()</code> function is an alias for <a href="#all_console_consolelogdata-args"><code>console.log()</code></a>.</p>
<h4><code>console.dir(obj[, options])</code><span><a class="mark" href="#all_console_consoledirobj-options" id="all_console_consoledirobj-options">#</a></span><a aria-hidden="true" class="legacy" id="console_console_dir_obj_options"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.101</span>
</div>
<ul>
<li><code>obj</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></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>showHidden</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code> then the object's non-enumerable and symbol
properties will be shown too. <strong>Default:</strong> <code>false</code>.</li>
<li><code>depth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Tells <a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> how many times to recurse while
formatting the object. This is useful for inspecting large complicated
objects. To make it recurse indefinitely, pass <code>null</code>. <strong>Default:</strong> <code>2</code>.</li>
<li><code>colors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, then the output will be styled with ANSI color
codes. Colors are customizable;
see <a href="#all_util_customizing-utilinspect-colors">customizing <code>util.inspect()</code> colors</a>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Uses <a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> on <code>obj</code> and prints the resulting string to <code>stdout</code>.
This function bypasses any custom <code>inspect()</code> function defined on <code>obj</code>.</p>
<h4><code>console.dirxml(...data)</code><span><a class="mark" href="#all_console_consoledirxmldata" id="all_console_consoledirxmldata">#</a></span><a aria-hidden="true" class="legacy" id="console_console_dirxml_data"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.3.0</td>
<td><p><code>console.dirxml</code> now calls <code>console.log</code> for its arguments.</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>...data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>This method calls <code>console.log()</code> passing it the arguments received.
This method does not produce any XML formatting.</p>
<h4><code>console.error([data][, ...args])</code><span><a class="mark" href="#all_console_consoleerrordata-args" id="all_console_consoleerrordata-args">#</a></span><a aria-hidden="true" class="legacy" id="console_console_error_data_args"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Prints to <code>stderr</code> with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to <a href="http://man7.org/linux/man-pages/man3/printf.3.html"><code>printf(3)</code></a> (the arguments are all passed to
<a href="#all_util_utilformatformat-args"><code>util.format()</code></a>).</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> code = <span class="hljs-number">5</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'error #%d'</span>, code);
<span class="hljs-comment">// Prints: error #5, to stderr</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'error'</span>, code);
<span class="hljs-comment">// Prints: error 5, to stderr</span></code> <button class="copy-button">copy</button></pre>
<p>If formatting elements (e.g. <code>%d</code>) are not found in the first string then
<a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> is called on each argument and the resulting string
values are concatenated. See <a href="#all_util_utilformatformat-args"><code>util.format()</code></a> for more information.</p>
<h4><code>console.group([...label])</code><span><a class="mark" href="#all_console_consolegrouplabel" id="all_console_consolegrouplabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_group_label"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>...label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Increases indentation of subsequent lines by spaces for <code>groupIndentation</code>
length.</p>
<p>If one or more <code>label</code>s are provided, those are printed first without the
additional indentation.</p>
<h4><code>console.groupCollapsed()</code><span><a class="mark" href="#all_console_consolegroupcollapsed" id="all_console_consolegroupcollapsed">#</a></span><a aria-hidden="true" class="legacy" id="console_console_groupcollapsed"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>An alias for <a href="#all_console_consolegrouplabel"><code>console.group()</code></a>.</p>
<h4><code>console.groupEnd()</code><span><a class="mark" href="#all_console_consolegroupend" id="all_console_consolegroupend">#</a></span><a aria-hidden="true" class="legacy" id="console_console_groupend"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>Decreases indentation of subsequent lines by spaces for <code>groupIndentation</code>
length.</p>
<h4><code>console.info([data][, ...args])</code><span><a class="mark" href="#all_console_consoleinfodata-args" id="all_console_consoleinfodata-args">#</a></span><a aria-hidden="true" class="legacy" id="console_console_info_data_args"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>The <code>console.info()</code> function is an alias for <a href="#all_console_consolelogdata-args"><code>console.log()</code></a>.</p>
<h4><code>console.log([data][, ...args])</code><span><a class="mark" href="#all_console_consolelogdata-args" id="all_console_consolelogdata-args">#</a></span><a aria-hidden="true" class="legacy" id="console_console_log_data_args"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Prints to <code>stdout</code> with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to <a href="http://man7.org/linux/man-pages/man3/printf.3.html"><code>printf(3)</code></a> (the arguments are all passed to
<a href="#all_util_utilformatformat-args"><code>util.format()</code></a>).</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> count = <span class="hljs-number">5</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'count: %d'</span>, count);
<span class="hljs-comment">// Prints: count: 5, to stdout</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'count:'</span>, count);
<span class="hljs-comment">// Prints: count: 5, to stdout</span></code> <button class="copy-button">copy</button></pre>
<p>See <a href="#all_util_utilformatformat-args"><code>util.format()</code></a> for more information.</p>
<h4><code>console.table(tabularData[, properties])</code><span><a class="mark" href="#all_console_consoletabletabulardata-properties" id="all_console_consoletabletabulardata-properties">#</a></span><a aria-hidden="true" class="legacy" id="console_console_table_tabulardata_properties"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>tabularData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>properties</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Alternate properties for constructing the table.</li>
</ul>
<p>Try to construct a table with the columns of the properties of <code>tabularData</code>
(or use <code>properties</code>) and rows of <code>tabularData</code> and log it. Falls back to just
logging the argument if it can't be parsed as tabular.</p>
<pre><code class="language-js"><span class="hljs-comment">// These can't be parsed as tabular data</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">table</span>(<span class="hljs-title class_">Symbol</span>());
<span class="hljs-comment">// Symbol()</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">table</span>(<span class="hljs-literal">undefined</span>);
<span class="hljs-comment">// undefined</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">table</span>([{ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-string">'Y'</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-string">'Z'</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> }]);
<span class="hljs-comment">// ┌─────────┬─────┬─────┐</span>
<span class="hljs-comment">// │ (index) │ a │ b │</span>
<span class="hljs-comment">// ├─────────┼─────┼─────┤</span>
<span class="hljs-comment">// │ 0 │ 1 │ 'Y' │</span>
<span class="hljs-comment">// │ 1 │ 'Z' │ 2 │</span>
<span class="hljs-comment">// └─────────┴─────┴─────┘</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">table</span>([{ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-string">'Y'</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-string">'Z'</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> }], [<span class="hljs-string">'a'</span>]);
<span class="hljs-comment">// ┌─────────┬─────┐</span>
<span class="hljs-comment">// │ (index) │ a │</span>
<span class="hljs-comment">// ├─────────┼─────┤</span>
<span class="hljs-comment">// │ 0 │ 1 │</span>
<span class="hljs-comment">// │ 1 │ 'Z' │</span>
<span class="hljs-comment">// └─────────┴─────┘</span></code> <button class="copy-button">copy</button></pre>
<h4><code>console.time([label])</code><span><a class="mark" href="#all_console_consoletimelabel" id="all_console_consoletimelabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_time_label"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div>
<ul>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'default'</code></li>
</ul>
<p>Starts a timer that can be used to compute the duration of an operation. Timers
are identified by a unique <code>label</code>. Use the same <code>label</code> when calling
<a href="#all_console_consoletimeendlabel"><code>console.timeEnd()</code></a> to stop the timer and output the elapsed time in
suitable time units to <code>stdout</code>. For example, if the elapsed
time is 3869ms, <code>console.timeEnd()</code> displays "3.869s".</p>
<h4><code>console.timeEnd([label])</code><span><a class="mark" href="#all_console_consoletimeendlabel" id="all_console_consoletimeendlabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_timeend_label"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The elapsed time is displayed with a suitable time unit.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>This method no longer supports multiple calls that don't map to individual <code>console.time()</code> calls; see below for details.</p></td></tr>
<tr><td>v0.1.104</td>
<td><p><span>Added in: v0.1.104</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'default'</code></li>
</ul>
<p>Stops a timer that was previously started by calling <a href="#all_console_consoletimelabel"><code>console.time()</code></a> and
prints the result to <code>stdout</code>:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">time</span>(<span class="hljs-string">'bunch-of-stuff'</span>);
<span class="hljs-comment">// Do a bunch of stuff.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">timeEnd</span>(<span class="hljs-string">'bunch-of-stuff'</span>);
<span class="hljs-comment">// Prints: bunch-of-stuff: 225.438ms</span></code> <button class="copy-button">copy</button></pre>
<h4><code>console.timeLog([label][, ...data])</code><span><a class="mark" href="#all_console_consoletimeloglabel-data" id="all_console_consoletimeloglabel-data">#</a></span><a aria-hidden="true" class="legacy" id="console_console_timelog_label_data"></a></h4>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
</div>
<ul>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'default'</code></li>
<li><code>...data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>For a timer that was previously started by calling <a href="#all_console_consoletimelabel"><code>console.time()</code></a>, prints
the elapsed time and other <code>data</code> arguments to <code>stdout</code>:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">time</span>(<span class="hljs-string">'process'</span>);
<span class="hljs-keyword">const</span> value = <span class="hljs-title function_">expensiveProcess1</span>(); <span class="hljs-comment">// Returns 42</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">timeLog</span>(<span class="hljs-string">'process'</span>, value);
<span class="hljs-comment">// Prints "process: 365.227ms 42".</span>
<span class="hljs-title function_">doExpensiveProcess2</span>(value);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">timeEnd</span>(<span class="hljs-string">'process'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>console.trace([message][, ...args])</code><span><a class="mark" href="#all_console_consoletracemessage-args" id="all_console_consoletracemessage-args">#</a></span><a aria-hidden="true" class="legacy" id="console_console_trace_message_args"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Prints to <code>stderr</code> the string <code>'Trace: '</code>, followed by the <a href="#all_util_utilformatformat-args"><code>util.format()</code></a>
formatted message and stack trace to the current position in the code.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">trace</span>(<span class="hljs-string">'Show me'</span>);
<span class="hljs-comment">// Prints: (stack trace will vary based on where trace is called)</span>
<span class="hljs-comment">// Trace: Show me</span>
<span class="hljs-comment">// at repl:2:9</span>
<span class="hljs-comment">// at REPLServer.defaultEval (repl.js:248:27)</span>
<span class="hljs-comment">// at bound (domain.js:287:14)</span>
<span class="hljs-comment">// at REPLServer.runBound [as eval] (domain.js:300:12)</span>
<span class="hljs-comment">// at REPLServer.<anonymous> (repl.js:412:12)</span>
<span class="hljs-comment">// at emitOne (events.js:82:20)</span>
<span class="hljs-comment">// at REPLServer.emit (events.js:169:7)</span>
<span class="hljs-comment">// at REPLServer.Interface._onLine (readline.js:210:10)</span>
<span class="hljs-comment">// at REPLServer.Interface._line (readline.js:549:8)</span>
<span class="hljs-comment">// at REPLServer.Interface._ttyWrite (readline.js:826:14)</span></code> <button class="copy-button">copy</button></pre>
<h4><code>console.warn([data][, ...args])</code><span><a class="mark" href="#all_console_consolewarndata-args" id="all_console_consolewarndata-args">#</a></span><a aria-hidden="true" class="legacy" id="console_console_warn_data_args"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>The <code>console.warn()</code> function is an alias for <a href="#all_console_consoleerrordata-args"><code>console.error()</code></a>.</p>
</section><section><h3>Inspector only methods<span><a class="mark" href="#all_console_inspector-only-methods" id="all_console_inspector-only-methods">#</a></span><a aria-hidden="true" class="legacy" id="console_inspector_only_methods"></a></h3>
<p>The following methods are exposed by the V8 engine in the general API but do
not display anything unless used in conjunction with the <a href="debugger.html">inspector</a>
(<code>--inspect</code> flag).</p>
<h4><code>console.profile([label])</code><span><a class="mark" href="#all_console_consoleprofilelabel" id="all_console_consoleprofilelabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_profile_label"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>This method does not display anything unless used in the inspector. The
<code>console.profile()</code> method starts a JavaScript CPU profile with an optional
label until <a href="#all_console_consoleprofileendlabel"><code>console.profileEnd()</code></a> is called. The profile is then added to
the <strong>Profile</strong> panel of the inspector.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">profile</span>(<span class="hljs-string">'MyLabel'</span>);
<span class="hljs-comment">// Some code</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">profileEnd</span>(<span class="hljs-string">'MyLabel'</span>);
<span class="hljs-comment">// Adds the profile 'MyLabel' to the Profiles panel of the inspector.</span></code> <button class="copy-button">copy</button></pre>
<h4><code>console.profileEnd([label])</code><span><a class="mark" href="#all_console_consoleprofileendlabel" id="all_console_consoleprofileendlabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_profileend_label"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>This method does not display anything unless used in the inspector. Stops the
current JavaScript CPU profiling session if one has been started and prints
the report to the <strong>Profiles</strong> panel of the inspector. See
<a href="#all_console_consoleprofilelabel"><code>console.profile()</code></a> for an example.</p>
<p>If this method is called without a label, the most recently started profile is
stopped.</p>
<h4><code>console.timeStamp([label])</code><span><a class="mark" href="#all_console_consoletimestamplabel" id="all_console_consoletimestamplabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_timestamp_label"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>This method does not display anything unless used in the inspector. The
<code>console.timeStamp()</code> method adds an event with the label <code>'label'</code> to the
<strong>Timeline</strong> panel of the inspector.</p></section>
</section>
<section><h2>Corepack<span><a class="mark" href="#all_corepack_corepack" id="all_corepack_corepack">#</a></span><a aria-hidden="true" class="legacy" id="corepack_corepack"></a></h2>
<div class="api_metadata">
<span>Added in: v16.9.0, v14.19.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p><em><a href="https://github.com/nodejs/corepack">Corepack</a></em> is an experimental tool to help with
managing versions of your package managers. It exposes binary proxies for
each <a href="#all_corepack_supported-package-managers">supported package manager</a> that, when called, will identify whatever
package manager is configured for the current project, download it if needed,
and finally run it.</p>
<p>Despite Corepack being distributed with default installs of Node.js, the package
managers managed by Corepack are not part of the Node.js distribution and:</p>
<ul>
<li>Upon first use, Corepack downloads the latest version from the network.</li>
<li>Any required updates (related to security vulnerabilities or otherwise) are
out of scope of the Node.js project. If necessary end users must figure out
how to update on their own.</li>
</ul>
<p>This feature simplifies two core workflows:</p>
<ul>
<li>
<p>It eases new contributor onboarding, since they won't have to follow
system-specific installation processes anymore just to have the package
manager you want them to.</p>
</li>
<li>
<p>It allows you to ensure that everyone in your team will use exactly the
package manager version you intend them to, without them having to
manually synchronize it each time you need to make an update.</p>
</li>
</ul>
<section><h3>Workflows<span><a class="mark" href="#all_corepack_workflows" id="all_corepack_workflows">#</a></span><a aria-hidden="true" class="legacy" id="corepack_workflows"></a></h3>
<h4>Enabling the feature<span><a class="mark" href="#all_corepack_enabling-the-feature" id="all_corepack_enabling-the-feature">#</a></span><a aria-hidden="true" class="legacy" id="corepack_enabling_the_feature"></a></h4>
<p>Due to its experimental status, Corepack currently needs to be explicitly
enabled to have any effect. To do that, run <a href="https://github.com/nodejs/corepack#corepack-enable--name"><code>corepack enable</code></a>, which
will set up the symlinks in your environment next to the <code>node</code> binary
(and overwrite the existing symlinks if necessary).</p>
<p>From this point forward, any call to the <a href="#all_corepack_supported-package-managers">supported binaries</a> will work
without further setup. Should you experience a problem, run
<a href="https://github.com/nodejs/corepack#corepack-disable--name"><code>corepack disable</code></a> to remove the proxies from your system (and consider
opening an issue on the <a href="https://github.com/nodejs/corepack">Corepack repository</a> to let us know).</p>
<h4>Configuring a package<span><a class="mark" href="#all_corepack_configuring-a-package" id="all_corepack_configuring-a-package">#</a></span><a aria-hidden="true" class="legacy" id="corepack_configuring_a_package"></a></h4>
<p>The Corepack proxies will find the closest <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file in your
current directory hierarchy to extract its <a href="#all_packages_packagemanager"><code>"packageManager"</code></a> property.</p>
<p>If the value corresponds to a <a href="#all_corepack_supported-package-managers">supported package manager</a>, Corepack will make
sure that all calls to the relevant binaries are run against the requested
version, downloading it on demand if needed, and aborting if it cannot be
successfully retrieved.</p>
<p>You can use <a href="https://github.com/nodejs/corepack#corepack-use-nameversion"><code>corepack use</code></a> to ask Corepack to update your local
<code>package.json</code> to use the package manager of your choice:</p>
<pre><code class="language-bash">corepack use pnpm@7.x <span class="hljs-comment"># sets the latest 7.x version in the package.json</span>
corepack use yarn@* <span class="hljs-comment"># sets the latest version in the package.json</span></code> <button class="copy-button">copy</button></pre>
<h4>Upgrading the global versions<span><a class="mark" href="#all_corepack_upgrading-the-global-versions" id="all_corepack_upgrading-the-global-versions">#</a></span><a aria-hidden="true" class="legacy" id="corepack_upgrading_the_global_versions"></a></h4>
<p>When running outside of an existing project (for example when running
<code>yarn init</code>), Corepack will by default use predefined versions roughly
corresponding to the latest stable releases from each tool. Those versions can
be overridden by running the <a href="https://github.com/nodejs/corepack#corepack-install--g--global---all--nameversion"><code>corepack install</code></a> command along with the
package manager version you wish to set:</p>
<pre><code class="language-bash">corepack install --global yarn@x.y.z</code> <button class="copy-button">copy</button></pre>
<p>Alternately, a tag or range may be used:</p>
<pre><code class="language-bash">corepack install --global pnpm@*
corepack install --global yarn@stable</code> <button class="copy-button">copy</button></pre>
<h4>Offline workflow<span><a class="mark" href="#all_corepack_offline-workflow" id="all_corepack_offline-workflow">#</a></span><a aria-hidden="true" class="legacy" id="corepack_offline_workflow"></a></h4>
<p>Many production environments don't have network access. Since Corepack
usually downloads the package manager releases straight from their registries,
it can conflict with such environments. To avoid that happening, call the
<a href="https://github.com/nodejs/corepack#corepack-pack---all--nameversion"><code>corepack pack</code></a> command while you still have network access (typically at
the same time you're preparing your deploy image). This will ensure that the
required package managers are available even without network access.</p>
<p>The <code>pack</code> command has <a href="https://github.com/nodejs/corepack#utility-commands">various flags</a>. Consult the detailed
<a href="https://github.com/nodejs/corepack#readme">Corepack documentation</a> for more information.</p>
</section><section><h3>Supported package managers<span><a class="mark" href="#all_corepack_supported-package-managers" id="all_corepack_supported-package-managers">#</a></span><a aria-hidden="true" class="legacy" id="corepack_supported_package_managers"></a></h3>
<p>The following binaries are provided through Corepack:</p>
<table><thead><tr><th>Package manager</th><th>Binary names</th></tr></thead><tbody><tr><td><a href="https://yarnpkg.com">Yarn</a></td><td><code>yarn</code>, <code>yarnpkg</code></td></tr><tr><td><a href="https://pnpm.io">pnpm</a></td><td><code>pnpm</code>, <code>pnpx</code></td></tr></tbody></table>
</section><section><h3>Common questions<span><a class="mark" href="#all_corepack_common-questions" id="all_corepack_common-questions">#</a></span><a aria-hidden="true" class="legacy" id="corepack_common_questions"></a></h3>
<h4>How does Corepack interact with npm?<span><a class="mark" href="#all_corepack_how-does-corepack-interact-with-npm" id="all_corepack_how-does-corepack-interact-with-npm">#</a></span><a aria-hidden="true" class="legacy" id="corepack_how_does_corepack_interact_with_npm"></a></h4>
<p>While Corepack could support npm like any other package manager, its
shims aren't enabled by default. This has a few consequences:</p>
<ul>
<li>
<p>It's always possible to run a <code>npm</code> command within a project configured to
be used with another package manager, since Corepack cannot intercept it.</p>
</li>
<li>
<p>While <code>npm</code> is a valid option in the <a href="#all_packages_packagemanager"><code>"packageManager"</code></a> property, the
lack of shim will cause the global npm to be used.</p>
</li>
</ul>
<h4>Running <code>npm install -g yarn</code> doesn't work<span><a class="mark" href="#all_corepack_running-npm-install--g-yarn-doesnt-work" id="all_corepack_running-npm-install--g-yarn-doesnt-work">#</a></span><a aria-hidden="true" class="legacy" id="corepack_running_npm_install_g_yarn_doesn_t_work"></a></h4>
<p>npm prevents accidentally overriding the Corepack binaries when doing a global
install. To avoid this problem, consider one of the following options:</p>
<ul>
<li>
<p>Don't run this command; Corepack will provide the package manager
binaries anyway and will ensure that the requested versions are always
available, so installing the package managers explicitly isn't needed.</p>
</li>
<li>
<p>Add the <code>--force</code> flag to <code>npm install</code>; this will tell npm that it's fine to
override binaries, but you'll erase the Corepack ones in the process. (Run
<a href="https://github.com/nodejs/corepack#corepack-enable--name"><code>corepack enable</code></a> to add them back.)</p>
</li>
</ul></section>
</section>
<section><h2>Crypto<span><a class="mark" href="#all_crypto_crypto" id="all_crypto_crypto">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/crypto.js">lib/crypto.js</a></p>
<p>The <code>node:crypto</code> module provides cryptographic functionality that includes a
set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify
functions.</p>
<pre class="with-51-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">const</span> { createHmac } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> secret = <span class="hljs-string">'abcdefg'</span>;
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, secret)
.<span class="hljs-title function_">update</span>(<span class="hljs-string">'I love cupcakes'</span>)
.<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createHmac } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> secret = <span class="hljs-string">'abcdefg'</span>;
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, secret)
.<span class="hljs-title function_">update</span>(<span class="hljs-string">'I love cupcakes'</span>)
.<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e</span></code><button class="copy-button">copy</button></pre>
<section><h3>Determining if crypto support is unavailable<span><a class="mark" href="#all_crypto_determining-if-crypto-support-is-unavailable" id="all_crypto_determining-if-crypto-support-is-unavailable">#</a></span><a aria-hidden="true" class="legacy" id="crypto_determining_if_crypto_support_is_unavailable"></a></h3>
<p>It is possible for Node.js to be built without including support for the
<code>node:crypto</code> module. In such cases, attempting to <code>import</code> from <code>crypto</code> or
calling <code>require('node:crypto')</code> will result in an error being thrown.</p>
<p>When using CommonJS, the error thrown can be caught using try/catch:</p>
<!-- eslint-disable no-global-assign -->
<pre><code class="language-js cjs"><span class="hljs-keyword">let</span> crypto;
<span class="hljs-keyword">try</span> {
crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'crypto support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
<!-- eslint-enable no-global-assign -->
<p>When using the lexical ESM <code>import</code> keyword, the error can only be
caught if a handler for <code>process.on('uncaughtException')</code> is registered
<em>before</em> any attempt to load the module is made (using, for instance,
a preload module).</p>
<p>When using ESM, if there is a chance that the code may be run on a build
of Node.js where crypto support is not enabled, consider using the
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import"><code>import()</code></a> function instead of the lexical <code>import</code> keyword:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">let</span> crypto;
<span class="hljs-keyword">try</span> {
crypto = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'crypto support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>Certificate</code><span><a class="mark" href="#all_crypto_class-certificate" id="all_crypto_class-certificate">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_certificate"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div>
<p>SPKAC is a Certificate Signing Request mechanism originally implemented by
Netscape and was specified formally as part of HTML5's <code>keygen</code> element.</p>
<p><code><keygen></code> is deprecated since <a href="https://www.w3.org/TR/html52/changes.html#features-removed">HTML 5.2</a> and new projects
should not use this element anymore.</p>
<p>The <code>node:crypto</code> module provides the <code>Certificate</code> class for working with SPKAC
data. The most common usage is handling output generated by the HTML5
<code><keygen></code> element. Node.js uses <a href="https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html">OpenSSL's SPKAC implementation</a> internally.</p>
<h4>Static method: <code>Certificate.exportChallenge(spkac[, encoding])</code><span><a class="mark" href="#all_crypto_static-method-certificateexportchallengespkac-encoding" id="all_crypto_static-method-certificateexportchallengespkac-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_static_method_certificate_exportchallenge_spkac_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The spkac argument can be an ArrayBuffer. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p><span>Added in: v9.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>spkac</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>spkac</code> string.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The challenge component of the <code>spkac</code> data structure, which
includes a public key and a challenge.</li>
</ul>
<pre class="with-52-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">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> challenge = <span class="hljs-title class_">Certificate</span>.<span class="hljs-title function_">exportChallenge</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(challenge.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: the challenge as a UTF8 string</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> challenge = <span class="hljs-title class_">Certificate</span>.<span class="hljs-title function_">exportChallenge</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(challenge.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: the challenge as a UTF8 string</span></code><button class="copy-button">copy</button></pre>
<h4>Static method: <code>Certificate.exportPublicKey(spkac[, encoding])</code><span><a class="mark" href="#all_crypto_static-method-certificateexportpublickeyspkac-encoding" id="all_crypto_static-method-certificateexportpublickeyspkac-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_static_method_certificate_exportpublickey_spkac_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The spkac argument can be an ArrayBuffer. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p><span>Added in: v9.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>spkac</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>spkac</code> string.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The public key component of the <code>spkac</code> data structure,
which includes a public key and a challenge.</li>
</ul>
<pre class="with-52-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">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> publicKey = <span class="hljs-title class_">Certificate</span>.<span class="hljs-title function_">exportPublicKey</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(publicKey);
<span class="hljs-comment">// Prints: the public key as <Buffer ...></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> publicKey = <span class="hljs-title class_">Certificate</span>.<span class="hljs-title function_">exportPublicKey</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(publicKey);
<span class="hljs-comment">// Prints: the public key as <Buffer ...></span></code><button class="copy-button">copy</button></pre>
<h4>Static method: <code>Certificate.verifySpkac(spkac[, encoding])</code><span><a class="mark" href="#all_crypto_static-method-certificateverifyspkacspkac-encoding" id="all_crypto_static-method-certificateverifyspkacspkac-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_static_method_certificate_verifyspkac_spkac_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The spkac argument can be an ArrayBuffer. Added encoding. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p><span>Added in: v9.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>spkac</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>spkac</code> string.</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 the given <code>spkac</code> data structure is valid,
<code>false</code> otherwise.</li>
</ul>
<pre class="with-52-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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Certificate</span>.<span class="hljs-title function_">verifySpkac</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(spkac)));
<span class="hljs-comment">// Prints: true or false</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Certificate</span>.<span class="hljs-title function_">verifySpkac</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(spkac)));
<span class="hljs-comment">// Prints: true or false</span></code><button class="copy-button">copy</button></pre>
<h4>Legacy API<span><a class="mark" href="#all_crypto_legacy-api" id="all_crypto_legacy-api">#</a></span><a aria-hidden="true" class="legacy" id="crypto_legacy_api"></a></h4>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p>As a legacy interface, it is possible to create new instances of
the <code>crypto.Certificate</code> class as illustrated in the examples below.</p>
<h5><code>new crypto.Certificate()</code><span><a class="mark" href="#all_crypto_new-cryptocertificate" id="all_crypto_new-cryptocertificate">#</a></span><a aria-hidden="true" class="legacy" id="crypto_new_crypto_certificate"></a></h5>
<p>Instances of the <code>Certificate</code> class can be created using the <code>new</code> keyword
or by calling <code>crypto.Certificate()</code> as a function:</p>
<pre class="with-52-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">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> cert1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> cert2 = <span class="hljs-title class_">Certificate</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> cert1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> cert2 = <span class="hljs-title class_">Certificate</span>();</code><button class="copy-button">copy</button></pre>
<h5><code>certificate.exportChallenge(spkac[, encoding])</code><span><a class="mark" href="#all_crypto_certificateexportchallengespkac-encoding" id="all_crypto_certificateexportchallengespkac-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_certificate_exportchallenge_spkac_encoding"></a></h5>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div>
<ul>
<li><code>spkac</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>spkac</code> string.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The challenge component of the <code>spkac</code> data structure, which
includes a public key and a challenge.</li>
</ul>
<pre class="with-52-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">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> cert = <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> challenge = cert.<span class="hljs-title function_">exportChallenge</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(challenge.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: the challenge as a UTF8 string</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> cert = <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> challenge = cert.<span class="hljs-title function_">exportChallenge</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(challenge.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: the challenge as a UTF8 string</span></code><button class="copy-button">copy</button></pre>
<h5><code>certificate.exportPublicKey(spkac[, encoding])</code><span><a class="mark" href="#all_crypto_certificateexportpublickeyspkac-encoding" id="all_crypto_certificateexportpublickeyspkac-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_certificate_exportpublickey_spkac_encoding"></a></h5>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div>
<ul>
<li><code>spkac</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>spkac</code> string.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The public key component of the <code>spkac</code> data structure,
which includes a public key and a challenge.</li>
</ul>
<pre class="with-52-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">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> cert = <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> publicKey = cert.<span class="hljs-title function_">exportPublicKey</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(publicKey);
<span class="hljs-comment">// Prints: the public key as <Buffer ...></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> cert = <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> publicKey = cert.<span class="hljs-title function_">exportPublicKey</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(publicKey);
<span class="hljs-comment">// Prints: the public key as <Buffer ...></span></code><button class="copy-button">copy</button></pre>
<h5><code>certificate.verifySpkac(spkac[, encoding])</code><span><a class="mark" href="#all_crypto_certificateverifyspkacspkac-encoding" id="all_crypto_certificateverifyspkacspkac-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_certificate_verifyspkac_spkac_encoding"></a></h5>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div>
<ul>
<li><code>spkac</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>spkac</code> string.</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 the given <code>spkac</code> data structure is valid,
<code>false</code> otherwise.</li>
</ul>
<pre class="with-52-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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> cert = <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cert.<span class="hljs-title function_">verifySpkac</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(spkac)));
<span class="hljs-comment">// Prints: true or false</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> cert = <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cert.<span class="hljs-title function_">verifySpkac</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(spkac)));
<span class="hljs-comment">// Prints: true or false</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>Cipher</code><span><a class="mark" href="#all_crypto_class-cipher" id="all_crypto_class-cipher">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_cipher"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamtransform" class="type"><stream.Transform></a></li>
</ul>
<p>Instances of the <code>Cipher</code> class are used to encrypt data. The class can be
used in one of two ways:</p>
<ul>
<li>As a <a href="stream.html">stream</a> that is both readable and writable, where plain unencrypted
data is written to produce encrypted data on the readable side, or</li>
<li>Using the <a href="#all_crypto_cipherupdatedata-inputencoding-outputencoding"><code>cipher.update()</code></a> and <a href="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a> methods to produce
the encrypted data.</li>
</ul>
<p>The <a href="#all_crypto_cryptocreatecipheralgorithm-password-options"><code>crypto.createCipher()</code></a> or <a href="#all_crypto_cryptocreatecipherivalgorithm-key-iv-options"><code>crypto.createCipheriv()</code></a> methods are
used to create <code>Cipher</code> instances. <code>Cipher</code> objects are not to be created
directly using the <code>new</code> keyword.</p>
<p>Example: Using <code>Cipher</code> objects as streams:</p>
<pre class="with-9-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">const</span> {
scrypt,
randomFill,
createCipheriv,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// First, we'll generate the key. The key length is dependent on the algorithm.</span>
<span class="hljs-comment">// In this case for aes192, it is 24 bytes (192 bits).</span>
<span class="hljs-title function_">scrypt</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-comment">// Then, we'll generate a random initialization vector</span>
<span class="hljs-title function_">randomFill</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>), <span class="hljs-function">(<span class="hljs-params">err, iv</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-comment">// Once we have the key and iv, we can create and use the cipher...</span>
<span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(algorithm, key, iv);
<span class="hljs-keyword">let</span> encrypted = <span class="hljs-string">''</span>;
cipher.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'hex'</span>);
cipher.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> encrypted += chunk);
cipher.<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>(encrypted));
cipher.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some clear text data'</span>);
cipher.<span class="hljs-title function_">end</span>();
});
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
scrypt,
randomFill,
createCipheriv,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// First, we'll generate the key. The key length is dependent on the algorithm.</span>
<span class="hljs-comment">// In this case for aes192, it is 24 bytes (192 bits).</span>
<span class="hljs-title function_">scrypt</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-comment">// Then, we'll generate a random initialization vector</span>
<span class="hljs-title function_">randomFill</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>), <span class="hljs-function">(<span class="hljs-params">err, iv</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-comment">// Once we have the key and iv, we can create and use the cipher...</span>
<span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(algorithm, key, iv);
<span class="hljs-keyword">let</span> encrypted = <span class="hljs-string">''</span>;
cipher.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'hex'</span>);
cipher.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> encrypted += chunk);
cipher.<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>(encrypted));
cipher.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some clear text data'</span>);
cipher.<span class="hljs-title function_">end</span>();
});
});</code><button class="copy-button">copy</button></pre>
<p>Example: Using <code>Cipher</code> and piped streams:</p>
<pre class="with-19-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> {
createReadStream,
createWriteStream,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> {
pipeline,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">const</span> {
scrypt,
randomFill,
createCipheriv,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// First, we'll generate the key. The key length is dependent on the algorithm.</span>
<span class="hljs-comment">// In this case for aes192, it is 24 bytes (192 bits).</span>
<span class="hljs-title function_">scrypt</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-comment">// Then, we'll generate a random initialization vector</span>
<span class="hljs-title function_">randomFill</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>), <span class="hljs-function">(<span class="hljs-params">err, iv</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(algorithm, key, iv);
<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.js'</span>);
<span class="hljs-keyword">const</span> output = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'test.enc'</span>);
<span class="hljs-title function_">pipeline</span>(input, cipher, output, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
});
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createReadStream,
createWriteStream,
} = <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> {
scrypt,
randomFill,
createCipheriv,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// First, we'll generate the key. The key length is dependent on the algorithm.</span>
<span class="hljs-comment">// In this case for aes192, it is 24 bytes (192 bits).</span>
<span class="hljs-title function_">scrypt</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-comment">// Then, we'll generate a random initialization vector</span>
<span class="hljs-title function_">randomFill</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>), <span class="hljs-function">(<span class="hljs-params">err, iv</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(algorithm, key, iv);
<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.js'</span>);
<span class="hljs-keyword">const</span> output = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'test.enc'</span>);
<span class="hljs-title function_">pipeline</span>(input, cipher, output, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
});
});</code><button class="copy-button">copy</button></pre>
<p>Example: Using the <a href="#all_crypto_cipherupdatedata-inputencoding-outputencoding"><code>cipher.update()</code></a> and <a href="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a> methods:</p>
<pre class="with-9-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">const</span> {
scrypt,
randomFill,
createCipheriv,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// First, we'll generate the key. The key length is dependent on the algorithm.</span>
<span class="hljs-comment">// In this case for aes192, it is 24 bytes (192 bits).</span>
<span class="hljs-title function_">scrypt</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-comment">// Then, we'll generate a random initialization vector</span>
<span class="hljs-title function_">randomFill</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>), <span class="hljs-function">(<span class="hljs-params">err, iv</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(algorithm, key, iv);
<span class="hljs-keyword">let</span> encrypted = cipher.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some clear text data'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-string">'hex'</span>);
encrypted += cipher.<span class="hljs-title function_">final</span>(<span class="hljs-string">'hex'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(encrypted);
});
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
scrypt,
randomFill,
createCipheriv,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// First, we'll generate the key. The key length is dependent on the algorithm.</span>
<span class="hljs-comment">// In this case for aes192, it is 24 bytes (192 bits).</span>
<span class="hljs-title function_">scrypt</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-comment">// Then, we'll generate a random initialization vector</span>
<span class="hljs-title function_">randomFill</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>), <span class="hljs-function">(<span class="hljs-params">err, iv</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(algorithm, key, iv);
<span class="hljs-keyword">let</span> encrypted = cipher.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some clear text data'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-string">'hex'</span>);
encrypted += cipher.<span class="hljs-title function_">final</span>(<span class="hljs-string">'hex'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(encrypted);
});
});</code><button class="copy-button">copy</button></pre>
<h4><code>cipher.final([outputEncoding])</code><span><a class="mark" href="#all_crypto_cipherfinaloutputencoding" id="all_crypto_cipherfinaloutputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_cipher_final_outputencoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div>
<ul>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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> Any remaining enciphered contents.
If <code>outputEncoding</code> is specified, a string is
returned. If an <code>outputEncoding</code> is not provided, a <a href="buffer.html"><code>Buffer</code></a> is returned.</li>
</ul>
<p>Once the <code>cipher.final()</code> method has been called, the <code>Cipher</code> object can no
longer be used to encrypt data. Attempts to call <code>cipher.final()</code> more than
once will result in an error being thrown.</p>
<h4><code>cipher.getAuthTag()</code><span><a class="mark" href="#all_crypto_ciphergetauthtag" id="all_crypto_ciphergetauthtag">#</a></span><a aria-hidden="true" class="legacy" id="crypto_cipher_getauthtag"></a></h4>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code>,
<code>OCB</code>, and <code>chacha20-poly1305</code> are currently supported), the
<code>cipher.getAuthTag()</code> method returns a
<a href="buffer.html"><code>Buffer</code></a> containing the <em>authentication tag</em> that has been computed from
the given data.</li>
</ul>
<p>The <code>cipher.getAuthTag()</code> method should only be called after encryption has
been completed using the <a href="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a> method.</p>
<p>If the <code>authTagLength</code> option was set during the <code>cipher</code> instance's creation,
this function will return exactly <code>authTagLength</code> bytes.</p>
<h4><code>cipher.setAAD(buffer[, options])</code><span><a class="mark" href="#all_crypto_ciphersetaadbuffer-options" id="all_crypto_ciphersetaadbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_cipher_setaad_buffer_options"></a></h4>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div>
<ul>
<li><code>buffer</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a>
<ul>
<li><code>plaintextLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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> The string encoding to use when <code>buffer</code> is a string.</li>
</ul>
</li>
<li>Returns: <a href="#all_crypto_class-cipher" class="type"><Cipher></a> The same <code>Cipher</code> instance for method chaining.</li>
</ul>
<p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code>, <code>OCB</code>, and
<code>chacha20-poly1305</code> are
currently supported), the <code>cipher.setAAD()</code> method sets the value used for the
<em>additional authenticated data</em> (AAD) input parameter.</p>
<p>The <code>plaintextLength</code> option is optional for <code>GCM</code> and <code>OCB</code>. When using <code>CCM</code>,
the <code>plaintextLength</code> option must be specified and its value must match the
length of the plaintext in bytes. See <a href="#all_crypto_ccm-mode">CCM mode</a>.</p>
<p>The <code>cipher.setAAD()</code> method must be called before <a href="#all_crypto_cipherupdatedata-inputencoding-outputencoding"><code>cipher.update()</code></a>.</p>
<h4><code>cipher.setAutoPadding([autoPadding])</code><span><a class="mark" href="#all_crypto_ciphersetautopaddingautopadding" id="all_crypto_ciphersetautopaddingautopadding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_cipher_setautopadding_autopadding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.1</span>
</div>
<ul>
<li><code>autoPadding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</code></li>
<li>Returns: <a href="#all_crypto_class-cipher" class="type"><Cipher></a> The same <code>Cipher</code> instance for method chaining.</li>
</ul>
<p>When using block encryption algorithms, the <code>Cipher</code> class will automatically
add padding to the input data to the appropriate block size. To disable the
default padding call <code>cipher.setAutoPadding(false)</code>.</p>
<p>When <code>autoPadding</code> is <code>false</code>, the length of the entire input data must be a
multiple of the cipher's block size or <a href="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a> will throw an error.
Disabling automatic padding is useful for non-standard padding, for instance
using <code>0x0</code> instead of PKCS padding.</p>
<p>The <code>cipher.setAutoPadding()</code> method must be called before
<a href="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a>.</p>
<h4><code>cipher.update(data[, inputEncoding][, outputEncoding])</code><span><a class="mark" href="#all_crypto_cipherupdatedata-inputencoding-outputencoding" id="all_crypto_cipherupdatedata-inputencoding-outputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_cipher_update_data_inputencoding_outputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the data.</li>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Updates the cipher with <code>data</code>. If the <code>inputEncoding</code> argument is given,
the <code>data</code>
argument is a string using the specified encoding. If the <code>inputEncoding</code>
argument is not given, <code>data</code> must be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>, then
<code>inputEncoding</code> is ignored.</p>
<p>The <code>outputEncoding</code> specifies the output format of the enciphered
data. If the <code>outputEncoding</code>
is specified, a string using the specified encoding is returned. If no
<code>outputEncoding</code> is provided, a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<p>The <code>cipher.update()</code> method can be called multiple times with new data until
<a href="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a> is called. Calling <code>cipher.update()</code> after
<a href="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a> will result in an error being thrown.</p>
</section><section><h3>Class: <code>Decipher</code><span><a class="mark" href="#all_crypto_class-decipher" id="all_crypto_class-decipher">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_decipher"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamtransform" class="type"><stream.Transform></a></li>
</ul>
<p>Instances of the <code>Decipher</code> class are used to decrypt data. The class can be
used in one of two ways:</p>
<ul>
<li>As a <a href="stream.html">stream</a> that is both readable and writable, where plain encrypted
data is written to produce unencrypted data on the readable side, or</li>
<li>Using the <a href="#all_crypto_decipherupdatedata-inputencoding-outputencoding"><code>decipher.update()</code></a> and <a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> methods to
produce the unencrypted data.</li>
</ul>
<p>The <a href="#all_crypto_cryptocreatedecipheralgorithm-password-options"><code>crypto.createDecipher()</code></a> or <a href="#all_crypto_cryptocreatedecipherivalgorithm-key-iv-options"><code>crypto.createDecipheriv()</code></a> methods are
used to create <code>Decipher</code> instances. <code>Decipher</code> objects are not to be created
directly using the <code>new</code> keyword.</p>
<p>Example: Using <code>Decipher</code> objects as streams:</p>
<pre class="with-37-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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> {
scryptSync,
createDecipheriv,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// Key length is dependent on the algorithm. In this case for aes192, it is</span>
<span class="hljs-comment">// 24 bytes (192 bits).</span>
<span class="hljs-comment">// Use the async `crypto.scrypt()` instead.</span>
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">scryptSync</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>);
<span class="hljs-comment">// The IV is usually passed along with the ciphertext.</span>
<span class="hljs-keyword">const</span> iv = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">16</span>, <span class="hljs-number">0</span>); <span class="hljs-comment">// Initialization vector.</span>
<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(algorithm, key, iv);
<span class="hljs-keyword">let</span> decrypted = <span class="hljs-string">''</span>;
decipher.<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 = decipher.<span class="hljs-title function_">read</span>())) {
decrypted += chunk.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>);
}
});
decipher.<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>(decrypted);
<span class="hljs-comment">// Prints: some clear text data</span>
});
<span class="hljs-comment">// Encrypted with same algorithm, key and iv.</span>
<span class="hljs-keyword">const</span> encrypted =
<span class="hljs-string">'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'</span>;
decipher.<span class="hljs-title function_">write</span>(encrypted, <span class="hljs-string">'hex'</span>);
decipher.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
scryptSync,
createDecipheriv,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// Key length is dependent on the algorithm. In this case for aes192, it is</span>
<span class="hljs-comment">// 24 bytes (192 bits).</span>
<span class="hljs-comment">// Use the async `crypto.scrypt()` instead.</span>
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">scryptSync</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>);
<span class="hljs-comment">// The IV is usually passed along with the ciphertext.</span>
<span class="hljs-keyword">const</span> iv = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">16</span>, <span class="hljs-number">0</span>); <span class="hljs-comment">// Initialization vector.</span>
<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(algorithm, key, iv);
<span class="hljs-keyword">let</span> decrypted = <span class="hljs-string">''</span>;
decipher.<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 = decipher.<span class="hljs-title function_">read</span>())) {
decrypted += chunk.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>);
}
});
decipher.<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>(decrypted);
<span class="hljs-comment">// Prints: some clear text data</span>
});
<span class="hljs-comment">// Encrypted with same algorithm, key and iv.</span>
<span class="hljs-keyword">const</span> encrypted =
<span class="hljs-string">'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'</span>;
decipher.<span class="hljs-title function_">write</span>(encrypted, <span class="hljs-string">'hex'</span>);
decipher.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<p>Example: Using <code>Decipher</code> and piped streams:</p>
<pre class="with-19-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> {
createReadStream,
createWriteStream,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> {
scryptSync,
createDecipheriv,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// Use the async `crypto.scrypt()` instead.</span>
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">scryptSync</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>);
<span class="hljs-comment">// The IV is usually passed along with the ciphertext.</span>
<span class="hljs-keyword">const</span> iv = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">16</span>, <span class="hljs-number">0</span>); <span class="hljs-comment">// Initialization vector.</span>
<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(algorithm, key, iv);
<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.enc'</span>);
<span class="hljs-keyword">const</span> output = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'test.js'</span>);
input.<span class="hljs-title function_">pipe</span>(decipher).<span class="hljs-title function_">pipe</span>(output);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createReadStream,
createWriteStream,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> {
scryptSync,
createDecipheriv,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// Use the async `crypto.scrypt()` instead.</span>
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">scryptSync</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>);
<span class="hljs-comment">// The IV is usually passed along with the ciphertext.</span>
<span class="hljs-keyword">const</span> iv = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">16</span>, <span class="hljs-number">0</span>); <span class="hljs-comment">// Initialization vector.</span>
<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(algorithm, key, iv);
<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.enc'</span>);
<span class="hljs-keyword">const</span> output = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'test.js'</span>);
input.<span class="hljs-title function_">pipe</span>(decipher).<span class="hljs-title function_">pipe</span>(output);</code><button class="copy-button">copy</button></pre>
<p>Example: Using the <a href="#all_crypto_decipherupdatedata-inputencoding-outputencoding"><code>decipher.update()</code></a> and <a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> methods:</p>
<pre class="with-37-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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> {
scryptSync,
createDecipheriv,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// Use the async `crypto.scrypt()` instead.</span>
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">scryptSync</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>);
<span class="hljs-comment">// The IV is usually passed along with the ciphertext.</span>
<span class="hljs-keyword">const</span> iv = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">16</span>, <span class="hljs-number">0</span>); <span class="hljs-comment">// Initialization vector.</span>
<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(algorithm, key, iv);
<span class="hljs-comment">// Encrypted using same algorithm, key and iv.</span>
<span class="hljs-keyword">const</span> encrypted =
<span class="hljs-string">'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'</span>;
<span class="hljs-keyword">let</span> decrypted = decipher.<span class="hljs-title function_">update</span>(encrypted, <span class="hljs-string">'hex'</span>, <span class="hljs-string">'utf8'</span>);
decrypted += decipher.<span class="hljs-title function_">final</span>(<span class="hljs-string">'utf8'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decrypted);
<span class="hljs-comment">// Prints: some clear text data</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
scryptSync,
createDecipheriv,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// Use the async `crypto.scrypt()` instead.</span>
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">scryptSync</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>);
<span class="hljs-comment">// The IV is usually passed along with the ciphertext.</span>
<span class="hljs-keyword">const</span> iv = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">16</span>, <span class="hljs-number">0</span>); <span class="hljs-comment">// Initialization vector.</span>
<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(algorithm, key, iv);
<span class="hljs-comment">// Encrypted using same algorithm, key and iv.</span>
<span class="hljs-keyword">const</span> encrypted =
<span class="hljs-string">'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'</span>;
<span class="hljs-keyword">let</span> decrypted = decipher.<span class="hljs-title function_">update</span>(encrypted, <span class="hljs-string">'hex'</span>, <span class="hljs-string">'utf8'</span>);
decrypted += decipher.<span class="hljs-title function_">final</span>(<span class="hljs-string">'utf8'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decrypted);
<span class="hljs-comment">// Prints: some clear text data</span></code><button class="copy-button">copy</button></pre>
<h4><code>decipher.final([outputEncoding])</code><span><a class="mark" href="#all_crypto_decipherfinaloutputencoding" id="all_crypto_decipherfinaloutputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_decipher_final_outputencoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div>
<ul>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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> Any remaining deciphered contents.
If <code>outputEncoding</code> is specified, a string is
returned. If an <code>outputEncoding</code> is not provided, a <a href="buffer.html"><code>Buffer</code></a> is returned.</li>
</ul>
<p>Once the <code>decipher.final()</code> method has been called, the <code>Decipher</code> object can
no longer be used to decrypt data. Attempts to call <code>decipher.final()</code> more
than once will result in an error being thrown.</p>
<h4><code>decipher.setAAD(buffer[, options])</code><span><a class="mark" href="#all_crypto_deciphersetaadbuffer-options" id="all_crypto_deciphersetaadbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_decipher_setaad_buffer_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>v15.0.0</td>
<td><p>The buffer argument can be a string or ArrayBuffer and is limited to no more than 2 ** 31 - 1 bytes.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>This method now returns a reference to <code>decipher</code>.</p></td></tr>
<tr><td>v1.0.0</td>
<td><p><span>Added in: v1.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a>
<ul>
<li><code>plaintextLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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> String encoding to use when <code>buffer</code> is a string.</li>
</ul>
</li>
<li>Returns: <a href="#all_crypto_class-decipher" class="type"><Decipher></a> The same Decipher for method chaining.</li>
</ul>
<p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code>, <code>OCB</code>, and
<code>chacha20-poly1305</code> are
currently supported), the <code>decipher.setAAD()</code> method sets the value used for the
<em>additional authenticated data</em> (AAD) input parameter.</p>
<p>The <code>options</code> argument is optional for <code>GCM</code>. When using <code>CCM</code>, the
<code>plaintextLength</code> option must be specified and its value must match the length
of the ciphertext in bytes. See <a href="#all_crypto_ccm-mode">CCM mode</a>.</p>
<p>The <code>decipher.setAAD()</code> method must be called before <a href="#all_crypto_decipherupdatedata-inputencoding-outputencoding"><code>decipher.update()</code></a>.</p>
<p>When passing a string as the <code>buffer</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</p>
<h4><code>decipher.setAuthTag(buffer[, encoding])</code><span><a class="mark" href="#all_crypto_deciphersetauthtagbuffer-encoding" id="all_crypto_deciphersetauthtagbuffer-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_decipher_setauthtag_buffer_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Using GCM tag lengths other than 128 bits without specifying the <code>authTagLength</code> option when creating <code>decipher</code> is deprecated.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The buffer argument can be a string or ArrayBuffer and is limited to no more than 2 ** 31 - 1 bytes.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>This method now throws if the GCM tag length is invalid.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>This method now returns a reference to <code>decipher</code>.</p></td></tr>
<tr><td>v1.0.0</td>
<td><p><span>Added in: v1.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></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/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></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> String encoding to use when <code>buffer</code> is a string.</li>
<li>Returns: <a href="#all_crypto_class-decipher" class="type"><Decipher></a> The same Decipher for method chaining.</li>
</ul>
<p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code>, <code>OCB</code>, and
<code>chacha20-poly1305</code> are
currently supported), the <code>decipher.setAuthTag()</code> method is used to pass in the
received <em>authentication tag</em>. If no tag is provided, or if the cipher text
has been tampered with, <a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> will throw, indicating that the
cipher text should be discarded due to failed authentication. If the tag length
is invalid according to <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf">NIST SP 800-38D</a> or does not match the value of the
<code>authTagLength</code> option, <code>decipher.setAuthTag()</code> will throw an error.</p>
<p>The <code>decipher.setAuthTag()</code> method must be called before <a href="#all_crypto_decipherupdatedata-inputencoding-outputencoding"><code>decipher.update()</code></a>
for <code>CCM</code> mode or before <a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> for <code>GCM</code> and <code>OCB</code> modes and
<code>chacha20-poly1305</code>.
<code>decipher.setAuthTag()</code> can only be called once.</p>
<p>When passing a string as the authentication tag, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</p>
<h4><code>decipher.setAutoPadding([autoPadding])</code><span><a class="mark" href="#all_crypto_deciphersetautopaddingautopadding" id="all_crypto_deciphersetautopaddingautopadding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_decipher_setautopadding_autopadding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.1</span>
</div>
<ul>
<li><code>autoPadding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</code></li>
<li>Returns: <a href="#all_crypto_class-decipher" class="type"><Decipher></a> The same Decipher for method chaining.</li>
</ul>
<p>When data has been encrypted without standard block padding, calling
<code>decipher.setAutoPadding(false)</code> will disable automatic padding to prevent
<a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> from checking for and removing padding.</p>
<p>Turning auto padding off will only work if the input data's length is a
multiple of the ciphers block size.</p>
<p>The <code>decipher.setAutoPadding()</code> method must be called before
<a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a>.</p>
<h4><code>decipher.update(data[, inputEncoding][, outputEncoding])</code><span><a class="mark" href="#all_crypto_decipherupdatedata-inputencoding-outputencoding" id="all_crypto_decipherupdatedata-inputencoding-outputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_decipher_update_data_inputencoding_outputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>data</code> string.</li>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Updates the decipher with <code>data</code>. If the <code>inputEncoding</code> argument is given,
the <code>data</code>
argument is a string using the specified encoding. If the <code>inputEncoding</code>
argument is not given, <code>data</code> must be a <a href="buffer.html"><code>Buffer</code></a>. If <code>data</code> is a
<a href="buffer.html"><code>Buffer</code></a> then <code>inputEncoding</code> is ignored.</p>
<p>The <code>outputEncoding</code> specifies the output format of the enciphered
data. If the <code>outputEncoding</code>
is specified, a string using the specified encoding is returned. If no
<code>outputEncoding</code> is provided, a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<p>The <code>decipher.update()</code> method can be called multiple times with new data until
<a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> is called. Calling <code>decipher.update()</code> after
<a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> will result in an error being thrown.</p>
<p>Even if the underlying cipher implements authentication, the authenticity and
integrity of the plaintext returned from this function may be uncertain at this
time. For authenticated encryption algorithms, authenticity is generally only
established when the application calls <a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a>.</p>
</section><section><h3>Class: <code>DiffieHellman</code><span><a class="mark" href="#all_crypto_class-diffiehellman" id="all_crypto_class-diffiehellman">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_diffiehellman"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<p>The <code>DiffieHellman</code> class is a utility for creating Diffie-Hellman key
exchanges.</p>
<p>Instances of the <code>DiffieHellman</code> class can be created using the
<a href="#all_crypto_cryptocreatediffiehellmanprime-primeencoding-generator-generatorencoding"><code>crypto.createDiffieHellman()</code></a> function.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">const</span> {
createDiffieHellman,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-comment">// Generate Alice's keys...</span>
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">createDiffieHellman</span>(<span class="hljs-number">2048</span>);
<span class="hljs-keyword">const</span> aliceKey = alice.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-comment">// Generate Bob's keys...</span>
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">createDiffieHellman</span>(alice.<span class="hljs-title function_">getPrime</span>(), alice.<span class="hljs-title function_">getGenerator</span>());
<span class="hljs-keyword">const</span> bobKey = bob.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-comment">// Exchange and generate the secret...</span>
<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bobKey);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(aliceKey);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">strictEqual</span>(aliceSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>), bobSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> {
createDiffieHellman,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-comment">// Generate Alice's keys...</span>
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">createDiffieHellman</span>(<span class="hljs-number">2048</span>);
<span class="hljs-keyword">const</span> aliceKey = alice.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-comment">// Generate Bob's keys...</span>
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">createDiffieHellman</span>(alice.<span class="hljs-title function_">getPrime</span>(), alice.<span class="hljs-title function_">getGenerator</span>());
<span class="hljs-keyword">const</span> bobKey = bob.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-comment">// Exchange and generate the secret...</span>
<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bobKey);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(aliceKey);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">strictEqual</span>(aliceSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>), bobSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));</code><button class="copy-button">copy</button></pre>
<h4><code>diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</code><span><a class="mark" href="#all_crypto_diffiehellmancomputesecretotherpublickey-inputencoding-outputencoding" id="all_crypto_diffiehellmancomputesecretotherpublickey-inputencoding-outputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_computesecret_otherpublickey_inputencoding_outputencoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<ul>
<li><code>otherPublicKey</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of an <code>otherPublicKey</code> string.</li>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Computes the shared secret using <code>otherPublicKey</code> as the other
party's public key and returns the computed shared secret. The supplied
key is interpreted using the specified <code>inputEncoding</code>, and secret is
encoded using specified <code>outputEncoding</code>.
If the <code>inputEncoding</code> is not
provided, <code>otherPublicKey</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>,
<code>TypedArray</code>, or <code>DataView</code>.</p>
<p>If <code>outputEncoding</code> is given a string is returned; otherwise, a
<a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<h4><code>diffieHellman.generateKeys([encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmangeneratekeysencoding" id="all_crypto_diffiehellmangeneratekeysencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_generatekeys_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.0</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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Generates private and public Diffie-Hellman key values unless they have been
generated or computed already, and returns
the public key in the specified <code>encoding</code>. This key should be
transferred to the other party.
If <code>encoding</code> is provided a string is returned; otherwise a
<a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<p>This function is a thin wrapper around <a href="https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html"><code>DH_generate_key()</code></a>. In particular,
once a private key has been generated or set, calling this function only updates
the public key but does not generate a new private key.</p>
<h4><code>diffieHellman.getGenerator([encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmangetgeneratorencoding" id="all_crypto_diffiehellmangetgeneratorencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_getgenerator_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.0</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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Returns the Diffie-Hellman generator in the specified <code>encoding</code>.
If <code>encoding</code> is provided a string is
returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<h4><code>diffieHellman.getPrime([encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmangetprimeencoding" id="all_crypto_diffiehellmangetprimeencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_getprime_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.0</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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Returns the Diffie-Hellman prime in the specified <code>encoding</code>.
If <code>encoding</code> is provided a string is
returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<h4><code>diffieHellman.getPrivateKey([encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmangetprivatekeyencoding" id="all_crypto_diffiehellmangetprivatekeyencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_getprivatekey_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.0</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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Returns the Diffie-Hellman private key in the specified <code>encoding</code>.
If <code>encoding</code> is provided a
string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<h4><code>diffieHellman.getPublicKey([encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmangetpublickeyencoding" id="all_crypto_diffiehellmangetpublickeyencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_getpublickey_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.0</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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Returns the Diffie-Hellman public key in the specified <code>encoding</code>.
If <code>encoding</code> is provided a
string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<h4><code>diffieHellman.setPrivateKey(privateKey[, encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmansetprivatekeyprivatekey-encoding" id="all_crypto_diffiehellmansetprivatekeyprivatekey-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_setprivatekey_privatekey_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<ul>
<li><code>privateKey</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>privateKey</code> string.</li>
</ul>
<p>Sets the Diffie-Hellman private key. If the <code>encoding</code> argument is provided,
<code>privateKey</code> is expected
to be a string. If no <code>encoding</code> is provided, <code>privateKey</code> is expected
to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p>
<p>This function does not automatically compute the associated public key. Either
<a href="#all_crypto_diffiehellmansetpublickeypublickey-encoding"><code>diffieHellman.setPublicKey()</code></a> or <a href="#all_crypto_diffiehellmangeneratekeysencoding"><code>diffieHellman.generateKeys()</code></a> can be
used to manually provide the public key or to automatically derive it.</p>
<h4><code>diffieHellman.setPublicKey(publicKey[, encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmansetpublickeypublickey-encoding" id="all_crypto_diffiehellmansetpublickeypublickey-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_setpublickey_publickey_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<ul>
<li><code>publicKey</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>publicKey</code> string.</li>
</ul>
<p>Sets the Diffie-Hellman public key. If the <code>encoding</code> argument is provided,
<code>publicKey</code> is expected
to be a string. If no <code>encoding</code> is provided, <code>publicKey</code> is expected
to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p>
<h4><code>diffieHellman.verifyError</code><span><a class="mark" href="#all_crypto_diffiehellmanverifyerror" id="all_crypto_diffiehellmanverifyerror">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_verifyerror"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div>
<p>A bit field containing any warnings and/or errors resulting from a check
performed during initialization of the <code>DiffieHellman</code> object.</p>
<p>The following values are valid for this property (as defined in <code>node:constants</code> module):</p>
<ul>
<li><code>DH_CHECK_P_NOT_SAFE_PRIME</code></li>
<li><code>DH_CHECK_P_NOT_PRIME</code></li>
<li><code>DH_UNABLE_TO_CHECK_GENERATOR</code></li>
<li><code>DH_NOT_SUITABLE_GENERATOR</code></li>
</ul>
</section><section><h3>Class: <code>DiffieHellmanGroup</code><span><a class="mark" href="#all_crypto_class-diffiehellmangroup" id="all_crypto_class-diffiehellmangroup">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_diffiehellmangroup"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div>
<p>The <code>DiffieHellmanGroup</code> class takes a well-known modp group as its argument.
It works the same as <code>DiffieHellman</code>, except that it does not allow changing
its keys after creation. In other words, it does not implement <code>setPublicKey()</code>
or <code>setPrivateKey()</code> methods.</p>
<pre class="with-65-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">const</span> { createDiffieHellmanGroup } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> dh = <span class="hljs-title function_">createDiffieHellmanGroup</span>(<span class="hljs-string">'modp16'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createDiffieHellmanGroup } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> dh = <span class="hljs-title function_">createDiffieHellmanGroup</span>(<span class="hljs-string">'modp16'</span>);</code><button class="copy-button">copy</button></pre>
<p>The following groups are supported:</p>
<ul>
<li><code>'modp14'</code> (2048 bits, <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a> Section 3)</li>
<li><code>'modp15'</code> (3072 bits, <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a> Section 4)</li>
<li><code>'modp16'</code> (4096 bits, <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a> Section 5)</li>
<li><code>'modp17'</code> (6144 bits, <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a> Section 6)</li>
<li><code>'modp18'</code> (8192 bits, <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a> Section 7)</li>
</ul>
<p>The following groups are still supported but deprecated (see <a href="#all_crypto_support-for-weak-or-compromised-algorithms">Caveats</a>):</p>
<ul>
<li><code>'modp1'</code> (768 bits, <a href="https://www.rfc-editor.org/rfc/rfc2409.txt">RFC 2409</a> Section 6.1) <span class="deprecated-inline"></span></li>
<li><code>'modp2'</code> (1024 bits, <a href="https://www.rfc-editor.org/rfc/rfc2409.txt">RFC 2409</a> Section 6.2) <span class="deprecated-inline"></span></li>
<li><code>'modp5'</code> (1536 bits, <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a> Section 2) <span class="deprecated-inline"></span></li>
</ul>
<p>These deprecated groups might be removed in future versions of Node.js.</p>
</section><section><h3>Class: <code>ECDH</code><span><a class="mark" href="#all_crypto_class-ecdh" id="all_crypto_class-ecdh">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_ecdh"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<p>The <code>ECDH</code> class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)
key exchanges.</p>
<p>Instances of the <code>ECDH</code> class can be created using the
<a href="#all_crypto_cryptocreateecdhcurvename"><code>crypto.createECDH()</code></a> function.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">const</span> {
createECDH,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-comment">// Generate Alice's keys...</span>
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp521r1'</span>);
<span class="hljs-keyword">const</span> aliceKey = alice.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-comment">// Generate Bob's keys...</span>
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp521r1'</span>);
<span class="hljs-keyword">const</span> bobKey = bob.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-comment">// Exchange and generate the secret...</span>
<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bobKey);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(aliceKey);
assert.<span class="hljs-title function_">strictEqual</span>(aliceSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>), bobSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> {
createECDH,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-comment">// Generate Alice's keys...</span>
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp521r1'</span>);
<span class="hljs-keyword">const</span> aliceKey = alice.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-comment">// Generate Bob's keys...</span>
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp521r1'</span>);
<span class="hljs-keyword">const</span> bobKey = bob.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-comment">// Exchange and generate the secret...</span>
<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bobKey);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(aliceKey);
assert.<span class="hljs-title function_">strictEqual</span>(aliceSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>), bobSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></pre>
<h4>Static method: <code>ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])</code><span><a class="mark" href="#all_crypto_static-method-ecdhconvertkeykey-curve-inputencoding-outputencoding-format" id="all_crypto_static-method-ecdhconvertkeykey-curve-inputencoding-outputencoding-format">#</a></span><a aria-hidden="true" class="legacy" id="crypto_static_method_ecdh_convertkey_key_curve_inputencoding_outputencoding_format"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>key</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>curve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>key</code> string.</li>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'uncompressed'</code></li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Converts the EC Diffie-Hellman public key specified by <code>key</code> and <code>curve</code> to the
format specified by <code>format</code>. The <code>format</code> argument specifies point encoding
and can be <code>'compressed'</code>, <code>'uncompressed'</code> or <code>'hybrid'</code>. The supplied key is
interpreted using the specified <code>inputEncoding</code>, and the returned key is encoded
using the specified <code>outputEncoding</code>.</p>
<p>Use <a href="#all_crypto_cryptogetcurves"><code>crypto.getCurves()</code></a> to obtain a list of available curve names.
On recent OpenSSL releases, <code>openssl ecparam -list_curves</code> will also display
the name and description of each available elliptic curve.</p>
<p>If <code>format</code> is not specified the point will be returned in <code>'uncompressed'</code>
format.</p>
<p>If the <code>inputEncoding</code> is not provided, <code>key</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>,
<code>TypedArray</code>, or <code>DataView</code>.</p>
<p>Example (uncompressing a key):</p>
<pre class="with-13-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">const</span> {
createECDH,
<span class="hljs-variable constant_">ECDH</span>,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> ecdh = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp256k1'</span>);
ecdh.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-keyword">const</span> compressedKey = ecdh.<span class="hljs-title function_">getPublicKey</span>(<span class="hljs-string">'hex'</span>, <span class="hljs-string">'compressed'</span>);
<span class="hljs-keyword">const</span> uncompressedKey = <span class="hljs-variable constant_">ECDH</span>.<span class="hljs-title function_">convertKey</span>(compressedKey,
<span class="hljs-string">'secp256k1'</span>,
<span class="hljs-string">'hex'</span>,
<span class="hljs-string">'hex'</span>,
<span class="hljs-string">'uncompressed'</span>);
<span class="hljs-comment">// The converted key and the uncompressed public key should be the same</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(uncompressedKey === ecdh.<span class="hljs-title function_">getPublicKey</span>(<span class="hljs-string">'hex'</span>));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createECDH,
<span class="hljs-variable constant_">ECDH</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> ecdh = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp256k1'</span>);
ecdh.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-keyword">const</span> compressedKey = ecdh.<span class="hljs-title function_">getPublicKey</span>(<span class="hljs-string">'hex'</span>, <span class="hljs-string">'compressed'</span>);
<span class="hljs-keyword">const</span> uncompressedKey = <span class="hljs-variable constant_">ECDH</span>.<span class="hljs-title function_">convertKey</span>(compressedKey,
<span class="hljs-string">'secp256k1'</span>,
<span class="hljs-string">'hex'</span>,
<span class="hljs-string">'hex'</span>,
<span class="hljs-string">'uncompressed'</span>);
<span class="hljs-comment">// The converted key and the uncompressed public key should be the same</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(uncompressedKey === ecdh.<span class="hljs-title function_">getPublicKey</span>(<span class="hljs-string">'hex'</span>));</code><button class="copy-button">copy</button></pre>
<h4><code>ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</code><span><a class="mark" href="#all_crypto_ecdhcomputesecretotherpublickey-inputencoding-outputencoding" id="all_crypto_ecdhcomputesecretotherpublickey-inputencoding-outputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ecdh_computesecret_otherpublickey_inputencoding_outputencoding"></a></h4>
<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>Changed error format to better support invalid public key error.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.11.14</td>
<td><p><span>Added in: v0.11.14</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>otherPublicKey</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>otherPublicKey</code> string.</li>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Computes the shared secret using <code>otherPublicKey</code> as the other
party's public key and returns the computed shared secret. The supplied
key is interpreted using specified <code>inputEncoding</code>, and the returned secret
is encoded using the specified <code>outputEncoding</code>.
If the <code>inputEncoding</code> is not
provided, <code>otherPublicKey</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>.</p>
<p>If <code>outputEncoding</code> is given a string will be returned; otherwise a
<a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<p><code>ecdh.computeSecret</code> will throw an
<code>ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY</code> error when <code>otherPublicKey</code>
lies outside of the elliptic curve. Since <code>otherPublicKey</code> is
usually supplied from a remote user over an insecure network,
be sure to handle this exception accordingly.</p>
<h4><code>ecdh.generateKeys([encoding[, format]])</code><span><a class="mark" href="#all_crypto_ecdhgeneratekeysencoding-format" id="all_crypto_ecdhgeneratekeysencoding-format">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ecdh_generatekeys_encoding_format"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'uncompressed'</code></li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Generates private and public EC Diffie-Hellman key values, and returns
the public key in the specified <code>format</code> and <code>encoding</code>. This key should be
transferred to the other party.</p>
<p>The <code>format</code> argument specifies point encoding and can be <code>'compressed'</code> or
<code>'uncompressed'</code>. If <code>format</code> is not specified, the point will be returned in
<code>'uncompressed'</code> format.</p>
<p>If <code>encoding</code> is provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a>
is returned.</p>
<h4><code>ecdh.getPrivateKey([encoding])</code><span><a class="mark" href="#all_crypto_ecdhgetprivatekeyencoding" id="all_crypto_ecdhgetprivatekeyencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ecdh_getprivatekey_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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> The EC Diffie-Hellman in the specified <code>encoding</code>.</li>
</ul>
<p>If <code>encoding</code> is specified, a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is
returned.</p>
<h4><code>ecdh.getPublicKey([encoding][, format])</code><span><a class="mark" href="#all_crypto_ecdhgetpublickeyencoding-format" id="all_crypto_ecdhgetpublickeyencoding-format">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ecdh_getpublickey_encoding_format"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'uncompressed'</code></li>
<li>Returns: <a href="#all_buffer_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> The EC Diffie-Hellman public key in the specified
<code>encoding</code> and <code>format</code>.</li>
</ul>
<p>The <code>format</code> argument specifies point encoding and can be <code>'compressed'</code> or
<code>'uncompressed'</code>. If <code>format</code> is not specified the point will be returned in
<code>'uncompressed'</code> format.</p>
<p>If <code>encoding</code> is specified, a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is
returned.</p>
<h4><code>ecdh.setPrivateKey(privateKey[, encoding])</code><span><a class="mark" href="#all_crypto_ecdhsetprivatekeyprivatekey-encoding" id="all_crypto_ecdhsetprivatekeyprivatekey-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ecdh_setprivatekey_privatekey_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<ul>
<li><code>privateKey</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>privateKey</code> string.</li>
</ul>
<p>Sets the EC Diffie-Hellman private key.
If <code>encoding</code> is provided, <code>privateKey</code> is expected
to be a string; otherwise <code>privateKey</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>,
<code>TypedArray</code>, or <code>DataView</code>.</p>
<p>If <code>privateKey</code> is not valid for the curve specified when the <code>ECDH</code> object was
created, an error is thrown. Upon setting the private key, the associated
public point (key) is also generated and set in the <code>ECDH</code> object.</p>
<h4><code>ecdh.setPublicKey(publicKey[, encoding])</code><span><a class="mark" href="#all_crypto_ecdhsetpublickeypublickey-encoding" id="all_crypto_ecdhsetpublickeypublickey-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ecdh_setpublickey_publickey_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</span><span>Deprecated since: v5.2.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<ul>
<li><code>publicKey</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>publicKey</code> string.</li>
</ul>
<p>Sets the EC Diffie-Hellman public key.
If <code>encoding</code> is provided <code>publicKey</code> is expected to
be a string; otherwise a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p>
<p>There is not normally a reason to call this method because <code>ECDH</code>
only requires a private key and the other party's public key to compute the
shared secret. Typically either <a href="#all_crypto_ecdhgeneratekeysencoding-format"><code>ecdh.generateKeys()</code></a> or
<a href="#all_crypto_ecdhsetprivatekeyprivatekey-encoding"><code>ecdh.setPrivateKey()</code></a> will be called. The <a href="#all_crypto_ecdhsetprivatekeyprivatekey-encoding"><code>ecdh.setPrivateKey()</code></a> method
attempts to generate the public point/key associated with the private key being
set.</p>
<p>Example (obtaining a shared secret):</p>
<pre class="with-13-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">const</span> {
createECDH,
createHash,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp256k1'</span>);
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp256k1'</span>);
<span class="hljs-comment">// This is a shortcut way of specifying one of Alice's previous private</span>
<span class="hljs-comment">// keys. It would be unwise to use such a predictable private key in a real</span>
<span class="hljs-comment">// application.</span>
alice.<span class="hljs-title function_">setPrivateKey</span>(
<span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>).<span class="hljs-title function_">update</span>(<span class="hljs-string">'alice'</span>, <span class="hljs-string">'utf8'</span>).<span class="hljs-title function_">digest</span>(),
);
<span class="hljs-comment">// Bob uses a newly generated cryptographically strong</span>
<span class="hljs-comment">// pseudorandom key pair</span>
bob.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bob.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(alice.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// aliceSecret and bobSecret should be the same shared secret value</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(aliceSecret === bobSecret);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createECDH,
createHash,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp256k1'</span>);
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp256k1'</span>);
<span class="hljs-comment">// This is a shortcut way of specifying one of Alice's previous private</span>
<span class="hljs-comment">// keys. It would be unwise to use such a predictable private key in a real</span>
<span class="hljs-comment">// application.</span>
alice.<span class="hljs-title function_">setPrivateKey</span>(
<span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>).<span class="hljs-title function_">update</span>(<span class="hljs-string">'alice'</span>, <span class="hljs-string">'utf8'</span>).<span class="hljs-title function_">digest</span>(),
);
<span class="hljs-comment">// Bob uses a newly generated cryptographically strong</span>
<span class="hljs-comment">// pseudorandom key pair</span>
bob.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bob.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(alice.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// aliceSecret and bobSecret should be the same shared secret value</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(aliceSecret === bobSecret);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>Hash</code><span><a class="mark" href="#all_crypto_class-hash" id="all_crypto_class-hash">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_hash"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamtransform" class="type"><stream.Transform></a></li>
</ul>
<p>The <code>Hash</code> class is a utility for creating hash digests of data. It can be
used in one of two ways:</p>
<ul>
<li>As a <a href="stream.html">stream</a> that is both readable and writable, where data is written
to produce a computed hash digest on the readable side, or</li>
<li>Using the <a href="#all_crypto_hashupdatedata-inputencoding"><code>hash.update()</code></a> and <a href="#all_crypto_hashdigestencoding"><code>hash.digest()</code></a> methods to produce the
computed hash.</li>
</ul>
<p>The <a href="#all_crypto_cryptocreatehashalgorithm-options"><code>crypto.createHash()</code></a> method is used to create <code>Hash</code> instances. <code>Hash</code>
objects are not to be created directly using the <code>new</code> keyword.</p>
<p>Example: Using <code>Hash</code> objects as streams:</p>
<pre class="with-13-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">const</span> {
createHash,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
hash.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Only one element is going to be produced by the</span>
<span class="hljs-comment">// hash stream.</span>
<span class="hljs-keyword">const</span> data = hash.<span class="hljs-title function_">read</span>();
<span class="hljs-keyword">if</span> (data) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50</span>
}
});
hash.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to hash'</span>);
hash.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createHash,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
hash.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Only one element is going to be produced by the</span>
<span class="hljs-comment">// hash stream.</span>
<span class="hljs-keyword">const</span> data = hash.<span class="hljs-title function_">read</span>();
<span class="hljs-keyword">if</span> (data) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50</span>
}
});
hash.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to hash'</span>);
hash.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<p>Example: Using <code>Hash</code> and piped streams:</p>
<pre class="with-48-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> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> { createHash } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.js'</span>);
input.<span class="hljs-title function_">pipe</span>(hash).<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'hex'</span>).<span class="hljs-title function_">pipe</span>(stdout);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createReadStream } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { createHash } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { stdout } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.js'</span>);
input.<span class="hljs-title function_">pipe</span>(hash).<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'hex'</span>).<span class="hljs-title function_">pipe</span>(stdout);</code><button class="copy-button">copy</button></pre>
<p>Example: Using the <a href="#all_crypto_hashupdatedata-inputencoding"><code>hash.update()</code></a> and <a href="#all_crypto_hashdigestencoding"><code>hash.digest()</code></a> methods:</p>
<pre class="with-13-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">const</span> {
createHash,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to hash'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createHash,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to hash'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50</span></code><button class="copy-button">copy</button></pre>
<h4><code>hash.copy([options])</code><span><a class="mark" href="#all_crypto_hashcopyoptions" id="all_crypto_hashcopyoptions">#</a></span><a aria-hidden="true" class="legacy" id="crypto_hash_copy_options"></a></h4>
<div class="api_metadata">
<span>Added in: v13.1.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 href="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#all_crypto_class-hash" class="type"><Hash></a></li>
</ul>
<p>Creates a new <code>Hash</code> object that contains a deep copy of the internal state
of the current <code>Hash</code> object.</p>
<p>The optional <code>options</code> argument controls stream behavior. For XOF hash
functions such as <code>'shake256'</code>, the <code>outputLength</code> option can be used to
specify the desired output length in bytes.</p>
<p>An error is thrown when an attempt is made to copy the <code>Hash</code> object after
its <a href="#all_crypto_hashdigestencoding"><code>hash.digest()</code></a> method has been called.</p>
<pre class="with-28-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// Calculate a rolling hash.</span>
<span class="hljs-keyword">const</span> {
createHash,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'one'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">copy</span>().<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'two'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">copy</span>().<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'three'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">copy</span>().<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Etc.</span></code><code class="language-js cjs"><span class="hljs-comment">// Calculate a rolling hash.</span>
<span class="hljs-keyword">const</span> {
createHash,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'one'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">copy</span>().<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'two'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">copy</span>().<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'three'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">copy</span>().<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Etc.</span></code><button class="copy-button">copy</button></pre>
<h4><code>hash.digest([encoding])</code><span><a class="mark" href="#all_crypto_hashdigestencoding" id="all_crypto_hashdigestencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_hash_digest_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.92</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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Calculates the digest of all of the data passed to be hashed (using the
<a href="#all_crypto_hashupdatedata-inputencoding"><code>hash.update()</code></a> method).
If <code>encoding</code> is provided a string will be returned; otherwise
a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<p>The <code>Hash</code> object can not be used again after <code>hash.digest()</code> method has been
called. Multiple calls will cause an error to be thrown.</p>
<h4><code>hash.update(data[, inputEncoding])</code><span><a class="mark" href="#all_crypto_hashupdatedata-inputencoding" id="all_crypto_hashupdatedata-inputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_hash_update_data_inputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>data</code> string.</li>
</ul>
<p>Updates the hash content with the given <code>data</code>, the encoding of which
is given in <code>inputEncoding</code>.
If <code>encoding</code> is not provided, and the <code>data</code> is a string, an
encoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>, then <code>inputEncoding</code> is ignored.</p>
<p>This can be called many times with new data as it is streamed.</p>
</section><section><h3>Class: <code>Hmac</code><span><a class="mark" href="#all_crypto_class-hmac" id="all_crypto_class-hmac">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_hmac"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamtransform" class="type"><stream.Transform></a></li>
</ul>
<p>The <code>Hmac</code> class is a utility for creating cryptographic HMAC digests. It can
be used in one of two ways:</p>
<ul>
<li>As a <a href="stream.html">stream</a> that is both readable and writable, where data is written
to produce a computed HMAC digest on the readable side, or</li>
<li>Using the <a href="#all_crypto_hmacupdatedata-inputencoding"><code>hmac.update()</code></a> and <a href="#all_crypto_hmacdigestencoding"><code>hmac.digest()</code></a> methods to produce the
computed HMAC digest.</li>
</ul>
<p>The <a href="#all_crypto_cryptocreatehmacalgorithm-key-options"><code>crypto.createHmac()</code></a> method is used to create <code>Hmac</code> instances. <code>Hmac</code>
objects are not to be created directly using the <code>new</code> keyword.</p>
<p>Example: Using <code>Hmac</code> objects as streams:</p>
<pre class="with-13-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">const</span> {
createHmac,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);
hmac.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Only one element is going to be produced by the</span>
<span class="hljs-comment">// hash stream.</span>
<span class="hljs-keyword">const</span> data = hmac.<span class="hljs-title function_">read</span>();
<span class="hljs-keyword">if</span> (data) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e</span>
}
});
hmac.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to hash'</span>);
hmac.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createHmac,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);
hmac.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Only one element is going to be produced by the</span>
<span class="hljs-comment">// hash stream.</span>
<span class="hljs-keyword">const</span> data = hmac.<span class="hljs-title function_">read</span>();
<span class="hljs-keyword">if</span> (data) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e</span>
}
});
hmac.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to hash'</span>);
hmac.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<p>Example: Using <code>Hmac</code> and piped streams:</p>
<pre class="with-43-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> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> {
createHmac,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);
<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.js'</span>);
input.<span class="hljs-title function_">pipe</span>(hmac).<span class="hljs-title function_">pipe</span>(stdout);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createReadStream,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> {
createHmac,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { stdout } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);
<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.js'</span>);
input.<span class="hljs-title function_">pipe</span>(hmac).<span class="hljs-title function_">pipe</span>(stdout);</code><button class="copy-button">copy</button></pre>
<p>Example: Using the <a href="#all_crypto_hmacupdatedata-inputencoding"><code>hmac.update()</code></a> and <a href="#all_crypto_hmacdigestencoding"><code>hmac.digest()</code></a> methods:</p>
<pre class="with-13-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">const</span> {
createHmac,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);
hmac.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to hash'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hmac.<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createHmac,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);
hmac.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to hash'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hmac.<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e</span></code><button class="copy-button">copy</button></pre>
<h4><code>hmac.digest([encoding])</code><span><a class="mark" href="#all_crypto_hmacdigestencoding" id="all_crypto_hmacdigestencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_hmac_digest_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.94</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 <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Calculates the HMAC digest of all of the data passed using <a href="#all_crypto_hmacupdatedata-inputencoding"><code>hmac.update()</code></a>.
If <code>encoding</code> is
provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned;</p>
<p>The <code>Hmac</code> object can not be used again after <code>hmac.digest()</code> has been
called. Multiple calls to <code>hmac.digest()</code> will result in an error being thrown.</p>
<h4><code>hmac.update(data[, inputEncoding])</code><span><a class="mark" href="#all_crypto_hmacupdatedata-inputencoding" id="all_crypto_hmacupdatedata-inputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_hmac_update_data_inputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>data</code> string.</li>
</ul>
<p>Updates the <code>Hmac</code> content with the given <code>data</code>, the encoding of which
is given in <code>inputEncoding</code>.
If <code>encoding</code> is not provided, and the <code>data</code> is a string, an
encoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>, then <code>inputEncoding</code> is ignored.</p>
<p>This can be called many times with new data as it is streamed.</p>
</section><section><h3>Class: <code>KeyObject</code><span><a class="mark" href="#all_crypto_class-keyobject" id="all_crypto_class-keyobject">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_keyobject"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Instances of this class can now be passed to worker threads using <code>postMessage</code>.</p></td></tr>
<tr><td>v11.13.0</td>
<td><p>This class is now exported.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p><span>Added in: v11.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Node.js uses a <code>KeyObject</code> class to represent a symmetric or asymmetric key,
and each kind of key exposes different functions. The
<a href="#all_crypto_cryptocreatesecretkeykey-encoding"><code>crypto.createSecretKey()</code></a>, <a href="#all_crypto_cryptocreatepublickeykey"><code>crypto.createPublicKey()</code></a> and
<a href="#all_crypto_cryptocreateprivatekeykey"><code>crypto.createPrivateKey()</code></a> methods are used to create <code>KeyObject</code>
instances. <code>KeyObject</code> objects are not to be created directly using the <code>new</code>
keyword.</p>
<p>Most applications should consider using the new <code>KeyObject</code> API instead of
passing keys as strings or <code>Buffer</code>s due to improved security features.</p>
<p><code>KeyObject</code> instances can be passed to other threads via <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>postMessage()</code></a>.
The receiver obtains a cloned <code>KeyObject</code>, and the <code>KeyObject</code> does not need to
be listed in the <code>transferList</code> argument.</p>
<h4>Static method: <code>KeyObject.from(key)</code><span><a class="mark" href="#all_crypto_static-method-keyobjectfromkey" id="all_crypto_static-method-keyobjectfromkey">#</a></span><a aria-hidden="true" class="legacy" id="crypto_static_method_keyobject_from_key"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>key</code> <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li>Returns: <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
</ul>
<p>Example: Converting a <code>CryptoKey</code> instance to a <code>KeyObject</code>:</p>
<pre class="with-50-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">const</span> { <span class="hljs-title class_">KeyObject</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
<span class="hljs-attr">hash</span>: <span class="hljs-string">'SHA-256'</span>,
<span class="hljs-attr">length</span>: <span class="hljs-number">256</span>,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);
<span class="hljs-keyword">const</span> keyObject = <span class="hljs-title class_">KeyObject</span>.<span class="hljs-title function_">from</span>(key);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(keyObject.<span class="hljs-property">symmetricKeySize</span>);
<span class="hljs-comment">// Prints: 32 (symmetric key size in bytes)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">KeyObject</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
<span class="hljs-attr">hash</span>: <span class="hljs-string">'SHA-256'</span>,
<span class="hljs-attr">length</span>: <span class="hljs-number">256</span>,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);
<span class="hljs-keyword">const</span> keyObject = <span class="hljs-title class_">KeyObject</span>.<span class="hljs-title function_">from</span>(key);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(keyObject.<span class="hljs-property">symmetricKeySize</span>);
<span class="hljs-comment">// Prints: 32 (symmetric key size in bytes)</span>
})();</code><button class="copy-button">copy</button></pre>
<h4><code>keyObject.asymmetricKeyDetails</code><span><a class="mark" href="#all_crypto_keyobjectasymmetrickeydetails" id="all_crypto_keyobjectasymmetrickeydetails">#</a></span><a aria-hidden="true" class="legacy" id="crypto_keyobject_asymmetrickeydetails"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.9.0</td>
<td><p>Expose <code>RSASSA-PSS-params</code> sequence parameters for RSA-PSS keys.</p></td></tr>
<tr><td>v15.7.0</td>
<td><p><span>Added in: v15.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>modulusLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Key size in bits (RSA, DSA).</li>
<li><code>publicExponent</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> Public exponent (RSA).</li>
<li><code>hashAlgorithm</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the message digest (RSA-PSS).</li>
<li><code>mgf1HashAlgorithm</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the message digest used by
MGF1 (RSA-PSS).</li>
<li><code>saltLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Minimal salt length in bytes (RSA-PSS).</li>
<li><code>divisorLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Size of <code>q</code> in bits (DSA).</li>
<li><code>namedCurve</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the curve (EC).</li>
</ul>
</li>
</ul>
<p>This property exists only on asymmetric keys. Depending on the type of the key,
this object contains information about the key. None of the information obtained
through this property can be used to uniquely identify a key or to compromise
the security of the key.</p>
<p>For RSA-PSS keys, if the key material contains a <code>RSASSA-PSS-params</code> sequence,
the <code>hashAlgorithm</code>, <code>mgf1HashAlgorithm</code>, and <code>saltLength</code> properties will be
set.</p>
<p>Other key details might be exposed via this API using additional attributes.</p>
<h4><code>keyObject.asymmetricKeyType</code><span><a class="mark" href="#all_crypto_keyobjectasymmetrickeytype" id="all_crypto_keyobjectasymmetrickeytype">#</a></span><a aria-hidden="true" class="legacy" id="crypto_keyobject_asymmetrickeytype"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.9.0, v12.17.0</td>
<td><p>Added support for <code>'dh'</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Added support for <code>'rsa-pss'</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>This property now returns <code>undefined</code> for KeyObject instances of unrecognized type instead of aborting.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Added support for <code>'x25519'</code> and <code>'x448'</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Added support for <code>'ed25519'</code> and <code>'ed448'</code>.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p><span>Added in: v11.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>For asymmetric keys, this property represents the type of the key. Supported key
types are:</p>
<ul>
<li><code>'rsa'</code> (OID 1.2.840.113549.1.1.1)</li>
<li><code>'rsa-pss'</code> (OID 1.2.840.113549.1.1.10)</li>
<li><code>'dsa'</code> (OID 1.2.840.10040.4.1)</li>
<li><code>'ec'</code> (OID 1.2.840.10045.2.1)</li>
<li><code>'x25519'</code> (OID 1.3.101.110)</li>
<li><code>'x448'</code> (OID 1.3.101.111)</li>
<li><code>'ed25519'</code> (OID 1.3.101.112)</li>
<li><code>'ed448'</code> (OID 1.3.101.113)</li>
<li><code>'dh'</code> (OID 1.2.840.113549.1.3.1)</li>
</ul>
<p>This property is <code>undefined</code> for unrecognized <code>KeyObject</code> types and symmetric
keys.</p>
<h4><code>keyObject.export([options])</code><span><a class="mark" href="#all_crypto_keyobjectexportoptions" id="all_crypto_keyobjectexportoptions">#</a></span><a aria-hidden="true" class="legacy" id="crypto_keyobject_export_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>v15.9.0</td>
<td><p>Added support for <code>'jwk'</code> format.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p><span>Added in: v11.6.0</span></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></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>For symmetric keys, the following encoding options can be used:</p>
<ul>
<li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'buffer'</code> (default) or <code>'jwk'</code>.</li>
</ul>
<p>For public keys, the following encoding options can be used:</p>
<ul>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'pkcs1'</code> (RSA only) or <code>'spki'</code>.</li>
<li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'pem'</code>, <code>'der'</code>, or <code>'jwk'</code>.</li>
</ul>
<p>For private keys, the following encoding options can be used:</p>
<ul>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'pkcs1'</code> (RSA only), <code>'pkcs8'</code> or
<code>'sec1'</code> (EC only).</li>
<li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'pem'</code>, <code>'der'</code>, or <code>'jwk'</code>.</li>
<li><code>cipher</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If specified, the private key will be encrypted with
the given <code>cipher</code> and <code>passphrase</code> using PKCS#5 v2.0 password based
encryption.</li>
<li><code>passphrase</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The passphrase to use for encryption, see
<code>cipher</code>.</li>
</ul>
<p>The result type depends on the selected encoding format, when PEM the
result is a string, when DER it will be a buffer containing the data
encoded as DER, when <a href="https://tools.ietf.org/html/rfc7517">JWK</a> it will be an object.</p>
<p>When <a href="https://tools.ietf.org/html/rfc7517">JWK</a> encoding format was selected, all other encoding options are
ignored.</p>
<p>PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of
the <code>cipher</code> and <code>format</code> options. The PKCS#8 <code>type</code> can be used with any
<code>format</code> to encrypt any key algorithm (RSA, EC, or DH) by specifying a
<code>cipher</code>. PKCS#1 and SEC1 can only be encrypted by specifying a <code>cipher</code>
when the PEM <code>format</code> is used. For maximum compatibility, use PKCS#8 for
encrypted private keys. Since PKCS#8 defines its own
encryption mechanism, PEM-level encryption is not supported when encrypting
a PKCS#8 key. See <a href="https://www.rfc-editor.org/rfc/rfc5208.txt">RFC 5208</a> for PKCS#8 encryption and <a href="https://www.rfc-editor.org/rfc/rfc1421.txt">RFC 1421</a> for
PKCS#1 and SEC1 encryption.</p>
<h4><code>keyObject.equals(otherKeyObject)</code><span><a class="mark" href="#all_crypto_keyobjectequalsotherkeyobject" id="all_crypto_keyobjectequalsotherkeyobject">#</a></span><a aria-hidden="true" class="legacy" id="crypto_keyobject_equals_otherkeyobject"></a></h4>
<div class="api_metadata">
<span>Added in: v17.7.0, v16.15.0</span>
</div>
<ul>
<li><code>otherKeyObject</code>: <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a> A <code>KeyObject</code> with which to
compare <code>keyObject</code>.</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 <code>true</code> or <code>false</code> depending on whether the keys have exactly the same
type, value, and parameters. This method is not
<a href="https://en.wikipedia.org/wiki/Timing_attack">constant time</a>.</p>
<h4><code>keyObject.symmetricKeySize</code><span><a class="mark" href="#all_crypto_keyobjectsymmetrickeysize" id="all_crypto_keyobjectsymmetrickeysize">#</a></span><a aria-hidden="true" class="legacy" id="crypto_keyobject_symmetrickeysize"></a></h4>
<div class="api_metadata">
<span>Added in: v11.6.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>For secret keys, this property represents the size of the key in bytes. This
property is <code>undefined</code> for asymmetric keys.</p>
<h4><code>keyObject.type</code><span><a class="mark" href="#all_crypto_keyobjecttype" id="all_crypto_keyobjecttype">#</a></span><a aria-hidden="true" class="legacy" id="crypto_keyobject_type"></a></h4>
<div class="api_metadata">
<span>Added in: v11.6.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Depending on the type of this <code>KeyObject</code>, this property is either
<code>'secret'</code> for secret (symmetric) keys, <code>'public'</code> for public (asymmetric) keys
or <code>'private'</code> for private (asymmetric) keys.</p>
</section><section><h3>Class: <code>Sign</code><span><a class="mark" href="#all_crypto_class-sign" id="all_crypto_class-sign">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_sign"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a></li>
</ul>
<p>The <code>Sign</code> class is a utility for generating signatures. It can be used in one
of two ways:</p>
<ul>
<li>As a writable <a href="stream.html">stream</a>, where data to be signed is written and the
<a href="#all_crypto_signsignprivatekey-outputencoding"><code>sign.sign()</code></a> method is used to generate and return the signature, or</li>
<li>Using the <a href="#all_crypto_signupdatedata-inputencoding"><code>sign.update()</code></a> and <a href="#all_crypto_signsignprivatekey-outputencoding"><code>sign.sign()</code></a> methods to produce the
signature.</li>
</ul>
<p>The <a href="#all_crypto_cryptocreatesignalgorithm-options"><code>crypto.createSign()</code></a> method is used to create <code>Sign</code> instances. The
argument is the string name of the hash function to use. <code>Sign</code> objects are not
to be created directly using the <code>new</code> keyword.</p>
<p>Example: Using <code>Sign</code> and <a href="#all_crypto_class-verify"><code>Verify</code></a> objects as streams:</p>
<pre class="with-22-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">const</span> {
generateKeyPairSync,
createSign,
createVerify,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { privateKey, publicKey } = <span class="hljs-title function_">generateKeyPairSync</span>(<span class="hljs-string">'ec'</span>, {
<span class="hljs-attr">namedCurve</span>: <span class="hljs-string">'sect239k1'</span>,
});
<span class="hljs-keyword">const</span> sign = <span class="hljs-title function_">createSign</span>(<span class="hljs-string">'SHA256'</span>);
sign.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to sign'</span>);
sign.<span class="hljs-title function_">end</span>();
<span class="hljs-keyword">const</span> signature = sign.<span class="hljs-title function_">sign</span>(privateKey, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> verify = <span class="hljs-title function_">createVerify</span>(<span class="hljs-string">'SHA256'</span>);
verify.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to sign'</span>);
verify.<span class="hljs-title function_">end</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(verify.<span class="hljs-title function_">verify</span>(publicKey, signature, <span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: true</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
generateKeyPairSync,
createSign,
createVerify,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { privateKey, publicKey } = <span class="hljs-title function_">generateKeyPairSync</span>(<span class="hljs-string">'ec'</span>, {
<span class="hljs-attr">namedCurve</span>: <span class="hljs-string">'sect239k1'</span>,
});
<span class="hljs-keyword">const</span> sign = <span class="hljs-title function_">createSign</span>(<span class="hljs-string">'SHA256'</span>);
sign.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to sign'</span>);
sign.<span class="hljs-title function_">end</span>();
<span class="hljs-keyword">const</span> signature = sign.<span class="hljs-title function_">sign</span>(privateKey, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> verify = <span class="hljs-title function_">createVerify</span>(<span class="hljs-string">'SHA256'</span>);
verify.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to sign'</span>);
verify.<span class="hljs-title function_">end</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(verify.<span class="hljs-title function_">verify</span>(publicKey, signature, <span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: true</span></code><button class="copy-button">copy</button></pre>
<p>Example: Using the <a href="#all_crypto_signupdatedata-inputencoding"><code>sign.update()</code></a> and <a href="#all_crypto_verifyupdatedata-inputencoding"><code>verify.update()</code></a> methods:</p>
<pre class="with-22-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">const</span> {
generateKeyPairSync,
createSign,
createVerify,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { privateKey, publicKey } = <span class="hljs-title function_">generateKeyPairSync</span>(<span class="hljs-string">'rsa'</span>, {
<span class="hljs-attr">modulusLength</span>: <span class="hljs-number">2048</span>,
});
<span class="hljs-keyword">const</span> sign = <span class="hljs-title function_">createSign</span>(<span class="hljs-string">'SHA256'</span>);
sign.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to sign'</span>);
sign.<span class="hljs-title function_">end</span>();
<span class="hljs-keyword">const</span> signature = sign.<span class="hljs-title function_">sign</span>(privateKey);
<span class="hljs-keyword">const</span> verify = <span class="hljs-title function_">createVerify</span>(<span class="hljs-string">'SHA256'</span>);
verify.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to sign'</span>);
verify.<span class="hljs-title function_">end</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(verify.<span class="hljs-title function_">verify</span>(publicKey, signature));
<span class="hljs-comment">// Prints: true</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
generateKeyPairSync,
createSign,
createVerify,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { privateKey, publicKey } = <span class="hljs-title function_">generateKeyPairSync</span>(<span class="hljs-string">'rsa'</span>, {
<span class="hljs-attr">modulusLength</span>: <span class="hljs-number">2048</span>,
});
<span class="hljs-keyword">const</span> sign = <span class="hljs-title function_">createSign</span>(<span class="hljs-string">'SHA256'</span>);
sign.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to sign'</span>);
sign.<span class="hljs-title function_">end</span>();
<span class="hljs-keyword">const</span> signature = sign.<span class="hljs-title function_">sign</span>(privateKey);
<span class="hljs-keyword">const</span> verify = <span class="hljs-title function_">createVerify</span>(<span class="hljs-string">'SHA256'</span>);
verify.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to sign'</span>);
verify.<span class="hljs-title function_">end</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(verify.<span class="hljs-title function_">verify</span>(publicKey, signature));
<span class="hljs-comment">// Prints: true</span></code><button class="copy-button">copy</button></pre>
<h4><code>sign.sign(privateKey[, outputEncoding])</code><span><a class="mark" href="#all_crypto_signsignprivatekey-outputencoding" id="all_crypto_signsignprivatekey-outputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_sign_sign_privatekey_outputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The privateKey can also be an ArrayBuffer and CryptoKey.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>This function now supports IEEE-P1363 DSA and ECDSA signatures.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>This function now supports RSA-PSS keys.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>This function now supports key objects.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Support for RSASSA-PSS and additional options was added.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>privateKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>
<ul>
<li><code>dsaEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
</li>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Calculates the signature on all the data passed through using either
<a href="#all_crypto_signupdatedata-inputencoding"><code>sign.update()</code></a> or <a href="#all_stream_writablewritechunk-encoding-callback"><code>sign.write()</code></a>.</p>
<p>If <code>privateKey</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>privateKey</code> had been passed to <a href="#all_crypto_cryptocreateprivatekeykey"><code>crypto.createPrivateKey()</code></a>. If it is an
object, the following additional properties can be passed:</p>
<ul>
<li>
<p><code>dsaEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> For DSA and ECDSA, this option specifies the
format of the generated signature. It can be one of the following:</p>
<ul>
<li><code>'der'</code> (default): DER-encoded ASN.1 signature structure encoding <code>(r, s)</code>.</li>
<li><code>'ieee-p1363'</code>: Signature format <code>r || s</code> as proposed in IEEE-P1363.</li>
</ul>
</li>
<li>
<p><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Optional padding value for RSA, one of the following:</p>
<ul>
<li><code>crypto.constants.RSA_PKCS1_PADDING</code> (default)</li>
<li><code>crypto.constants.RSA_PKCS1_PSS_PADDING</code></li>
</ul>
<p><code>RSA_PKCS1_PSS_PADDING</code> will use MGF1 with the same hash function
used to sign the message as specified in section 3.1 of <a href="https://www.rfc-editor.org/rfc/rfc4055.txt">RFC 4055</a>, unless
an MGF1 hash function has been specified as part of the key in compliance with
section 3.3 of <a href="https://www.rfc-editor.org/rfc/rfc4055.txt">RFC 4055</a>.</p>
</li>
<li>
<p><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Salt length for when padding is
<code>RSA_PKCS1_PSS_PADDING</code>. The special value
<code>crypto.constants.RSA_PSS_SALTLEN_DIGEST</code> sets the salt length to the digest
size, <code>crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN</code> (default) sets it to the
maximum permissible value.</p>
</li>
</ul>
<p>If <code>outputEncoding</code> is provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a>
is returned.</p>
<p>The <code>Sign</code> object can not be again used after <code>sign.sign()</code> method has been
called. Multiple calls to <code>sign.sign()</code> will result in an error being thrown.</p>
<h4><code>sign.update(data[, inputEncoding])</code><span><a class="mark" href="#all_crypto_signupdatedata-inputencoding" id="all_crypto_signupdatedata-inputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_sign_update_data_inputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>data</code> string.</li>
</ul>
<p>Updates the <code>Sign</code> content with the given <code>data</code>, the encoding of which
is given in <code>inputEncoding</code>.
If <code>encoding</code> is not provided, and the <code>data</code> is a string, an
encoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>, then <code>inputEncoding</code> is ignored.</p>
<p>This can be called many times with new data as it is streamed.</p>
</section><section><h3>Class: <code>Verify</code><span><a class="mark" href="#all_crypto_class-verify" id="all_crypto_class-verify">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_verify"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a></li>
</ul>
<p>The <code>Verify</code> class is a utility for verifying signatures. It can be used in one
of two ways:</p>
<ul>
<li>As a writable <a href="stream.html">stream</a> where written data is used to validate against the
supplied signature, or</li>
<li>Using the <a href="#all_crypto_verifyupdatedata-inputencoding"><code>verify.update()</code></a> and <a href="#all_crypto_verifyverifyobject-signature-signatureencoding"><code>verify.verify()</code></a> methods to verify
the signature.</li>
</ul>
<p>The <a href="#all_crypto_cryptocreateverifyalgorithm-options"><code>crypto.createVerify()</code></a> method is used to create <code>Verify</code> instances.
<code>Verify</code> objects are not to be created directly using the <code>new</code> keyword.</p>
<p>See <a href="#all_crypto_class-sign"><code>Sign</code></a> for examples.</p>
<h4><code>verify.update(data[, inputEncoding])</code><span><a class="mark" href="#all_crypto_verifyupdatedata-inputencoding" id="all_crypto_verifyupdatedata-inputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_verify_update_data_inputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>data</code> string.</li>
</ul>
<p>Updates the <code>Verify</code> content with the given <code>data</code>, the encoding of which
is given in <code>inputEncoding</code>.
If <code>inputEncoding</code> is not provided, and the <code>data</code> is a string, an
encoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>, then <code>inputEncoding</code> is ignored.</p>
<p>This can be called many times with new data as it is streamed.</p>
<h4><code>verify.verify(object, signature[, signatureEncoding])</code><span><a class="mark" href="#all_crypto_verifyverifyobject-signature-signatureencoding" id="all_crypto_verifyverifyobject-signature-signatureencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_verify_verify_object_signature_signatureencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The object can also be an ArrayBuffer and CryptoKey.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>This function now supports IEEE-P1363 DSA and ECDSA signatures.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>This function now supports RSA-PSS keys.</p></td></tr>
<tr><td>v11.7.0</td>
<td><p>The key can now be a private key.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Support for RSASSA-PSS and additional options was added.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>
<ul>
<li><code>dsaEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
</li>
<li><code>signature</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>signatureEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>signature</code> string.</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> or <code>false</code> depending on the validity of the
signature for the data and public key.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Verifies the provided data using the given <code>object</code> and <code>signature</code>.</p>
<p>If <code>object</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>object</code> had been passed to <a href="#all_crypto_cryptocreatepublickeykey"><code>crypto.createPublicKey()</code></a>. If it is an
object, the following additional properties can be passed:</p>
<ul>
<li>
<p><code>dsaEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> For DSA and ECDSA, this option specifies the
format of the signature. It can be one of the following:</p>
<ul>
<li><code>'der'</code> (default): DER-encoded ASN.1 signature structure encoding <code>(r, s)</code>.</li>
<li><code>'ieee-p1363'</code>: Signature format <code>r || s</code> as proposed in IEEE-P1363.</li>
</ul>
</li>
<li>
<p><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Optional padding value for RSA, one of the following:</p>
<ul>
<li><code>crypto.constants.RSA_PKCS1_PADDING</code> (default)</li>
<li><code>crypto.constants.RSA_PKCS1_PSS_PADDING</code></li>
</ul>
<p><code>RSA_PKCS1_PSS_PADDING</code> will use MGF1 with the same hash function
used to verify the message as specified in section 3.1 of <a href="https://www.rfc-editor.org/rfc/rfc4055.txt">RFC 4055</a>, unless
an MGF1 hash function has been specified as part of the key in compliance with
section 3.3 of <a href="https://www.rfc-editor.org/rfc/rfc4055.txt">RFC 4055</a>.</p>
</li>
<li>
<p><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Salt length for when padding is
<code>RSA_PKCS1_PSS_PADDING</code>. The special value
<code>crypto.constants.RSA_PSS_SALTLEN_DIGEST</code> sets the salt length to the digest
size, <code>crypto.constants.RSA_PSS_SALTLEN_AUTO</code> (default) causes it to be
determined automatically.</p>
</li>
</ul>
<p>The <code>signature</code> argument is the previously calculated signature for the data, in
the <code>signatureEncoding</code>.
If a <code>signatureEncoding</code> is specified, the <code>signature</code> is expected to be a
string; otherwise <code>signature</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>,
<code>TypedArray</code>, or <code>DataView</code>.</p>
<p>The <code>verify</code> object can not be used again after <code>verify.verify()</code> has been
called. Multiple calls to <code>verify.verify()</code> will result in an error being
thrown.</p>
<p>Because public keys can be derived from private keys, a private key may
be passed instead of a public key.</p>
</section><section><h3>Class: <code>X509Certificate</code><span><a class="mark" href="#all_crypto_class-x509certificate" id="all_crypto_class-x509certificate">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_x509certificate"></a></h3>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<p>Encapsulates an X509 certificate and provides read-only access to
its information.</p>
<pre class="with-56-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">const</span> { X509Certificate } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> x509 = <span class="hljs-keyword">new</span> <span class="hljs-title function_">X509Certificate</span>(<span class="hljs-string">'{... pem encoded cert ...}'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x509.<span class="hljs-property">subject</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { X509Certificate } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> x509 = <span class="hljs-keyword">new</span> <span class="hljs-title function_">X509Certificate</span>(<span class="hljs-string">'{... pem encoded cert ...}'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x509.<span class="hljs-property">subject</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>new X509Certificate(buffer)</code><span><a class="mark" href="#all_crypto_new-x509certificatebuffer" id="all_crypto_new-x509certificatebuffer">#</a></span><a aria-hidden="true" class="legacy" id="crypto_new_x509certificate_buffer"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li><code>buffer</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/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> A PEM or DER encoded
X509 Certificate.</li>
</ul>
<h4><code>x509.ca</code><span><a class="mark" href="#all_crypto_x509ca" id="all_crypto_x509ca">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_ca"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Will be <code>true</code> if this is a Certificate Authority (CA)
certificate.</li>
</ul>
<h4><code>x509.checkEmail(email[, options])</code><span><a class="mark" href="#all_crypto_x509checkemailemail-options" id="all_crypto_x509checkemailemail-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_checkemail_email_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</td>
<td><p>The subject option now defaults to <code>'default'</code>.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>The subject option can now be set to <code>'default'</code>.</p></td></tr>
<tr><td>v17.5.0, v16.14.1</td>
<td><p>The <code>wildcards</code>, <code>partialWildcards</code>, <code>multiLabelWildcards</code>, and <code>singleLabelSubdomains</code> options have been removed since they had no effect.</p></td></tr>
<tr><td>v15.6.0</td>
<td><p><span>Added in: v15.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>email</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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>subject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <code>'default'</code>, <code>'always'</code>, or <code>'never'</code>.
<strong>Default:</strong> <code>'default'</code>.</li>
</ul>
</li>
<li>Returns: <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#Undefined_type" class="type"><undefined></a> Returns <code>email</code> if the certificate matches,
<code>undefined</code> if it does not.</li>
</ul>
<p>Checks whether the certificate matches the given email address.</p>
<p>If the <code>'subject'</code> option is undefined or set to <code>'default'</code>, the certificate
subject is only considered if the subject alternative name extension either does
not exist or does not contain any email addresses.</p>
<p>If the <code>'subject'</code> option is set to <code>'always'</code> and if the subject alternative
name extension either does not exist or does not contain a matching email
address, the certificate subject is considered.</p>
<p>If the <code>'subject'</code> option is set to <code>'never'</code>, the certificate subject is never
considered, even if the certificate contains no subject alternative names.</p>
<h4><code>x509.checkHost(name[, options])</code><span><a class="mark" href="#all_crypto_x509checkhostname-options" id="all_crypto_x509checkhostname-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_checkhost_name_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</td>
<td><p>The subject option now defaults to <code>'default'</code>.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>The subject option can now be set to <code>'default'</code>.</p></td></tr>
<tr><td>v15.6.0</td>
<td><p><span>Added in: v15.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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>subject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <code>'default'</code>, <code>'always'</code>, or <code>'never'</code>.
<strong>Default:</strong> <code>'default'</code>.</li>
<li><code>wildcards</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</code>.</li>
<li><code>partialWildcards</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</code>.</li>
<li><code>multiLabelWildcards</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code>.</li>
<li><code>singleLabelSubdomains</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <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#Undefined_type" class="type"><undefined></a> Returns a subject name that matches <code>name</code>,
or <code>undefined</code> if no subject name matches <code>name</code>.</li>
</ul>
<p>Checks whether the certificate matches the given host name.</p>
<p>If the certificate matches the given host name, the matching subject name is
returned. The returned name might be an exact match (e.g., <code>foo.example.com</code>)
or it might contain wildcards (e.g., <code>*.example.com</code>). Because host name
comparisons are case-insensitive, the returned subject name might also differ
from the given <code>name</code> in capitalization.</p>
<p>If the <code>'subject'</code> option is undefined or set to <code>'default'</code>, the certificate
subject is only considered if the subject alternative name extension either does
not exist or does not contain any DNS names. This behavior is consistent with
<a href="https://www.rfc-editor.org/rfc/rfc2818.txt">RFC 2818</a> ("HTTP Over TLS").</p>
<p>If the <code>'subject'</code> option is set to <code>'always'</code> and if the subject alternative
name extension either does not exist or does not contain a matching DNS name,
the certificate subject is considered.</p>
<p>If the <code>'subject'</code> option is set to <code>'never'</code>, the certificate subject is never
considered, even if the certificate contains no subject alternative names.</p>
<h4><code>x509.checkIP(ip)</code><span><a class="mark" href="#all_crypto_x509checkipip" id="all_crypto_x509checkipip">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_checkip_ip"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.5.0, v16.14.1</td>
<td><p>The <code>options</code> argument has been removed since it had no effect.</p></td></tr>
<tr><td>v15.6.0</td>
<td><p><span>Added in: v15.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>ip</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <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#Undefined_type" class="type"><undefined></a> Returns <code>ip</code> if the certificate matches,
<code>undefined</code> if it does not.</li>
</ul>
<p>Checks whether the certificate matches the given IP address (IPv4 or IPv6).</p>
<p>Only <a href="https://www.rfc-editor.org/rfc/rfc5280.txt">RFC 5280</a> <code>iPAddress</code> subject alternative names are considered, and they
must match the given <code>ip</code> address exactly. Other subject alternative names as
well as the subject field of the certificate are ignored.</p>
<h4><code>x509.checkIssued(otherCert)</code><span><a class="mark" href="#all_crypto_x509checkissuedothercert" id="all_crypto_x509checkissuedothercert">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_checkissued_othercert"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li><code>otherCert</code> <a href="#all_crypto_class-x509certificate" class="type"><X509Certificate></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>Checks whether this certificate was issued by the given <code>otherCert</code>.</p>
<h4><code>x509.checkPrivateKey(privateKey)</code><span><a class="mark" href="#all_crypto_x509checkprivatekeyprivatekey" id="all_crypto_x509checkprivatekeyprivatekey">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_checkprivatekey_privatekey"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li><code>privateKey</code> <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a> A private key.</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>Checks whether the public key for this certificate is consistent with
the given private key.</p>
<h4><code>x509.fingerprint</code><span><a class="mark" href="#all_crypto_x509fingerprint" id="all_crypto_x509fingerprint">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_fingerprint"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The SHA-1 fingerprint of this certificate.</p>
<p>Because SHA-1 is cryptographically broken and because the security of SHA-1 is
significantly worse than that of algorithms that are commonly used to sign
certificates, consider using <a href="#all_crypto_x509fingerprint256"><code>x509.fingerprint256</code></a> instead.</p>
<h4><code>x509.fingerprint256</code><span><a class="mark" href="#all_crypto_x509fingerprint256" id="all_crypto_x509fingerprint256">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_fingerprint256"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The SHA-256 fingerprint of this certificate.</p>
<h4><code>x509.fingerprint512</code><span><a class="mark" href="#all_crypto_x509fingerprint512" id="all_crypto_x509fingerprint512">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_fingerprint512"></a></h4>
<div class="api_metadata">
<span>Added in: v17.2.0, v16.14.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The SHA-512 fingerprint of this certificate.</p>
<p>Because computing the SHA-256 fingerprint is usually faster and because it is
only half the size of the SHA-512 fingerprint, <a href="#all_crypto_x509fingerprint256"><code>x509.fingerprint256</code></a> may be
a better choice. While SHA-512 presumably provides a higher level of security in
general, the security of SHA-256 matches that of most algorithms that are
commonly used to sign certificates.</p>
<h4><code>x509.infoAccess</code><span><a class="mark" href="#all_crypto_x509infoaccess" id="all_crypto_x509infoaccess">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_infoaccess"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.3.1, v16.13.2</td>
<td><p>Parts of this string may be encoded as JSON string literals in response to CVE-2021-44532.</p></td></tr>
<tr><td>v15.6.0</td>
<td><p><span>Added in: v15.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>A textual representation of the certificate's authority information access
extension.</p>
<p>This is a line feed separated list of access descriptions. Each line begins with
the access method and the kind of the access location, followed by a colon and
the value associated with the access location.</p>
<p>After the prefix denoting the access method and the kind of the access location,
the remainder of each line might be enclosed in quotes to indicate that the
value is a JSON string literal. For backward compatibility, Node.js only uses
JSON string literals within this property when necessary to avoid ambiguity.
Third-party code should be prepared to handle both possible entry formats.</p>
<h4><code>x509.issuer</code><span><a class="mark" href="#all_crypto_x509issuer" id="all_crypto_x509issuer">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_issuer"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The issuer identification included in this certificate.</p>
<h4><code>x509.issuerCertificate</code><span><a class="mark" href="#all_crypto_x509issuercertificate" id="all_crypto_x509issuercertificate">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_issuercertificate"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0</span>
</div>
<ul>
<li>Type: <a href="#all_crypto_class-x509certificate" class="type"><X509Certificate></a></li>
</ul>
<p>The issuer certificate or <code>undefined</code> if the issuer certificate is not
available.</p>
<h4><code>x509.extKeyUsage</code><span><a class="mark" href="#all_crypto_x509extkeyusage" id="all_crypto_x509extkeyusage">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_extkeyusage"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>An array detailing the key extended usages for this certificate.</p>
<h4><code>x509.publicKey</code><span><a class="mark" href="#all_crypto_x509publickey" id="all_crypto_x509publickey">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_publickey"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
</ul>
<p>The public key <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a> for this certificate.</p>
<h4><code>x509.raw</code><span><a class="mark" href="#all_crypto_x509raw" id="all_crypto_x509raw">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_raw"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>A <code>Buffer</code> containing the DER encoding of this certificate.</p>
<h4><code>x509.serialNumber</code><span><a class="mark" href="#all_crypto_x509serialnumber" id="all_crypto_x509serialnumber">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_serialnumber"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The serial number of this certificate.</p>
<p>Serial numbers are assigned by certificate authorities and do not uniquely
identify certificates. Consider using <a href="#all_crypto_x509fingerprint256"><code>x509.fingerprint256</code></a> as a unique
identifier instead.</p>
<h4><code>x509.subject</code><span><a class="mark" href="#all_crypto_x509subject" id="all_crypto_x509subject">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_subject"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The complete subject of this certificate.</p>
<h4><code>x509.subjectAltName</code><span><a class="mark" href="#all_crypto_x509subjectaltname" id="all_crypto_x509subjectaltname">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_subjectaltname"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.3.1, v16.13.2</td>
<td><p>Parts of this string may be encoded as JSON string literals in response to CVE-2021-44532.</p></td></tr>
<tr><td>v15.6.0</td>
<td><p><span>Added in: v15.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The subject alternative name specified for this certificate.</p>
<p>This is a comma-separated list of subject alternative names. Each entry begins
with a string identifying the kind of the subject alternative name followed by
a colon and the value associated with the entry.</p>
<p>Earlier versions of Node.js incorrectly assumed that it is safe to split this
property at the two-character sequence <code>', '</code> (see <a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532">CVE-2021-44532</a>). However,
both malicious and legitimate certificates can contain subject alternative names
that include this sequence when represented as a string.</p>
<p>After the prefix denoting the type of the entry, the remainder of each entry
might be enclosed in quotes to indicate that the value is a JSON string literal.
For backward compatibility, Node.js only uses JSON string literals within this
property when necessary to avoid ambiguity. Third-party code should be prepared
to handle both possible entry formats.</p>
<h4><code>x509.toJSON()</code><span><a class="mark" href="#all_crypto_x509tojson" id="all_crypto_x509tojson">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_tojson"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>There is no standard JSON encoding for X509 certificates. The
<code>toJSON()</code> method returns a string containing the PEM encoded
certificate.</p>
<h4><code>x509.toLegacyObject()</code><span><a class="mark" href="#all_crypto_x509tolegacyobject" id="all_crypto_x509tolegacyobject">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_tolegacyobject"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns information about this certificate using the legacy
<a href="#all_tls_certificate-object">certificate object</a> encoding.</p>
<h4><code>x509.toString()</code><span><a class="mark" href="#all_crypto_x509tostring" id="all_crypto_x509tostring">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_tostring"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the PEM-encoded certificate.</p>
<h4><code>x509.validFrom</code><span><a class="mark" href="#all_crypto_x509validfrom" id="all_crypto_x509validfrom">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_validfrom"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The date/time from which this certificate is valid.</p>
<h4><code>x509.validTo</code><span><a class="mark" href="#all_crypto_x509validto" id="all_crypto_x509validto">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_validto"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The date/time until which this certificate is valid.</p>
<h4><code>x509.verify(publicKey)</code><span><a class="mark" href="#all_crypto_x509verifypublickey" id="all_crypto_x509verifypublickey">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_verify_publickey"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li><code>publicKey</code> <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a> A public key.</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>Verifies that this certificate was signed by the given public key.
Does not perform any other validation checks on the certificate.</p>
</section><section><h3><code>node:crypto</code> module methods and properties<span><a class="mark" href="#all_crypto_nodecrypto-module-methods-and-properties" id="all_crypto_nodecrypto-module-methods-and-properties">#</a></span><a aria-hidden="true" class="legacy" id="crypto_node_crypto_module_methods_and_properties"></a></h3>
<h4><code>crypto.constants</code><span><a class="mark" href="#all_crypto_cryptoconstants" id="all_crypto_cryptoconstants">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_constants"></a></h4>
<div class="api_metadata">
<span>Added in: v6.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>An object containing commonly used constants for crypto and security related
operations. The specific constants currently defined are described in
<a href="#all_crypto_crypto-constants">Crypto constants</a>.</p>
<h4><code>crypto.fips</code><span><a class="mark" href="#all_crypto_cryptofips" id="all_crypto_cryptofips">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_fips"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span><span>Deprecated since: v10.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p>Property for checking and controlling whether a FIPS compliant crypto provider
is currently in use. Setting to true requires a FIPS build of Node.js.</p>
<p>This property is deprecated. Please use <code>crypto.setFips()</code> and
<code>crypto.getFips()</code> instead.</p>
<h4><code>crypto.checkPrime(candidate[, options], callback)</code><span><a class="mark" href="#all_crypto_cryptocheckprimecandidate-options-callback" id="all_crypto_cryptocheckprimecandidate-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_checkprime_candidate_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>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>v15.8.0</td>
<td><p><span>Added in: v15.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>candidate</code> <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/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></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/Reference/Global_Objects/BigInt" class="type"><bigint></a>
A possible prime encoded as a sequence of big endian octets of arbitrary
length.</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>checks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of Miller-Rabin probabilistic primality
iterations to perform. When the value is <code>0</code> (zero), a number of checks
is used that yields a false positive rate of at most 2<sup>-64</sup> for
random input. Care must be used when selecting a number of checks. Refer
to the OpenSSL documentation for the <a href="https://www.openssl.org/docs/man1.1.1/man3/BN_is_prime_ex.html"><code>BN_is_prime_ex</code></a> function <code>nchecks</code>
options for more details. <strong>Default:</strong> <code>0</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>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> Set to an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> object if an error occurred during check.</li>
<li><code>result</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the candidate is a prime with an error
probability less than <code>0.25 ** options.checks</code>.</li>
</ul>
</li>
</ul>
<p>Checks the primality of the <code>candidate</code>.</p>
<h4><code>crypto.checkPrimeSync(candidate[, options])</code><span><a class="mark" href="#all_crypto_cryptocheckprimesynccandidate-options" id="all_crypto_cryptocheckprimesynccandidate-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_checkprimesync_candidate_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.8.0</span>
</div>
<ul>
<li><code>candidate</code> <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/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></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/Reference/Global_Objects/BigInt" class="type"><bigint></a>
A possible prime encoded as a sequence of big endian octets of arbitrary
length.</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>checks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of Miller-Rabin probabilistic primality
iterations to perform. When the value is <code>0</code> (zero), a number of checks
is used that yields a false positive rate of at most 2<sup>-64</sup> for
random input. Care must be used when selecting a number of checks. Refer
to the OpenSSL documentation for the <a href="https://www.openssl.org/docs/man1.1.1/man3/BN_is_prime_ex.html"><code>BN_is_prime_ex</code></a> function <code>nchecks</code>
options for more details. <strong>Default:</strong> <code>0</code></li>
</ul>
</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 the candidate is a prime with an error
probability less than <code>0.25 ** options.checks</code>.</li>
</ul>
<p>Checks the primality of the <code>candidate</code>.</p>
<h4><code>crypto.createCipher(algorithm, password[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatecipheralgorithm-password-options" id="all_crypto_cryptocreatecipheralgorithm-password-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createcipher_algorithm_password_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>v17.9.0, v16.17.0</td>
<td><p>The <code>authTagLength</code> option is now optional when using the <code>chacha20-poly1305</code> cipher and defaults to 16 bytes.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The password argument can be an ArrayBuffer and is limited to a maximum of 2 ** 31 - 1 bytes.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>Ciphers in OCB mode are now supported.</p></td></tr>
<tr><td>v10.2.0</td>
<td><p>The <code>authTagLength</code> option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Deprecated since: v10.0.0</span></p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_crypto_cryptocreatecipherivalgorithm-key-iv-options"><code>crypto.createCipheriv()</code></a> instead.</div><p></p>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>password</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#all_crypto_class-cipher" class="type"><Cipher></a></li>
</ul>
<p>Creates and returns a <code>Cipher</code> object that uses the given <code>algorithm</code> and
<code>password</code>.</p>
<p>The <code>options</code> argument controls stream behavior and is optional except when a
cipher in CCM or OCB mode (e.g. <code>'aes-128-ccm'</code>) is used. In that case, the
<code>authTagLength</code> option is required and specifies the length of the
authentication tag in bytes, see <a href="#all_crypto_ccm-mode">CCM mode</a>. In GCM mode, the <code>authTagLength</code>
option is not required but can be used to set the length of the authentication
tag that will be returned by <code>getAuthTag()</code> and defaults to 16 bytes.
For <code>chacha20-poly1305</code>, the <code>authTagLength</code> option defaults to 16 bytes.</p>
<p>The <code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On
recent OpenSSL releases, <code>openssl list -cipher-algorithms</code> will
display the available cipher algorithms.</p>
<p>The <code>password</code> is used to derive the cipher key and initialization vector (IV).
The value must be either a <code>'latin1'</code> encoded string, a <a href="buffer.html"><code>Buffer</code></a>, a
<code>TypedArray</code>, or a <code>DataView</code>.</p>
<p><strong class="critical">This function is semantically insecure for all
supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,
GCM, or CCM).</strong></p>
<p>The implementation of <code>crypto.createCipher()</code> derives keys using the OpenSSL
function <a href="https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> with the digest algorithm set to MD5, one
iteration, and no salt. The lack of salt allows dictionary attacks as the same
password always creates the same key. The low iteration count and
non-cryptographically secure hash algorithm allow passwords to be tested very
rapidly.</p>
<p>In line with OpenSSL's recommendation to use a more modern algorithm instead of
<a href="https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> it is recommended that developers derive a key and IV on
their own using <a href="#all_crypto_cryptoscryptpassword-salt-keylen-options-callback"><code>crypto.scrypt()</code></a> and to use <a href="#all_crypto_cryptocreatecipherivalgorithm-key-iv-options"><code>crypto.createCipheriv()</code></a>
to create the <code>Cipher</code> object. Users should not use ciphers with counter mode
(e.g. CTR, GCM, or CCM) in <code>crypto.createCipher()</code>. A warning is emitted when
they are used in order to avoid the risk of IV reuse that causes
vulnerabilities. For the case when IV is reused in GCM, see <a href="https://github.com/nonce-disrespect/nonce-disrespect">Nonce-Disrespecting
Adversaries</a> for details.</p>
<h4><code>crypto.createCipheriv(algorithm, key, iv[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatecipherivalgorithm-key-iv-options" id="all_crypto_cryptocreatecipherivalgorithm-key-iv-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createcipheriv_algorithm_key_iv_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>v17.9.0, v16.17.0</td>
<td><p>The <code>authTagLength</code> option is now optional when using the <code>chacha20-poly1305</code> cipher and defaults to 16 bytes.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The password and iv arguments can be an ArrayBuffer and are each limited to a maximum of 2 ** 31 - 1 bytes.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>The <code>key</code> argument can now be a <code>KeyObject</code>.</p></td></tr>
<tr><td>v11.2.0, v10.17.0</td>
<td><p>The cipher <code>chacha20-poly1305</code> (the IETF variant of ChaCha20-Poly1305) is now supported.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>Ciphers in OCB mode are now supported.</p></td></tr>
<tr><td>v10.2.0</td>
<td><p>The <code>authTagLength</code> option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>The <code>iv</code> parameter may now be <code>null</code> for ciphers which do not need an initialization vector.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>key</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li><code>iv</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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#Null_type" class="type"><null></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> <a href="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#all_crypto_class-cipher" class="type"><Cipher></a></li>
</ul>
<p>Creates and returns a <code>Cipher</code> object, with the given <code>algorithm</code>, <code>key</code> and
initialization vector (<code>iv</code>).</p>
<p>The <code>options</code> argument controls stream behavior and is optional except when a
cipher in CCM or OCB mode (e.g. <code>'aes-128-ccm'</code>) is used. In that case, the
<code>authTagLength</code> option is required and specifies the length of the
authentication tag in bytes, see <a href="#all_crypto_ccm-mode">CCM mode</a>. In GCM mode, the <code>authTagLength</code>
option is not required but can be used to set the length of the authentication
tag that will be returned by <code>getAuthTag()</code> and defaults to 16 bytes.
For <code>chacha20-poly1305</code>, the <code>authTagLength</code> option defaults to 16 bytes.</p>
<p>The <code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On
recent OpenSSL releases, <code>openssl list -cipher-algorithms</code> will
display the available cipher algorithms.</p>
<p>The <code>key</code> is the raw key used by the <code>algorithm</code> and <code>iv</code> is an
<a href="https://en.wikipedia.org/wiki/Initialization_vector">initialization vector</a>. Both arguments must be <code>'utf8'</code> encoded strings,
<a href="buffer.html">Buffers</a>, <code>TypedArray</code>, or <code>DataView</code>s. The <code>key</code> may optionally be
a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a> of type <code>secret</code>. If the cipher does not need
an initialization vector, <code>iv</code> may be <code>null</code>.</p>
<p>When passing strings for <code>key</code> or <code>iv</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</p>
<p>Initialization vectors should be unpredictable and unique; ideally, they will be
cryptographically random. They do not have to be secret: IVs are typically just
added to ciphertext messages unencrypted. It may sound contradictory that
something has to be unpredictable and unique, but does not have to be secret;
remember that an attacker must not be able to predict ahead of time what a
given IV will be.</p>
<h4><code>crypto.createDecipher(algorithm, password[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatedecipheralgorithm-password-options" id="all_crypto_cryptocreatedecipheralgorithm-password-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createdecipher_algorithm_password_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>v17.9.0, v16.17.0</td>
<td><p>The <code>authTagLength</code> option is now optional when using the <code>chacha20-poly1305</code> cipher and defaults to 16 bytes.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>Ciphers in OCB mode are now supported.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Deprecated since: v10.0.0</span></p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_crypto_cryptocreatedecipherivalgorithm-key-iv-options"><code>crypto.createDecipheriv()</code></a> instead.</div><p></p>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>password</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#all_crypto_class-decipher" class="type"><Decipher></a></li>
</ul>
<p>Creates and returns a <code>Decipher</code> object that uses the given <code>algorithm</code> and
<code>password</code> (key).</p>
<p>The <code>options</code> argument controls stream behavior and is optional except when a
cipher in CCM or OCB mode (e.g. <code>'aes-128-ccm'</code>) is used. In that case, the
<code>authTagLength</code> option is required and specifies the length of the
authentication tag in bytes, see <a href="#all_crypto_ccm-mode">CCM mode</a>.
For <code>chacha20-poly1305</code>, the <code>authTagLength</code> option defaults to 16 bytes.</p>
<p><strong class="critical">This function is semantically insecure for all
supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,
GCM, or CCM).</strong></p>
<p>The implementation of <code>crypto.createDecipher()</code> derives keys using the OpenSSL
function <a href="https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> with the digest algorithm set to MD5, one
iteration, and no salt. The lack of salt allows dictionary attacks as the same
password always creates the same key. The low iteration count and
non-cryptographically secure hash algorithm allow passwords to be tested very
rapidly.</p>
<p>In line with OpenSSL's recommendation to use a more modern algorithm instead of
<a href="https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> it is recommended that developers derive a key and IV on
their own using <a href="#all_crypto_cryptoscryptpassword-salt-keylen-options-callback"><code>crypto.scrypt()</code></a> and to use <a href="#all_crypto_cryptocreatedecipherivalgorithm-key-iv-options"><code>crypto.createDecipheriv()</code></a>
to create the <code>Decipher</code> object.</p>
<h4><code>crypto.createDecipheriv(algorithm, key, iv[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatedecipherivalgorithm-key-iv-options" id="all_crypto_cryptocreatedecipherivalgorithm-key-iv-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createdecipheriv_algorithm_key_iv_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>v17.9.0, v16.17.0</td>
<td><p>The <code>authTagLength</code> option is now optional when using the <code>chacha20-poly1305</code> cipher and defaults to 16 bytes.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>The <code>key</code> argument can now be a <code>KeyObject</code>.</p></td></tr>
<tr><td>v11.2.0, v10.17.0</td>
<td><p>The cipher <code>chacha20-poly1305</code> (the IETF variant of ChaCha20-Poly1305) is now supported.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>Ciphers in OCB mode are now supported.</p></td></tr>
<tr><td>v10.2.0</td>
<td><p>The <code>authTagLength</code> option can now be used to restrict accepted GCM authentication tag lengths.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>The <code>iv</code> parameter may now be <code>null</code> for ciphers which do not need an initialization vector.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>key</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li><code>iv</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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#Null_type" class="type"><null></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> <a href="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#all_crypto_class-decipher" class="type"><Decipher></a></li>
</ul>
<p>Creates and returns a <code>Decipher</code> object that uses the given <code>algorithm</code>, <code>key</code>
and initialization vector (<code>iv</code>).</p>
<p>The <code>options</code> argument controls stream behavior and is optional except when a
cipher in CCM or OCB mode (e.g. <code>'aes-128-ccm'</code>) is used. In that case, the
<code>authTagLength</code> option is required and specifies the length of the
authentication tag in bytes, see <a href="#all_crypto_ccm-mode">CCM mode</a>. In GCM mode, the <code>authTagLength</code>
option is not required but can be used to restrict accepted authentication tags
to those with the specified length.
For <code>chacha20-poly1305</code>, the <code>authTagLength</code> option defaults to 16 bytes.</p>
<p>The <code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On
recent OpenSSL releases, <code>openssl list -cipher-algorithms</code> will
display the available cipher algorithms.</p>
<p>The <code>key</code> is the raw key used by the <code>algorithm</code> and <code>iv</code> is an
<a href="https://en.wikipedia.org/wiki/Initialization_vector">initialization vector</a>. Both arguments must be <code>'utf8'</code> encoded strings,
<a href="buffer.html">Buffers</a>, <code>TypedArray</code>, or <code>DataView</code>s. The <code>key</code> may optionally be
a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a> of type <code>secret</code>. If the cipher does not need
an initialization vector, <code>iv</code> may be <code>null</code>.</p>
<p>When passing strings for <code>key</code> or <code>iv</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</p>
<p>Initialization vectors should be unpredictable and unique; ideally, they will be
cryptographically random. They do not have to be secret: IVs are typically just
added to ciphertext messages unencrypted. It may sound contradictory that
something has to be unpredictable and unique, but does not have to be secret;
remember that an attacker must not be able to predict ahead of time what a given
IV will be.</p>
<h4><code>crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])</code><span><a class="mark" href="#all_crypto_cryptocreatediffiehellmanprime-primeencoding-generator-generatorencoding" id="all_crypto_cryptocreatediffiehellmanprime-primeencoding-generator-generatorencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>prime</code> argument can be any <code>TypedArray</code> or <code>DataView</code> now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>prime</code> argument can be a <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The default for the encoding parameters changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>prime</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>primeEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>prime</code> string.</li>
<li><code>generator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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>
<strong>Default:</strong> <code>2</code></li>
<li><code>generatorEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>generator</code> string.</li>
<li>Returns: <a href="#all_crypto_class-diffiehellman" class="type"><DiffieHellman></a></li>
</ul>
<p>Creates a <code>DiffieHellman</code> key exchange object using the supplied <code>prime</code> and an
optional specific <code>generator</code>.</p>
<p>The <code>generator</code> argument can be a number, string, or <a href="buffer.html"><code>Buffer</code></a>. If
<code>generator</code> is not specified, the value <code>2</code> is used.</p>
<p>If <code>primeEncoding</code> is specified, <code>prime</code> is expected to be a string; otherwise
a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p>
<p>If <code>generatorEncoding</code> is specified, <code>generator</code> is expected to be a string;
otherwise a number, <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p>
<h4><code>crypto.createDiffieHellman(primeLength[, generator])</code><span><a class="mark" href="#all_crypto_cryptocreatediffiehellmanprimelength-generator" id="all_crypto_cryptocreatediffiehellmanprimelength-generator">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_creatediffiehellman_primelength_generator"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<ul>
<li><code>primeLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>generator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>2</code></li>
<li>Returns: <a href="#all_crypto_class-diffiehellman" class="type"><DiffieHellman></a></li>
</ul>
<p>Creates a <code>DiffieHellman</code> key exchange object and generates a prime of
<code>primeLength</code> bits using an optional specific numeric <code>generator</code>.
If <code>generator</code> is not specified, the value <code>2</code> is used.</p>
<h4><code>crypto.createDiffieHellmanGroup(name)</code><span><a class="mark" href="#all_crypto_cryptocreatediffiehellmangroupname" id="all_crypto_cryptocreatediffiehellmangroupname">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_creatediffiehellmangroup_name"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="#all_crypto_class-diffiehellmangroup" class="type"><DiffieHellmanGroup></a></li>
</ul>
<p>An alias for <a href="#all_crypto_cryptogetdiffiehellmangroupname"><code>crypto.getDiffieHellman()</code></a></p>
<h4><code>crypto.createECDH(curveName)</code><span><a class="mark" href="#all_crypto_cryptocreateecdhcurvename" id="all_crypto_cryptocreateecdhcurvename">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createecdh_curvename"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<ul>
<li><code>curveName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="#all_crypto_class-ecdh" class="type"><ECDH></a></li>
</ul>
<p>Creates an Elliptic Curve Diffie-Hellman (<code>ECDH</code>) key exchange object using a
predefined curve specified by the <code>curveName</code> string. Use
<a href="#all_crypto_cryptogetcurves"><code>crypto.getCurves()</code></a> to obtain a list of available curve names. On recent
OpenSSL releases, <code>openssl ecparam -list_curves</code> will also display the name
and description of each available elliptic curve.</p>
<h4><code>crypto.createHash(algorithm[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatehashalgorithm-options" id="all_crypto_cryptocreatehashalgorithm-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createhash_algorithm_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>v12.8.0</td>
<td><p>The <code>outputLength</code> option was added for XOF hash functions.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> <a href="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#all_crypto_class-hash" class="type"><Hash></a></li>
</ul>
<p>Creates and returns a <code>Hash</code> object that can be used to generate hash digests
using the given <code>algorithm</code>. Optional <code>options</code> argument controls stream
behavior. For XOF hash functions such as <code>'shake256'</code>, the <code>outputLength</code> option
can be used to specify the desired output length in bytes.</p>
<p>The <code>algorithm</code> is dependent on the available algorithms supported by the
version of OpenSSL on the platform. Examples are <code>'sha256'</code>, <code>'sha512'</code>, etc.
On recent releases of OpenSSL, <code>openssl list -digest-algorithms</code> will
display the available digest algorithms.</p>
<p>Example: generating the sha256 sum of a file</p>
<pre class="with-19-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> {
createReadStream,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { argv } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> {
createHash,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> filename = argv[<span class="hljs-number">2</span>];
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(filename);
input.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Only one element is going to be produced by the</span>
<span class="hljs-comment">// hash stream.</span>
<span class="hljs-keyword">const</span> data = input.<span class="hljs-title function_">read</span>();
<span class="hljs-keyword">if</span> (data)
hash.<span class="hljs-title function_">update</span>(data);
<span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${hash.digest(<span class="hljs-string">'hex'</span>)}</span> <span class="hljs-subst">${filename}</span>`</span>);
}
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createReadStream,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> {
createHash,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { argv } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> filename = argv[<span class="hljs-number">2</span>];
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(filename);
input.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Only one element is going to be produced by the</span>
<span class="hljs-comment">// hash stream.</span>
<span class="hljs-keyword">const</span> data = input.<span class="hljs-title function_">read</span>();
<span class="hljs-keyword">if</span> (data)
hash.<span class="hljs-title function_">update</span>(data);
<span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${hash.digest(<span class="hljs-string">'hex'</span>)}</span> <span class="hljs-subst">${filename}</span>`</span>);
}
});</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.createHmac(algorithm, key[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatehmacalgorithm-key-options" id="all_crypto_cryptocreatehmacalgorithm-key-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createhmac_algorithm_key_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>v15.0.0</td>
<td><p>The key can also be an ArrayBuffer or CryptoKey. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>The <code>key</code> argument can now be a <code>KeyObject</code>.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>key</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></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> <a href="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</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> The string encoding to use when <code>key</code> is a string.</li>
</ul>
</li>
<li>Returns: <a href="#all_crypto_class-hmac" class="type"><Hmac></a></li>
</ul>
<p>Creates and returns an <code>Hmac</code> object that uses the given <code>algorithm</code> and <code>key</code>.
Optional <code>options</code> argument controls stream behavior.</p>
<p>The <code>algorithm</code> is dependent on the available algorithms supported by the
version of OpenSSL on the platform. Examples are <code>'sha256'</code>, <code>'sha512'</code>, etc.
On recent releases of OpenSSL, <code>openssl list -digest-algorithms</code> will
display the available digest algorithms.</p>
<p>The <code>key</code> is the HMAC key used to generate the cryptographic HMAC hash. If it is
a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, its type must be <code>secret</code>. If it is a string, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>. If it was
obtained from a cryptographically secure source of entropy, such as
<a href="#all_crypto_cryptorandombytessize-callback"><code>crypto.randomBytes()</code></a> or <a href="#all_crypto_cryptogeneratekeytype-options-callback"><code>crypto.generateKey()</code></a>, its length should not
exceed the block size of <code>algorithm</code> (e.g., 512 bits for SHA-256).</p>
<p>Example: generating the sha256 HMAC of a file</p>
<pre class="with-19-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> {
createReadStream,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { argv } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> {
createHmac,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> filename = argv[<span class="hljs-number">2</span>];
<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);
<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(filename);
input.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Only one element is going to be produced by the</span>
<span class="hljs-comment">// hash stream.</span>
<span class="hljs-keyword">const</span> data = input.<span class="hljs-title function_">read</span>();
<span class="hljs-keyword">if</span> (data)
hmac.<span class="hljs-title function_">update</span>(data);
<span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${hmac.digest(<span class="hljs-string">'hex'</span>)}</span> <span class="hljs-subst">${filename}</span>`</span>);
}
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createReadStream,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> {
createHmac,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { argv } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> filename = argv[<span class="hljs-number">2</span>];
<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);
<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(filename);
input.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Only one element is going to be produced by the</span>
<span class="hljs-comment">// hash stream.</span>
<span class="hljs-keyword">const</span> data = input.<span class="hljs-title function_">read</span>();
<span class="hljs-keyword">if</span> (data)
hmac.<span class="hljs-title function_">update</span>(data);
<span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${hmac.digest(<span class="hljs-string">'hex'</span>)}</span> <span class="hljs-subst">${filename}</span>`</span>);
}
});</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.createPrivateKey(key)</code><span><a class="mark" href="#all_crypto_cryptocreateprivatekeykey" id="all_crypto_cryptocreateprivatekeykey">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createprivatekey_key"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.12.0</td>
<td><p>The key can also be a JWK object.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The key can also be an ArrayBuffer. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p><span>Added in: v11.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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>
<ul>
<li><code>key</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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/Reference/Global_Objects/Object" class="type"><Object></a> The key
material, either in PEM, DER, or JWK format.</li>
<li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'pem'</code>, <code>'der'</code>, or '<code>'jwk'</code>.
<strong>Default:</strong> <code>'pem'</code>.</li>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'pkcs1'</code>, <code>'pkcs8'</code> or <code>'sec1'</code>. This option is
required only if the <code>format</code> is <code>'der'</code> and ignored otherwise.</li>
<li><code>passphrase</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The passphrase to use for decryption.</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 string encoding to use when <code>key</code> is a string.</li>
</ul>
</li>
<li>Returns: <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Creates and returns a new key object containing a private key. If <code>key</code> is a
string or <code>Buffer</code>, <code>format</code> is assumed to be <code>'pem'</code>; otherwise, <code>key</code>
must be an object with the properties described above.</p>
<p>If the private key is encrypted, a <code>passphrase</code> must be specified. The length
of the passphrase is limited to 1024 bytes.</p>
<h4><code>crypto.createPublicKey(key)</code><span><a class="mark" href="#all_crypto_cryptocreatepublickeykey" id="all_crypto_cryptocreatepublickeykey">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createpublickey_key"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.12.0</td>
<td><p>The key can also be a JWK object.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The key can also be an ArrayBuffer. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes.</p></td></tr>
<tr><td>v11.13.0</td>
<td><p>The <code>key</code> argument can now be a <code>KeyObject</code> with type <code>private</code>.</p></td></tr>
<tr><td>v11.7.0</td>
<td><p>The <code>key</code> argument can now be a private key.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p><span>Added in: v11.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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>
<ul>
<li><code>key</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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/Reference/Global_Objects/Object" class="type"><Object></a> The key
material, either in PEM, DER, or JWK format.</li>
<li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'pem'</code>, <code>'der'</code>, or <code>'jwk'</code>.
<strong>Default:</strong> <code>'pem'</code>.</li>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'pkcs1'</code> or <code>'spki'</code>. This option is
required only if the <code>format</code> is <code>'der'</code> and ignored otherwise.</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 string encoding to use when <code>key</code> is a string.</li>
</ul>
</li>
<li>Returns: <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Creates and returns a new key object containing a public key. If <code>key</code> is a
string or <code>Buffer</code>, <code>format</code> is assumed to be <code>'pem'</code>; if <code>key</code> is a <code>KeyObject</code>
with type <code>'private'</code>, the public key is derived from the given private key;
otherwise, <code>key</code> must be an object with the properties described above.</p>
<p>If the format is <code>'pem'</code>, the <code>'key'</code> may also be an X.509 certificate.</p>
<p>Because public keys can be derived from private keys, a private key may be
passed instead of a public key. In that case, this function behaves as if
<a href="#all_crypto_cryptocreateprivatekeykey"><code>crypto.createPrivateKey()</code></a> had been called, except that the type of the
returned <code>KeyObject</code> will be <code>'public'</code> and that the private key cannot be
extracted from the returned <code>KeyObject</code>. Similarly, if a <code>KeyObject</code> with type
<code>'private'</code> is given, a new <code>KeyObject</code> with type <code>'public'</code> will be returned
and it will be impossible to extract the private key from the returned object.</p>
<h4><code>crypto.createSecretKey(key[, encoding])</code><span><a class="mark" href="#all_crypto_cryptocreatesecretkeykey-encoding" id="all_crypto_cryptocreatesecretkeykey-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createsecretkey_key_encoding"></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.8.0, v16.18.0</td>
<td><p>The key can now be zero-length.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The key can also be an ArrayBuffer or string. The encoding argument was added. The key cannot contain more than 2 ** 32 - 1 bytes.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p><span>Added in: v11.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>key</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></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 string encoding when <code>key</code> is a string.</li>
<li>Returns: <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
</ul>
<p>Creates and returns a new key object containing a secret key for symmetric
encryption or <code>Hmac</code>.</p>
<h4><code>crypto.createSign(algorithm[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatesignalgorithm-options" id="all_crypto_cryptocreatesignalgorithm-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createsign_algorithm_options"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> <a href="#all_stream_new-streamwritableoptions"><code>stream.Writable</code> options</a></li>
<li>Returns: <a href="#all_crypto_class-sign" class="type"><Sign></a></li>
</ul>
<p>Creates and returns a <code>Sign</code> object that uses the given <code>algorithm</code>. Use
<a href="#all_crypto_cryptogethashes"><code>crypto.getHashes()</code></a> to obtain the names of the available digest algorithms.
Optional <code>options</code> argument controls the <code>stream.Writable</code> behavior.</p>
<p>In some cases, a <code>Sign</code> instance can be created using the name of a signature
algorithm, such as <code>'RSA-SHA256'</code>, instead of a digest algorithm. This will use
the corresponding digest algorithm. This does not work for all signature
algorithms, such as <code>'ecdsa-with-SHA256'</code>, so it is best to always use digest
algorithm names.</p>
<h4><code>crypto.createVerify(algorithm[, options])</code><span><a class="mark" href="#all_crypto_cryptocreateverifyalgorithm-options" id="all_crypto_cryptocreateverifyalgorithm-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createverify_algorithm_options"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> <a href="#all_stream_new-streamwritableoptions"><code>stream.Writable</code> options</a></li>
<li>Returns: <a href="#all_crypto_class-verify" class="type"><Verify></a></li>
</ul>
<p>Creates and returns a <code>Verify</code> object that uses the given algorithm.
Use <a href="#all_crypto_cryptogethashes"><code>crypto.getHashes()</code></a> to obtain an array of names of the available
signing algorithms. Optional <code>options</code> argument controls the
<code>stream.Writable</code> behavior.</p>
<p>In some cases, a <code>Verify</code> instance can be created using the name of a signature
algorithm, such as <code>'RSA-SHA256'</code>, instead of a digest algorithm. This will use
the corresponding digest algorithm. This does not work for all signature
algorithms, such as <code>'ecdsa-with-SHA256'</code>, so it is best to always use digest
algorithm names.</p>
<h4><code>crypto.diffieHellman(options)</code><span><a class="mark" href="#all_crypto_cryptodiffiehellmanoptions" id="all_crypto_cryptodiffiehellmanoptions">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_diffiehellman_options"></a></h4>
<div class="api_metadata">
<span>Added in: v13.9.0, v12.17.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>
<ul>
<li><code>privateKey</code>: <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
<li><code>publicKey</code>: <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
</ul>
</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Computes the Diffie-Hellman secret based on a <code>privateKey</code> and a <code>publicKey</code>.
Both keys must have the same <code>asymmetricKeyType</code>, which must be one of <code>'dh'</code>
(for Diffie-Hellman), <code>'ec'</code>, <code>'x448'</code>, or <code>'x25519'</code> (for ECDH).</p>
<h4><code>crypto.hash(algorithm, data[, outputEncoding])</code><span><a class="mark" href="#all_crypto_cryptohashalgorithm-data-outputencoding" id="all_crypto_cryptohashalgorithm-data-outputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_hash_algorithm_data_outputencoding"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><code>algorithm</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#Undefined_type" class="type"><undefined></a></li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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> When <code>data</code> is a
string, it will be encoded as UTF-8 before being hashed. If a different
input encoding is desired for a string input, user could encode the string
into a <code>TypedArray</code> using either <code>TextEncoder</code> or <code>Buffer.from()</code> and passing
the encoded <code>TypedArray</code> into this API instead.</li>
<li><code>outputEncoding</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#Undefined_type" class="type"><undefined></a> <a href="#all_buffer_buffers-and-character-encodings">Encoding</a> used to encode the
returned digest. <strong>Default:</strong> <code>'hex'</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>A utility for creating one-shot hash digests of data. It can be faster than
the object-based <code>crypto.createHash()</code> when hashing a smaller amount of data
(<= 5MB) that's readily available. If the data can be big or if it is streamed,
it's still recommended to use <code>crypto.createHash()</code> instead.</p>
<p>The <code>algorithm</code> is dependent on the available algorithms supported by the
version of OpenSSL on the platform. Examples are <code>'sha256'</code>, <code>'sha512'</code>, etc.
On recent releases of OpenSSL, <code>openssl list -digest-algorithms</code> will
display the available digest algorithms.</p>
<p>Example:</p>
<pre class="with-42-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> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-comment">// Hashing a string and return the result as a hex-encoded string.</span>
<span class="hljs-keyword">const</span> string = <span class="hljs-string">'Node.js'</span>;
<span class="hljs-comment">// 10b3493287f831e81a438811a1ffba01f8cec4b7</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(crypto.<span class="hljs-title function_">hash</span>(<span class="hljs-string">'sha1'</span>, string));
<span class="hljs-comment">// Encode a base64-encoded string into a Buffer, hash it and return</span>
<span class="hljs-comment">// the result as a buffer.</span>
<span class="hljs-keyword">const</span> base64 = <span class="hljs-string">'Tm9kZS5qcw=='</span>;
<span class="hljs-comment">// <Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(crypto.<span class="hljs-title function_">hash</span>(<span class="hljs-string">'sha1'</span>, <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(base64, <span class="hljs-string">'base64'</span>), <span class="hljs-string">'buffer'</span>));</code><code class="language-js mjs"><span class="hljs-keyword">import</span> crypto <span class="hljs-keyword">from</span> <span class="hljs-string">'node:crypto'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-comment">// Hashing a string and return the result as a hex-encoded string.</span>
<span class="hljs-keyword">const</span> string = <span class="hljs-string">'Node.js'</span>;
<span class="hljs-comment">// 10b3493287f831e81a438811a1ffba01f8cec4b7</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(crypto.<span class="hljs-title function_">hash</span>(<span class="hljs-string">'sha1'</span>, string));
<span class="hljs-comment">// Encode a base64-encoded string into a Buffer, hash it and return</span>
<span class="hljs-comment">// the result as a buffer.</span>
<span class="hljs-keyword">const</span> base64 = <span class="hljs-string">'Tm9kZS5qcw=='</span>;
<span class="hljs-comment">// <Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(crypto.<span class="hljs-title function_">hash</span>(<span class="hljs-string">'sha1'</span>, <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(base64, <span class="hljs-string">'base64'</span>), <span class="hljs-string">'buffer'</span>));</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.generateKey(type, options, callback)</code><span><a class="mark" href="#all_crypto_cryptogeneratekeytype-options-callback" id="all_crypto_cryptogeneratekeytype-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_generatekey_type_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>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>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The intended use of the generated secret key. Currently
accepted values are <code>'hmac'</code> and <code>'aes'</code>.</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>length</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The bit length of the key to generate. This must be a
value greater than 0.
<ul>
<li>If <code>type</code> is <code>'hmac'</code>, the minimum is 8, and the maximum length is
2<sup>31</sup>-1. If the value is not a multiple of 8, the generated
key will be truncated to <code>Math.floor(length / 8)</code>.</li>
<li>If <code>type</code> is <code>'aes'</code>, the length must be one of <code>128</code>, <code>192</code>, or <code>256</code>.</li>
</ul>
</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>
<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>key</code>: <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
</ul>
</li>
</ul>
<p>Asynchronously generates a new random secret key of the given <code>length</code>. The
<code>type</code> will determine which validations will be performed on the <code>length</code>.</p>
<pre class="with-14-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">const</span> {
generateKey,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-title function_">generateKey</span>(<span class="hljs-string">'hmac'</span>, { <span class="hljs-attr">length</span>: <span class="hljs-number">512</span> }, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key.<span class="hljs-title function_">export</span>().<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// 46e..........620</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
generateKey,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-title function_">generateKey</span>(<span class="hljs-string">'hmac'</span>, { <span class="hljs-attr">length</span>: <span class="hljs-number">512</span> }, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key.<span class="hljs-title function_">export</span>().<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// 46e..........620</span>
});</code><button class="copy-button">copy</button></pre>
<p>The size of a generated HMAC key should not exceed the block size of the
underlying hash function. See <a href="#all_crypto_cryptocreatehmacalgorithm-key-options"><code>crypto.createHmac()</code></a> for more information.</p>
<h4><code>crypto.generateKeyPair(type, options, callback)</code><span><a class="mark" href="#all_crypto_cryptogeneratekeypairtype-options-callback" id="all_crypto_cryptogeneratekeypairtype-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_generatekeypair_type_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>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>v16.10.0</td>
<td><p>Add ability to define <code>RSASSA-PSS-params</code> sequence parameters for RSA-PSS keys pairs.</p></td></tr>
<tr><td>v13.9.0, v12.17.0</td>
<td><p>Add support for Diffie-Hellman.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add support for RSA-PSS key pairs.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add ability to generate X25519 and X448 key pairs.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add ability to generate Ed25519 and Ed448 key pairs.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>The <code>generateKeyPair</code> and <code>generateKeyPairSync</code> functions now produce key objects if no encoding was specified.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p><span>Added in: v10.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'rsa'</code>, <code>'rsa-pss'</code>, <code>'dsa'</code>, <code>'ec'</code>, <code>'ed25519'</code>,
<code>'ed448'</code>, <code>'x25519'</code>, <code>'x448'</code>, or <code>'dh'</code>.</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>modulusLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Key size in bits (RSA, DSA).</li>
<li><code>publicExponent</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Public exponent (RSA). <strong>Default:</strong> <code>0x10001</code>.</li>
<li><code>hashAlgorithm</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the message digest (RSA-PSS).</li>
<li><code>mgf1HashAlgorithm</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the message digest used by
MGF1 (RSA-PSS).</li>
<li><code>saltLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Minimal salt length in bytes (RSA-PSS).</li>
<li><code>divisorLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Size of <code>q</code> in bits (DSA).</li>
<li><code>namedCurve</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the curve to use (EC).</li>
<li><code>prime</code>: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The prime parameter (DH).</li>
<li><code>primeLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Prime length in bits (DH).</li>
<li><code>generator</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Custom generator (DH). <strong>Default:</strong> <code>2</code>.</li>
<li><code>groupName</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Diffie-Hellman group name (DH). See
<a href="#all_crypto_cryptogetdiffiehellmangroupname"><code>crypto.getDiffieHellman()</code></a>.</li>
<li><code>paramEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'named'</code> or <code>'explicit'</code> (EC).
<strong>Default:</strong> <code>'named'</code>.</li>
<li><code>publicKeyEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See <a href="#all_crypto_keyobjectexportoptions"><code>keyObject.export()</code></a>.</li>
<li><code>privateKeyEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See <a href="#all_crypto_keyobjectexportoptions"><code>keyObject.export()</code></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>
<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>publicKey</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
<li><code>privateKey</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
</ul>
</li>
</ul>
<p>Generates a new asymmetric key pair of the given <code>type</code>. RSA, RSA-PSS, DSA, EC,
Ed25519, Ed448, X25519, X448, and DH are currently supported.</p>
<p>If a <code>publicKeyEncoding</code> or <code>privateKeyEncoding</code> was specified, this function
behaves as if <a href="#all_crypto_keyobjectexportoptions"><code>keyObject.export()</code></a> had been called on its result. Otherwise,
the respective part of the key is returned as a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>.</p>
<p>It is recommended to encode public keys as <code>'spki'</code> and private keys as
<code>'pkcs8'</code> with encryption for long-term storage:</p>
<pre class="with-18-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">const</span> {
generateKeyPair,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-title function_">generateKeyPair</span>(<span class="hljs-string">'rsa'</span>, {
<span class="hljs-attr">modulusLength</span>: <span class="hljs-number">4096</span>,
<span class="hljs-attr">publicKeyEncoding</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">'spki'</span>,
<span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
},
<span class="hljs-attr">privateKeyEncoding</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">'pkcs8'</span>,
<span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
<span class="hljs-attr">cipher</span>: <span class="hljs-string">'aes-256-cbc'</span>,
<span class="hljs-attr">passphrase</span>: <span class="hljs-string">'top secret'</span>,
},
}, <span class="hljs-function">(<span class="hljs-params">err, publicKey, privateKey</span>) =></span> {
<span class="hljs-comment">// Handle errors and use the generated key pair.</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
generateKeyPair,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-title function_">generateKeyPair</span>(<span class="hljs-string">'rsa'</span>, {
<span class="hljs-attr">modulusLength</span>: <span class="hljs-number">4096</span>,
<span class="hljs-attr">publicKeyEncoding</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">'spki'</span>,
<span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
},
<span class="hljs-attr">privateKeyEncoding</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">'pkcs8'</span>,
<span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
<span class="hljs-attr">cipher</span>: <span class="hljs-string">'aes-256-cbc'</span>,
<span class="hljs-attr">passphrase</span>: <span class="hljs-string">'top secret'</span>,
},
}, <span class="hljs-function">(<span class="hljs-params">err, publicKey, privateKey</span>) =></span> {
<span class="hljs-comment">// Handle errors and use the generated key pair.</span>
});</code><button class="copy-button">copy</button></pre>
<p>On completion, <code>callback</code> will be called with <code>err</code> set to <code>undefined</code> and
<code>publicKey</code> / <code>privateKey</code> representing the generated key pair.</p>
<p>If this method is invoked as its <a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed version, it returns
a <code>Promise</code> for an <code>Object</code> with <code>publicKey</code> and <code>privateKey</code> properties.</p>
<h4><code>crypto.generateKeyPairSync(type, options)</code><span><a class="mark" href="#all_crypto_cryptogeneratekeypairsynctype-options" id="all_crypto_cryptogeneratekeypairsynctype-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_generatekeypairsync_type_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>v16.10.0</td>
<td><p>Add ability to define <code>RSASSA-PSS-params</code> sequence parameters for RSA-PSS keys pairs.</p></td></tr>
<tr><td>v13.9.0, v12.17.0</td>
<td><p>Add support for Diffie-Hellman.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add support for RSA-PSS key pairs.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add ability to generate X25519 and X448 key pairs.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add ability to generate Ed25519 and Ed448 key pairs.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>The <code>generateKeyPair</code> and <code>generateKeyPairSync</code> functions now produce key objects if no encoding was specified.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p><span>Added in: v10.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'rsa'</code>, <code>'rsa-pss'</code>, <code>'dsa'</code>, <code>'ec'</code>, <code>'ed25519'</code>,
<code>'ed448'</code>, <code>'x25519'</code>, <code>'x448'</code>, or <code>'dh'</code>.</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>modulusLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Key size in bits (RSA, DSA).</li>
<li><code>publicExponent</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Public exponent (RSA). <strong>Default:</strong> <code>0x10001</code>.</li>
<li><code>hashAlgorithm</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the message digest (RSA-PSS).</li>
<li><code>mgf1HashAlgorithm</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the message digest used by
MGF1 (RSA-PSS).</li>
<li><code>saltLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Minimal salt length in bytes (RSA-PSS).</li>
<li><code>divisorLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Size of <code>q</code> in bits (DSA).</li>
<li><code>namedCurve</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the curve to use (EC).</li>
<li><code>prime</code>: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The prime parameter (DH).</li>
<li><code>primeLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Prime length in bits (DH).</li>
<li><code>generator</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Custom generator (DH). <strong>Default:</strong> <code>2</code>.</li>
<li><code>groupName</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Diffie-Hellman group name (DH). See
<a href="#all_crypto_cryptogetdiffiehellmangroupname"><code>crypto.getDiffieHellman()</code></a>.</li>
<li><code>paramEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'named'</code> or <code>'explicit'</code> (EC).
<strong>Default:</strong> <code>'named'</code>.</li>
<li><code>publicKeyEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See <a href="#all_crypto_keyobjectexportoptions"><code>keyObject.export()</code></a>.</li>
<li><code>privateKeyEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See <a href="#all_crypto_keyobjectexportoptions"><code>keyObject.export()</code></a>.</li>
</ul>
</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>publicKey</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
<li><code>privateKey</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
</ul>
</li>
</ul>
<p>Generates a new asymmetric key pair of the given <code>type</code>. RSA, RSA-PSS, DSA, EC,
Ed25519, Ed448, X25519, X448, and DH are currently supported.</p>
<p>If a <code>publicKeyEncoding</code> or <code>privateKeyEncoding</code> was specified, this function
behaves as if <a href="#all_crypto_keyobjectexportoptions"><code>keyObject.export()</code></a> had been called on its result. Otherwise,
the respective part of the key is returned as a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>.</p>
<p>When encoding public keys, it is recommended to use <code>'spki'</code>. When encoding
private keys, it is recommended to use <code>'pkcs8'</code> with a strong passphrase,
and to keep the passphrase confidential.</p>
<pre class="with-22-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">const</span> {
generateKeyPairSync,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> {
publicKey,
privateKey,
} = <span class="hljs-title function_">generateKeyPairSync</span>(<span class="hljs-string">'rsa'</span>, {
<span class="hljs-attr">modulusLength</span>: <span class="hljs-number">4096</span>,
<span class="hljs-attr">publicKeyEncoding</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">'spki'</span>,
<span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
},
<span class="hljs-attr">privateKeyEncoding</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">'pkcs8'</span>,
<span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
<span class="hljs-attr">cipher</span>: <span class="hljs-string">'aes-256-cbc'</span>,
<span class="hljs-attr">passphrase</span>: <span class="hljs-string">'top secret'</span>,
},
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
generateKeyPairSync,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> {
publicKey,
privateKey,
} = <span class="hljs-title function_">generateKeyPairSync</span>(<span class="hljs-string">'rsa'</span>, {
<span class="hljs-attr">modulusLength</span>: <span class="hljs-number">4096</span>,
<span class="hljs-attr">publicKeyEncoding</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">'spki'</span>,
<span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
},
<span class="hljs-attr">privateKeyEncoding</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">'pkcs8'</span>,
<span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
<span class="hljs-attr">cipher</span>: <span class="hljs-string">'aes-256-cbc'</span>,
<span class="hljs-attr">passphrase</span>: <span class="hljs-string">'top secret'</span>,
},
});</code><button class="copy-button">copy</button></pre>
<p>The return value <code>{ publicKey, privateKey }</code> represents the generated key pair.
When PEM encoding was selected, the respective key will be a string, otherwise
it will be a buffer containing the data encoded as DER.</p>
<h4><code>crypto.generateKeySync(type, options)</code><span><a class="mark" href="#all_crypto_cryptogeneratekeysynctype-options" id="all_crypto_cryptogeneratekeysynctype-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_generatekeysync_type_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The intended use of the generated secret key. Currently
accepted values are <code>'hmac'</code> and <code>'aes'</code>.</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>length</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The bit length of the key to generate.
<ul>
<li>If <code>type</code> is <code>'hmac'</code>, the minimum is 8, and the maximum length is
2<sup>31</sup>-1. If the value is not a multiple of 8, the generated
key will be truncated to <code>Math.floor(length / 8)</code>.</li>
<li>If <code>type</code> is <code>'aes'</code>, the length must be one of <code>128</code>, <code>192</code>, or <code>256</code>.</li>
</ul>
</li>
</ul>
</li>
<li>Returns: <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a></li>
</ul>
<p>Synchronously generates a new random secret key of the given <code>length</code>. The
<code>type</code> will determine which validations will be performed on the <code>length</code>.</p>
<pre class="with-18-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">const</span> {
generateKeySync,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">generateKeySync</span>(<span class="hljs-string">'hmac'</span>, { <span class="hljs-attr">length</span>: <span class="hljs-number">512</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key.<span class="hljs-title function_">export</span>().<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// e89..........41e</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
generateKeySync,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">generateKeySync</span>(<span class="hljs-string">'hmac'</span>, { <span class="hljs-attr">length</span>: <span class="hljs-number">512</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key.<span class="hljs-title function_">export</span>().<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// e89..........41e</span></code><button class="copy-button">copy</button></pre>
<p>The size of a generated HMAC key should not exceed the block size of the
underlying hash function. See <a href="#all_crypto_cryptocreatehmacalgorithm-key-options"><code>crypto.createHmac()</code></a> for more information.</p>
<h4><code>crypto.generatePrime(size[, options[, callback]])</code><span><a class="mark" href="#all_crypto_cryptogenerateprimesize-options-callback" id="all_crypto_cryptogenerateprimesize-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_generateprime_size_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>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>v15.8.0</td>
<td><p><span>Added in: v15.8.0</span></p></td></tr>
</tbody></table>
</details>
</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> The size (in bits) of the prime to generate.</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>add</code> <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/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></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/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
<li><code>rem</code> <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/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></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/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
<li><code>safe</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code>.</li>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the generated prime is returned
as a <code>bigint</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>
<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>prime</code> <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/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
</li>
</ul>
<p>Generates a pseudorandom prime of <code>size</code> bits.</p>
<p>If <code>options.safe</code> is <code>true</code>, the prime will be a safe prime -- that is,
<code>(prime - 1) / 2</code> will also be a prime.</p>
<p>The <code>options.add</code> and <code>options.rem</code> parameters can be used to enforce additional
requirements, e.g., for Diffie-Hellman:</p>
<ul>
<li>If <code>options.add</code> and <code>options.rem</code> are both set, the prime will satisfy the
condition that <code>prime % add = rem</code>.</li>
<li>If only <code>options.add</code> is set and <code>options.safe</code> is not <code>true</code>, the prime will
satisfy the condition that <code>prime % add = 1</code>.</li>
<li>If only <code>options.add</code> is set and <code>options.safe</code> is set to <code>true</code>, the prime
will instead satisfy the condition that <code>prime % add = 3</code>. This is necessary
because <code>prime % add = 1</code> for <code>options.add > 2</code> would contradict the condition
enforced by <code>options.safe</code>.</li>
<li><code>options.rem</code> is ignored if <code>options.add</code> is not given.</li>
</ul>
<p>Both <code>options.add</code> and <code>options.rem</code> must be encoded as big-endian sequences
if given as an <code>ArrayBuffer</code>, <code>SharedArrayBuffer</code>, <code>TypedArray</code>, <code>Buffer</code>, or
<code>DataView</code>.</p>
<p>By default, the prime is encoded as a big-endian sequence of octets
in an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a>. If the <code>bigint</code> option is <code>true</code>, then a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a>
is provided.</p>
<h4><code>crypto.generatePrimeSync(size[, options])</code><span><a class="mark" href="#all_crypto_cryptogenerateprimesyncsize-options" id="all_crypto_cryptogenerateprimesyncsize-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_generateprimesync_size_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.8.0</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> The size (in bits) of the prime to generate.</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>add</code> <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/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></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/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
<li><code>rem</code> <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/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></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/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
<li><code>safe</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code>.</li>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the generated prime is returned
as a <code>bigint</code>.</li>
</ul>
</li>
<li>Returns: <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/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Generates a pseudorandom prime of <code>size</code> bits.</p>
<p>If <code>options.safe</code> is <code>true</code>, the prime will be a safe prime -- that is,
<code>(prime - 1) / 2</code> will also be a prime.</p>
<p>The <code>options.add</code> and <code>options.rem</code> parameters can be used to enforce additional
requirements, e.g., for Diffie-Hellman:</p>
<ul>
<li>If <code>options.add</code> and <code>options.rem</code> are both set, the prime will satisfy the
condition that <code>prime % add = rem</code>.</li>
<li>If only <code>options.add</code> is set and <code>options.safe</code> is not <code>true</code>, the prime will
satisfy the condition that <code>prime % add = 1</code>.</li>
<li>If only <code>options.add</code> is set and <code>options.safe</code> is set to <code>true</code>, the prime
will instead satisfy the condition that <code>prime % add = 3</code>. This is necessary
because <code>prime % add = 1</code> for <code>options.add > 2</code> would contradict the condition
enforced by <code>options.safe</code>.</li>
<li><code>options.rem</code> is ignored if <code>options.add</code> is not given.</li>
</ul>
<p>Both <code>options.add</code> and <code>options.rem</code> must be encoded as big-endian sequences
if given as an <code>ArrayBuffer</code>, <code>SharedArrayBuffer</code>, <code>TypedArray</code>, <code>Buffer</code>, or
<code>DataView</code>.</p>
<p>By default, the prime is encoded as a big-endian sequence of octets
in an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a>. If the <code>bigint</code> option is <code>true</code>, then a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a>
is provided.</p>
<h4><code>crypto.getCipherInfo(nameOrNid[, options])</code><span><a class="mark" href="#all_crypto_cryptogetcipherinfonameornid-options" id="all_crypto_cryptogetcipherinfonameornid-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_getcipherinfo_nameornid_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>nameOrNid</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#Number_type" class="type"><number></a> The name or nid of the cipher to query.</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>keyLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A test key length.</li>
<li><code>ivLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A test IV length.</li>
</ul>
</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>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the cipher</li>
<li><code>nid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nid of the cipher</li>
<li><code>blockSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The block size of the cipher in bytes. This property
is omitted when <code>mode</code> is <code>'stream'</code>.</li>
<li><code>ivLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The expected or default initialization vector length in
bytes. This property is omitted if the cipher does not use an initialization
vector.</li>
<li><code>keyLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The expected or default key length in bytes.</li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The cipher mode. One of <code>'cbc'</code>, <code>'ccm'</code>, <code>'cfb'</code>, <code>'ctr'</code>,
<code>'ecb'</code>, <code>'gcm'</code>, <code>'ocb'</code>, <code>'ofb'</code>, <code>'stream'</code>, <code>'wrap'</code>, <code>'xts'</code>.</li>
</ul>
</li>
</ul>
<p>Returns information about a given cipher.</p>
<p>Some ciphers accept variable length keys and initialization vectors. By default,
the <code>crypto.getCipherInfo()</code> method will return the default values for these
ciphers. To test if a given key length or iv length is acceptable for given
cipher, use the <code>keyLength</code> and <code>ivLength</code> options. If the given values are
unacceptable, <code>undefined</code> will be returned.</p>
<h4><code>crypto.getCiphers()</code><span><a class="mark" href="#all_crypto_cryptogetciphers" id="all_crypto_cryptogetciphers">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_getciphers"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array with the names of the supported cipher
algorithms.</li>
</ul>
<pre class="with-13-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">const</span> {
getCiphers,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getCiphers</span>()); <span class="hljs-comment">// ['aes-128-cbc', 'aes-128-ccm', ...]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
getCiphers,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getCiphers</span>()); <span class="hljs-comment">// ['aes-128-cbc', 'aes-128-ccm', ...]</span></code><button class="copy-button">copy</button></pre>
<h4><code>crypto.getCurves()</code><span><a class="mark" href="#all_crypto_cryptogetcurves" id="all_crypto_cryptogetcurves">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_getcurves"></a></h4>
<div class="api_metadata">
<span>Added in: v2.3.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array with the names of the supported elliptic curves.</li>
</ul>
<pre class="with-12-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">const</span> {
getCurves,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getCurves</span>()); <span class="hljs-comment">// ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
getCurves,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getCurves</span>()); <span class="hljs-comment">// ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]</span></code><button class="copy-button">copy</button></pre>
<h4><code>crypto.getDiffieHellman(groupName)</code><span><a class="mark" href="#all_crypto_cryptogetdiffiehellmangroupname" id="all_crypto_cryptogetdiffiehellmangroupname">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_getdiffiehellman_groupname"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div>
<ul>
<li><code>groupName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="#all_crypto_class-diffiehellmangroup" class="type"><DiffieHellmanGroup></a></li>
</ul>
<p>Creates a predefined <code>DiffieHellmanGroup</code> key exchange object. The
supported groups are listed in the documentation for <a href="#all_crypto_class-diffiehellmangroup"><code>DiffieHellmanGroup</code></a>.</p>
<p>The returned object mimics the interface of objects created by
<a href="#all_crypto_cryptocreatediffiehellmanprime-primeencoding-generator-generatorencoding"><code>crypto.createDiffieHellman()</code></a>, but will not allow changing
the keys (with <a href="#all_crypto_diffiehellmansetpublickeypublickey-encoding"><code>diffieHellman.setPublicKey()</code></a>, for example). The
advantage of using this method is that the parties do not have to
generate nor exchange a group modulus beforehand, saving both processor
and communication time.</p>
<p>Example (obtaining a shared secret):</p>
<pre class="with-19-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">const</span> {
getDiffieHellman,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">getDiffieHellman</span>(<span class="hljs-string">'modp14'</span>);
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">getDiffieHellman</span>(<span class="hljs-string">'modp14'</span>);
alice.<span class="hljs-title function_">generateKeys</span>();
bob.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bob.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(alice.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">/* aliceSecret and bobSecret should be the same */</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(aliceSecret === bobSecret);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
getDiffieHellman,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">getDiffieHellman</span>(<span class="hljs-string">'modp14'</span>);
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">getDiffieHellman</span>(<span class="hljs-string">'modp14'</span>);
alice.<span class="hljs-title function_">generateKeys</span>();
bob.<span class="hljs-title function_">generateKeys</span>();
<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bob.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(alice.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">/* aliceSecret and bobSecret should be the same */</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(aliceSecret === bobSecret);</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.getFips()</code><span><a class="mark" href="#all_crypto_cryptogetfips" id="all_crypto_cryptogetfips">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_getfips"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <code>1</code> if and only if a FIPS compliant crypto provider is
currently in use, <code>0</code> otherwise. A future semver-major release may change
the return type of this API to a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a>.</li>
</ul>
<h4><code>crypto.getHashes()</code><span><a class="mark" href="#all_crypto_cryptogethashes" id="all_crypto_cryptogethashes">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_gethashes"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array of the names of the supported hash algorithms,
such as <code>'RSA-SHA256'</code>. Hash algorithms are also called "digest" algorithms.</li>
</ul>
<pre class="with-12-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">const</span> {
getHashes,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getHashes</span>()); <span class="hljs-comment">// ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
getHashes,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getHashes</span>()); <span class="hljs-comment">// ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]</span></code><button class="copy-button">copy</button></pre>
<h4><code>crypto.getRandomValues(typedArray)</code><span><a class="mark" href="#all_crypto_cryptogetrandomvaluestypedarray" id="all_crypto_cryptogetrandomvaluestypedarray">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_getrandomvalues_typedarray"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0</span>
</div>
<ul>
<li><code>typedArray</code> <a href="#all_buffer_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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a></li>
<li>Returns: <a href="#all_buffer_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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> Returns <code>typedArray</code>.</li>
</ul>
<p>A convenient alias for <a href="#all_webcrypto_cryptogetrandomvaluestypedarray"><code>crypto.webcrypto.getRandomValues()</code></a>. This
implementation is not compliant with the Web Crypto spec, to write
web-compatible code use <a href="#all_webcrypto_cryptogetrandomvaluestypedarray"><code>crypto.webcrypto.getRandomValues()</code></a> instead.</p>
<h4><code>crypto.hkdf(digest, ikm, salt, info, keylen, callback)</code><span><a class="mark" href="#all_crypto_cryptohkdfdigest-ikm-salt-info-keylen-callback" id="all_crypto_cryptohkdfdigest-ikm-salt-info-keylen-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_hkdf_digest_ikm_salt_info_keylen_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>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>v18.8.0, v16.18.0</td>
<td><p>The input keying material can now be zero-length.</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>digest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The digest algorithm to use.</li>
<li><code>ikm</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> The input
keying material. Must be provided but can be zero-length.</li>
<li><code>salt</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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> The salt value. Must
be provided but can be zero-length.</li>
<li><code>info</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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> Additional info value.
Must be provided but can be zero-length, and cannot be more than 1024 bytes.</li>
<li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The length of the key to generate. Must be greater than 0.
The maximum allowable value is <code>255</code> times the number of bytes produced by
the selected digest function (e.g. <code>sha512</code> generates 64-byte hashes, making
the maximum HKDF output 16320 bytes).</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>derivedKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a></li>
</ul>
</li>
</ul>
<p>HKDF is a simple key derivation function defined in RFC 5869. The given <code>ikm</code>,
<code>salt</code> and <code>info</code> are used with the <code>digest</code> to derive a key of <code>keylen</code> bytes.</p>
<p>The supplied <code>callback</code> function is called with two arguments: <code>err</code> and
<code>derivedKey</code>. If an errors occurs while deriving the key, <code>err</code> will be set;
otherwise <code>err</code> will be <code>null</code>. The successfully generated <code>derivedKey</code> will
be passed to the callback as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a>. An error will be thrown if any
of the input arguments specify invalid values or types.</p>
<pre class="with-37-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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> {
hkdf,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-title function_">hkdf</span>(<span class="hljs-string">'sha512'</span>, <span class="hljs-string">'key'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-string">'info'</span>, <span class="hljs-number">64</span>, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(derivedKey).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '24156e2...5391653'</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
hkdf,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-title function_">hkdf</span>(<span class="hljs-string">'sha512'</span>, <span class="hljs-string">'key'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-string">'info'</span>, <span class="hljs-number">64</span>, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(derivedKey).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '24156e2...5391653'</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.hkdfSync(digest, ikm, salt, info, keylen)</code><span><a class="mark" href="#all_crypto_cryptohkdfsyncdigest-ikm-salt-info-keylen" id="all_crypto_cryptohkdfsyncdigest-ikm-salt-info-keylen">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_hkdfsync_digest_ikm_salt_info_keylen"></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.8.0, v16.18.0</td>
<td><p>The input keying material can now be zero-length.</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>digest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The digest algorithm to use.</li>
<li><code>ikm</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> The input
keying material. Must be provided but can be zero-length.</li>
<li><code>salt</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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> The salt value. Must
be provided but can be zero-length.</li>
<li><code>info</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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> Additional info value.
Must be provided but can be zero-length, and cannot be more than 1024 bytes.</li>
<li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The length of the key to generate. Must be greater than 0.
The maximum allowable value is <code>255</code> times the number of bytes produced by
the selected digest function (e.g. <code>sha512</code> generates 64-byte hashes, making
the maximum HKDF output 16320 bytes).</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a></li>
</ul>
<p>Provides a synchronous HKDF key derivation function as defined in RFC 5869. The
given <code>ikm</code>, <code>salt</code> and <code>info</code> are used with the <code>digest</code> to derive a key of
<code>keylen</code> bytes.</p>
<p>The successfully generated <code>derivedKey</code> will be returned as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a>.</p>
<p>An error will be thrown if any of the input arguments specify invalid values or
types, or if the derived key cannot be generated.</p>
<pre class="with-37-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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> {
hkdfSync,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> derivedKey = <span class="hljs-title function_">hkdfSync</span>(<span class="hljs-string">'sha512'</span>, <span class="hljs-string">'key'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-string">'info'</span>, <span class="hljs-number">64</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(derivedKey).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '24156e2...5391653'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
hkdfSync,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> derivedKey = <span class="hljs-title function_">hkdfSync</span>(<span class="hljs-string">'sha512'</span>, <span class="hljs-string">'key'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-string">'info'</span>, <span class="hljs-number">64</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(derivedKey).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '24156e2...5391653'</span></code><button class="copy-button">copy</button></pre>
<h4><code>crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)</code><span><a class="mark" href="#all_crypto_cryptopbkdf2password-salt-iterations-keylen-digest-callback" id="all_crypto_cryptopbkdf2password-salt-iterations-keylen-digest-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_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>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>v15.0.0</td>
<td><p>The password and salt arguments can also be ArrayBuffer instances.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>iterations</code> parameter is now restricted to positive values. Earlier releases treated other values as one.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>digest</code> parameter is always required now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Calling this function without passing the <code>digest</code> parameter is deprecated now and will emit a warning.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The default encoding for <code>password</code> if it is a string changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>password</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>salt</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>iterations</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>digest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>derivedKey</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
</ul>
<p>Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
implementation. A selected HMAC digest algorithm specified by <code>digest</code> is
applied to derive a key of the requested byte length (<code>keylen</code>) from the
<code>password</code>, <code>salt</code> and <code>iterations</code>.</p>
<p>The supplied <code>callback</code> function is called with two arguments: <code>err</code> and
<code>derivedKey</code>. If an error occurs while deriving the key, <code>err</code> will be set;
otherwise <code>err</code> will be <code>null</code>. By default, the successfully generated
<code>derivedKey</code> will be passed to the callback as a <a href="buffer.html"><code>Buffer</code></a>. An error will be
thrown if any of the input arguments specify invalid values or types.</p>
<p>The <code>iterations</code> argument must be a number set as high as possible. The
higher the number of iterations, the more secure the derived key will be,
but will take a longer amount of time to complete.</p>
<p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p>
<p>When passing strings for <code>password</code> or <code>salt</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</p>
<pre class="with-9-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">const</span> {
pbkdf2,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-title function_">pbkdf2</span>(<span class="hljs-string">'secret'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">100000</span>, <span class="hljs-number">64</span>, <span class="hljs-string">'sha512'</span>, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(derivedKey.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '3745e48...08d59ae'</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
pbkdf2,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-title function_">pbkdf2</span>(<span class="hljs-string">'secret'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">100000</span>, <span class="hljs-number">64</span>, <span class="hljs-string">'sha512'</span>, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(derivedKey.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '3745e48...08d59ae'</span>
});</code><button class="copy-button">copy</button></pre>
<p>An array of supported digest functions can be retrieved using
<a href="#all_crypto_cryptogethashes"><code>crypto.getHashes()</code></a>.</p>
<p>This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the
<a href="#all_cli_uv_threadpool_sizesize"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>
<h4><code>crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)</code><span><a class="mark" href="#all_crypto_cryptopbkdf2syncpassword-salt-iterations-keylen-digest" id="all_crypto_cryptopbkdf2syncpassword-salt-iterations-keylen-digest">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest"></a></h4>
<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>The <code>iterations</code> parameter is now restricted to positive values. Earlier releases treated other values as one.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Calling this function without passing the <code>digest</code> parameter is deprecated now and will emit a warning.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The default encoding for <code>password</code> if it is a string changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.9.3</td>
<td><p><span>Added in: v0.9.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
<li><code>salt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
<li><code>iterations</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>digest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
implementation. A selected HMAC digest algorithm specified by <code>digest</code> is
applied to derive a key of the requested byte length (<code>keylen</code>) from the
<code>password</code>, <code>salt</code> and <code>iterations</code>.</p>
<p>If an error occurs an <code>Error</code> will be thrown, otherwise the derived key will be
returned as a <a href="buffer.html"><code>Buffer</code></a>.</p>
<p>The <code>iterations</code> argument must be a number set as high as possible. The
higher the number of iterations, the more secure the derived key will be,
but will take a longer amount of time to complete.</p>
<p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p>
<p>When passing strings for <code>password</code> or <code>salt</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</p>
<pre class="with-13-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">const</span> {
pbkdf2Sync,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">pbkdf2Sync</span>(<span class="hljs-string">'secret'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">100000</span>, <span class="hljs-number">64</span>, <span class="hljs-string">'sha512'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '3745e48...08d59ae'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
pbkdf2Sync,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">pbkdf2Sync</span>(<span class="hljs-string">'secret'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">100000</span>, <span class="hljs-number">64</span>, <span class="hljs-string">'sha512'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '3745e48...08d59ae'</span></code><button class="copy-button">copy</button></pre>
<p>An array of supported digest functions can be retrieved using
<a href="#all_crypto_cryptogethashes"><code>crypto.getHashes()</code></a>.</p>
<h4><code>crypto.privateDecrypt(privateKey, buffer)</code><span><a class="mark" href="#all_crypto_cryptoprivatedecryptprivatekey-buffer" id="all_crypto_cryptoprivatedecryptprivatekey-buffer">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_privatedecrypt_privatekey_buffer"></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.6.2, v20.11.1, v18.19.1</td>
<td><p>The <code>RSA_PKCS1_PADDING</code> padding was disabled unless the OpenSSL build supports implicit rejection.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Added string, ArrayBuffer, and CryptoKey as allowable key types. The oaepLabel can be an ArrayBuffer. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes.</p></td></tr>
<tr><td>v12.11.0</td>
<td><p>The <code>oaepLabel</code> option was added.</p></td></tr>
<tr><td>v12.9.0</td>
<td><p>The <code>oaepHash</code> option was added.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>This function now supports key objects.</p></td></tr>
<tr><td>v0.11.14</td>
<td><p><span>Added in: v0.11.14</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>privateKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>
<ul>
<li><code>oaepHash</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The hash function to use for OAEP padding and MGF1.
<strong>Default:</strong> <code>'sha1'</code></li>
<li><code>oaepLabel</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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> The label to
use for OAEP padding. If not specified, no label is used.</li>
<li><code>padding</code> <a href="#all_crypto_cryptoconstants" class="type"><crypto.constants></a> An optional padding value defined in
<code>crypto.constants</code>, which may be: <code>crypto.constants.RSA_NO_PADDING</code>,
<code>crypto.constants.RSA_PKCS1_PADDING</code>, or
<code>crypto.constants.RSA_PKCS1_OAEP_PADDING</code>.</li>
</ul>
</li>
<li><code>buffer</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> A new <code>Buffer</code> with the decrypted content.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Decrypts <code>buffer</code> with <code>privateKey</code>. <code>buffer</code> was previously encrypted using
the corresponding public key, for example using <a href="#all_crypto_cryptopublicencryptkey-buffer"><code>crypto.publicEncrypt()</code></a>.</p>
<p>If <code>privateKey</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>privateKey</code> had been passed to <a href="#all_crypto_cryptocreateprivatekeykey"><code>crypto.createPrivateKey()</code></a>. If it is an
object, the <code>padding</code> property can be passed. Otherwise, this function uses
<code>RSA_PKCS1_OAEP_PADDING</code>.</p>
<p>Using <code>crypto.constants.RSA_PKCS1_PADDING</code> in <a href="#all_crypto_cryptoprivatedecryptprivatekey-buffer"><code>crypto.privateDecrypt()</code></a>
requires OpenSSL to support implicit rejection (<code>rsa_pkcs1_implicit_rejection</code>).
If the version of OpenSSL used by Node.js does not support this feature,
attempting to use <code>RSA_PKCS1_PADDING</code> will fail.</p>
<h4><code>crypto.privateEncrypt(privateKey, buffer)</code><span><a class="mark" href="#all_crypto_cryptoprivateencryptprivatekey-buffer" id="all_crypto_cryptoprivateencryptprivatekey-buffer">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_privateencrypt_privatekey_buffer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Added string, ArrayBuffer, and CryptoKey as allowable key types. The passphrase can be an ArrayBuffer. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>This function now supports key objects.</p></td></tr>
<tr><td>v1.1.0</td>
<td><p><span>Added in: v1.1.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>privateKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>
<ul>
<li><code>key</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>
A PEM encoded private key.</li>
<li><code>passphrase</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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> An optional
passphrase for the private key.</li>
<li><code>padding</code> <a href="#all_crypto_cryptoconstants" class="type"><crypto.constants></a> An optional padding value defined in
<code>crypto.constants</code>, which may be: <code>crypto.constants.RSA_NO_PADDING</code> or
<code>crypto.constants.RSA_PKCS1_PADDING</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 string encoding to use when <code>buffer</code>, <code>key</code>,
or <code>passphrase</code> are strings.</li>
</ul>
</li>
<li><code>buffer</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> A new <code>Buffer</code> with the encrypted content.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Encrypts <code>buffer</code> with <code>privateKey</code>. The returned data can be decrypted using
the corresponding public key, for example using <a href="#all_crypto_cryptopublicdecryptkey-buffer"><code>crypto.publicDecrypt()</code></a>.</p>
<p>If <code>privateKey</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>privateKey</code> had been passed to <a href="#all_crypto_cryptocreateprivatekeykey"><code>crypto.createPrivateKey()</code></a>. If it is an
object, the <code>padding</code> property can be passed. Otherwise, this function uses
<code>RSA_PKCS1_PADDING</code>.</p>
<h4><code>crypto.publicDecrypt(key, buffer)</code><span><a class="mark" href="#all_crypto_cryptopublicdecryptkey-buffer" id="all_crypto_cryptopublicdecryptkey-buffer">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_publicdecrypt_key_buffer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Added string, ArrayBuffer, and CryptoKey as allowable key types. The passphrase can be an ArrayBuffer. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>This function now supports key objects.</p></td></tr>
<tr><td>v1.1.0</td>
<td><p><span>Added in: v1.1.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>
<ul>
<li><code>passphrase</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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> An optional
passphrase for the private key.</li>
<li><code>padding</code> <a href="#all_crypto_cryptoconstants" class="type"><crypto.constants></a> An optional padding value defined in
<code>crypto.constants</code>, which may be: <code>crypto.constants.RSA_NO_PADDING</code> or
<code>crypto.constants.RSA_PKCS1_PADDING</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 string encoding to use when <code>buffer</code>, <code>key</code>,
or <code>passphrase</code> are strings.</li>
</ul>
</li>
<li><code>buffer</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> A new <code>Buffer</code> with the decrypted content.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Decrypts <code>buffer</code> with <code>key</code>.<code>buffer</code> was previously encrypted using
the corresponding private key, for example using <a href="#all_crypto_cryptoprivateencryptprivatekey-buffer"><code>crypto.privateEncrypt()</code></a>.</p>
<p>If <code>key</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>key</code> had been passed to <a href="#all_crypto_cryptocreatepublickeykey"><code>crypto.createPublicKey()</code></a>. If it is an
object, the <code>padding</code> property can be passed. Otherwise, this function uses
<code>RSA_PKCS1_PADDING</code>.</p>
<p>Because RSA public keys can be derived from private keys, a private key may
be passed instead of a public key.</p>
<h4><code>crypto.publicEncrypt(key, buffer)</code><span><a class="mark" href="#all_crypto_cryptopublicencryptkey-buffer" id="all_crypto_cryptopublicencryptkey-buffer">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_publicencrypt_key_buffer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Added string, ArrayBuffer, and CryptoKey as allowable key types. The oaepLabel and passphrase can be ArrayBuffers. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes.</p></td></tr>
<tr><td>v12.11.0</td>
<td><p>The <code>oaepLabel</code> option was added.</p></td></tr>
<tr><td>v12.9.0</td>
<td><p>The <code>oaepHash</code> option was added.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>This function now supports key objects.</p></td></tr>
<tr><td>v0.11.14</td>
<td><p><span>Added in: v0.11.14</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>
<ul>
<li><code>key</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>
A PEM encoded public or private key, <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a>, or <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>.</li>
<li><code>oaepHash</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The hash function to use for OAEP padding and MGF1.
<strong>Default:</strong> <code>'sha1'</code></li>
<li><code>oaepLabel</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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> The label to
use for OAEP padding. If not specified, no label is used.</li>
<li><code>passphrase</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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> An optional
passphrase for the private key.</li>
<li><code>padding</code> <a href="#all_crypto_cryptoconstants" class="type"><crypto.constants></a> An optional padding value defined in
<code>crypto.constants</code>, which may be: <code>crypto.constants.RSA_NO_PADDING</code>,
<code>crypto.constants.RSA_PKCS1_PADDING</code>, or
<code>crypto.constants.RSA_PKCS1_OAEP_PADDING</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 string encoding to use when <code>buffer</code>, <code>key</code>,
<code>oaepLabel</code>, or <code>passphrase</code> are strings.</li>
</ul>
</li>
<li><code>buffer</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> A new <code>Buffer</code> with the encrypted content.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Encrypts the content of <code>buffer</code> with <code>key</code> and returns a new
<a href="buffer.html"><code>Buffer</code></a> with encrypted content. The returned data can be decrypted using
the corresponding private key, for example using <a href="#all_crypto_cryptoprivatedecryptprivatekey-buffer"><code>crypto.privateDecrypt()</code></a>.</p>
<p>If <code>key</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>key</code> had been passed to <a href="#all_crypto_cryptocreatepublickeykey"><code>crypto.createPublicKey()</code></a>. If it is an
object, the <code>padding</code> property can be passed. Otherwise, this function uses
<code>RSA_PKCS1_OAEP_PADDING</code>.</p>
<p>Because RSA public keys can be derived from private keys, a private key may
be passed instead of a public key.</p>
<h4><code>crypto.randomBytes(size[, callback])</code><span><a class="mark" href="#all_crypto_cryptorandombytessize-callback" id="all_crypto_cryptorandombytessize-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_randombytes_size_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>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>v9.0.0</td>
<td><p>Passing <code>null</code> as the <code>callback</code> argument now throws <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v0.5.8</td>
<td><p><span>Added in: v0.5.8</span></p></td></tr>
</tbody></table>
</details>
</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> The number of bytes to generate. The <code>size</code> must
not be larger than <code>2**31 - 1</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>
<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>buf</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> if the <code>callback</code> function is not provided.</li>
</ul>
<p>Generates cryptographically strong pseudorandom data. The <code>size</code> argument
is a number indicating the number of bytes to generate.</p>
<p>If a <code>callback</code> function is provided, the bytes are generated asynchronously
and the <code>callback</code> function is invoked with two arguments: <code>err</code> and <code>buf</code>.
If an error occurs, <code>err</code> will be an <code>Error</code> object; otherwise it is <code>null</code>. The
<code>buf</code> argument is a <a href="buffer.html"><code>Buffer</code></a> containing the generated bytes.</p>
<pre class="with-15-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// Asynchronous</span>
<span class="hljs-keyword">const</span> {
randomBytes,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-title function_">randomBytes</span>(<span class="hljs-number">256</span>, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${buf.length}</span> bytes of random data: <span class="hljs-subst">${buf.toString(<span class="hljs-string">'hex'</span>)}</span>`</span>);
});</code><code class="language-js cjs"><span class="hljs-comment">// Asynchronous</span>
<span class="hljs-keyword">const</span> {
randomBytes,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-title function_">randomBytes</span>(<span class="hljs-number">256</span>, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${buf.length}</span> bytes of random data: <span class="hljs-subst">${buf.toString(<span class="hljs-string">'hex'</span>)}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<p>If the <code>callback</code> function is not provided, the random bytes are generated
synchronously and returned as a <a href="buffer.html"><code>Buffer</code></a>. An error will be thrown if
there is a problem generating the bytes.</p>
<pre class="with-14-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// Synchronous</span>
<span class="hljs-keyword">const</span> {
randomBytes,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title function_">randomBytes</span>(<span class="hljs-number">256</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
<span class="hljs-string">`<span class="hljs-subst">${buf.length}</span> bytes of random data: <span class="hljs-subst">${buf.toString(<span class="hljs-string">'hex'</span>)}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-comment">// Synchronous</span>
<span class="hljs-keyword">const</span> {
randomBytes,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title function_">randomBytes</span>(<span class="hljs-number">256</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
<span class="hljs-string">`<span class="hljs-subst">${buf.length}</span> bytes of random data: <span class="hljs-subst">${buf.toString(<span class="hljs-string">'hex'</span>)}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<p>The <code>crypto.randomBytes()</code> method will not complete until there is
sufficient entropy available.
This should normally never take longer than a few milliseconds. The only time
when generating the random bytes may conceivably block for a longer period of
time is right after boot, when the whole system is still low on entropy.</p>
<p>This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the
<a href="#all_cli_uv_threadpool_sizesize"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>
<p>The asynchronous version of <code>crypto.randomBytes()</code> is carried out in a single
threadpool request. To minimize threadpool task length variation, partition
large <code>randomBytes</code> requests when doing so as part of fulfilling a client
request.</p>
<h4><code>crypto.randomFillSync(buffer[, offset][, size])</code><span><a class="mark" href="#all_crypto_cryptorandomfillsyncbuffer-offset-size" id="all_crypto_cryptorandomfillsyncbuffer-offset-size">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_randomfillsync_buffer_offset_size"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>buffer</code> argument may be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v7.10.0, v6.13.0</td>
<td><p><span>Added in: v7.10.0, v6.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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> Must be supplied. The
size of the provided <code>buffer</code> must not be larger than <code>2**31 - 1</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>0</code></li>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>buffer.length - offset</code>. The <code>size</code> must
not be larger than <code>2**31 - 1</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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> The object passed as
<code>buffer</code> argument.</li>
</ul>
<p>Synchronous version of <a href="#all_crypto_cryptorandomfillbuffer-offset-size-callback"><code>crypto.randomFill()</code></a>.</p>
<pre class="with-55-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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> { randomFillSync } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">randomFillSync</span>(buf).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-title function_">randomFillSync</span>(buf, <span class="hljs-number">5</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// The above is equivalent to the following:</span>
<span class="hljs-title function_">randomFillSync</span>(buf, <span class="hljs-number">5</span>, <span class="hljs-number">5</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { randomFillSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">randomFillSync</span>(buf).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-title function_">randomFillSync</span>(buf, <span class="hljs-number">5</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// The above is equivalent to the following:</span>
<span class="hljs-title function_">randomFillSync</span>(buf, <span class="hljs-number">5</span>, <span class="hljs-number">5</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));</code><button class="copy-button">copy</button></pre>
<p>Any <code>ArrayBuffer</code>, <code>TypedArray</code> or <code>DataView</code> instance may be passed as
<code>buffer</code>.</p>
<pre class="with-55-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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> { randomFillSync } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">randomFillSync</span>(a).<span class="hljs-property">buffer</span>,
a.<span class="hljs-property">byteOffset</span>, a.<span class="hljs-property">byteLength</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title class_">DataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">randomFillSync</span>(b).<span class="hljs-property">buffer</span>,
b.<span class="hljs-property">byteOffset</span>, b.<span class="hljs-property">byteLength</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-keyword">const</span> c = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">randomFillSync</span>(c)).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { randomFillSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">randomFillSync</span>(a).<span class="hljs-property">buffer</span>,
a.<span class="hljs-property">byteOffset</span>, a.<span class="hljs-property">byteLength</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title class_">DataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">randomFillSync</span>(b).<span class="hljs-property">buffer</span>,
b.<span class="hljs-property">byteOffset</span>, b.<span class="hljs-property">byteLength</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-keyword">const</span> c = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">randomFillSync</span>(c)).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.randomFill(buffer[, offset][, size], callback)</code><span><a class="mark" href="#all_crypto_cryptorandomfillbuffer-offset-size-callback" id="all_crypto_cryptorandomfillbuffer-offset-size-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_randomfill_buffer_offset_size_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>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>v9.0.0</td>
<td><p>The <code>buffer</code> argument may be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v7.10.0, v6.13.0</td>
<td><p><span>Added in: v7.10.0, v6.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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> Must be supplied. The
size of the provided <code>buffer</code> must not be larger than <code>2**31 - 1</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>0</code></li>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>buffer.length - offset</code>. The <code>size</code> must
not be larger than <code>2**31 - 1</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> <code>function(err, buf) {}</code>.</li>
</ul>
<p>This function is similar to <a href="#all_crypto_cryptorandombytessize-callback"><code>crypto.randomBytes()</code></a> but requires the first
argument to be a <a href="buffer.html"><code>Buffer</code></a> that will be filled. It also
requires that a callback is passed in.</p>
<p>If the <code>callback</code> function is not provided, an error will be thrown.</p>
<pre class="with-51-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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> { randomFill } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-title function_">randomFill</span>(buf, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});
<span class="hljs-title function_">randomFill</span>(buf, <span class="hljs-number">5</span>, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});
<span class="hljs-comment">// The above is equivalent to the following:</span>
<span class="hljs-title function_">randomFill</span>(buf, <span class="hljs-number">5</span>, <span class="hljs-number">5</span>, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { randomFill } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-title function_">randomFill</span>(buf, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});
<span class="hljs-title function_">randomFill</span>(buf, <span class="hljs-number">5</span>, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});
<span class="hljs-comment">// The above is equivalent to the following:</span>
<span class="hljs-title function_">randomFill</span>(buf, <span class="hljs-number">5</span>, <span class="hljs-number">5</span>, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});</code><button class="copy-button">copy</button></pre>
<p>Any <code>ArrayBuffer</code>, <code>TypedArray</code>, or <code>DataView</code> instance may be passed as
<code>buffer</code>.</p>
<p>While this includes instances of <code>Float32Array</code> and <code>Float64Array</code>, this
function should not be used to generate random floating-point numbers. The
result may contain <code>+Infinity</code>, <code>-Infinity</code>, and <code>NaN</code>, and even if the array
contains finite numbers only, they are not drawn from a uniform random
distribution and have no meaningful lower or upper bounds.</p>
<pre class="with-51-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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> { randomFill } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>(<span class="hljs-number">10</span>);
<span class="hljs-title function_">randomFill</span>(a, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf.<span class="hljs-property">buffer</span>, buf.<span class="hljs-property">byteOffset</span>, buf.<span class="hljs-property">byteLength</span>)
.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});
<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title class_">DataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>));
<span class="hljs-title function_">randomFill</span>(b, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf.<span class="hljs-property">buffer</span>, buf.<span class="hljs-property">byteOffset</span>, buf.<span class="hljs-property">byteLength</span>)
.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});
<span class="hljs-keyword">const</span> c = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-title function_">randomFill</span>(c, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { randomFill } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>(<span class="hljs-number">10</span>);
<span class="hljs-title function_">randomFill</span>(a, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf.<span class="hljs-property">buffer</span>, buf.<span class="hljs-property">byteOffset</span>, buf.<span class="hljs-property">byteLength</span>)
.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});
<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title class_">DataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>));
<span class="hljs-title function_">randomFill</span>(b, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf.<span class="hljs-property">buffer</span>, buf.<span class="hljs-property">byteOffset</span>, buf.<span class="hljs-property">byteLength</span>)
.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});
<span class="hljs-keyword">const</span> c = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-title function_">randomFill</span>(c, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});</code><button class="copy-button">copy</button></pre>
<p>This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the
<a href="#all_cli_uv_threadpool_sizesize"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>
<p>The asynchronous version of <code>crypto.randomFill()</code> is carried out in a single
threadpool request. To minimize threadpool task length variation, partition
large <code>randomFill</code> requests when doing so as part of fulfilling a client
request.</p>
<h4><code>crypto.randomInt([min, ]max[, callback])</code><span><a class="mark" href="#all_crypto_cryptorandomintmin-max-callback" id="all_crypto_cryptorandomintmin-max-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_randomint_min_max_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>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.10.0, v12.19.0</td>
<td><p><span>Added in: v14.10.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>min</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Start of random range (inclusive). <strong>Default:</strong> <code>0</code>.</li>
<li><code>max</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> End of random range (exclusive).</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> <code>function(err, n) {}</code>.</li>
</ul>
<p>Return a random integer <code>n</code> such that <code>min <= n < max</code>. This
implementation avoids <a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias">modulo bias</a>.</p>
<p>The range (<code>max - min</code>) must be less than 2<sup>48</sup>. <code>min</code> and <code>max</code> must
be <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger">safe integers</a>.</p>
<p>If the <code>callback</code> function is not provided, the random integer is
generated synchronously.</p>
<pre class="with-15-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// Asynchronous</span>
<span class="hljs-keyword">const</span> {
randomInt,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-title function_">randomInt</span>(<span class="hljs-number">3</span>, <span class="hljs-function">(<span class="hljs-params">err, n</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Random number chosen from (0, 1, 2): <span class="hljs-subst">${n}</span>`</span>);
});</code><code class="language-js cjs"><span class="hljs-comment">// Asynchronous</span>
<span class="hljs-keyword">const</span> {
randomInt,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-title function_">randomInt</span>(<span class="hljs-number">3</span>, <span class="hljs-function">(<span class="hljs-params">err, n</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Random number chosen from (0, 1, 2): <span class="hljs-subst">${n}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<pre class="with-14-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// Synchronous</span>
<span class="hljs-keyword">const</span> {
randomInt,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> n = <span class="hljs-title function_">randomInt</span>(<span class="hljs-number">3</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Random number chosen from (0, 1, 2): <span class="hljs-subst">${n}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-comment">// Synchronous</span>
<span class="hljs-keyword">const</span> {
randomInt,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> n = <span class="hljs-title function_">randomInt</span>(<span class="hljs-number">3</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Random number chosen from (0, 1, 2): <span class="hljs-subst">${n}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<pre class="with-22-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// With `min` argument</span>
<span class="hljs-keyword">const</span> {
randomInt,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> n = <span class="hljs-title function_">randomInt</span>(<span class="hljs-number">1</span>, <span class="hljs-number">7</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The dice rolled: <span class="hljs-subst">${n}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-comment">// With `min` argument</span>
<span class="hljs-keyword">const</span> {
randomInt,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> n = <span class="hljs-title function_">randomInt</span>(<span class="hljs-number">1</span>, <span class="hljs-number">7</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The dice rolled: <span class="hljs-subst">${n}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.randomUUID([options])</code><span><a class="mark" href="#all_crypto_cryptorandomuuidoptions" id="all_crypto_cryptorandomuuidoptions">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_randomuuid_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0, v14.17.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>
<ul>
<li><code>disableEntropyCache</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> By default, to improve performance,
Node.js generates and caches enough
random data to generate up to 128 random UUIDs. To generate a UUID
without using the cache, set <code>disableEntropyCache</code> to <code>true</code>.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Generates a random <a href="https://www.rfc-editor.org/rfc/rfc4122.txt">RFC 4122</a> version 4 UUID. The UUID is generated using a
cryptographic pseudorandom number generator.</p>
<h4><code>crypto.scrypt(password, salt, keylen[, options], callback)</code><span><a class="mark" href="#all_crypto_cryptoscryptpassword-salt-keylen-options-callback" id="all_crypto_cryptoscryptpassword-salt-keylen-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_scrypt_password_salt_keylen_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>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>v15.0.0</td>
<td><p>The password and salt arguments can also be ArrayBuffer instances.</p></td></tr>
<tr><td>v12.8.0, v10.17.0</td>
<td><p>The <code>maxmem</code> value can now be any safe integer.</p></td></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>cost</code>, <code>blockSize</code> and <code>parallelization</code> option names have been added.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>password</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>salt</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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>cost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> CPU/memory cost parameter. Must be a power of two greater
than one. <strong>Default:</strong> <code>16384</code>.</li>
<li><code>blockSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Block size parameter. <strong>Default:</strong> <code>8</code>.</li>
<li><code>parallelization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Parallelization parameter. <strong>Default:</strong> <code>1</code>.</li>
<li><code>N</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>cost</code>. Only one of both may be specified.</li>
<li><code>r</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>blockSize</code>. Only one of both may be specified.</li>
<li><code>p</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>parallelization</code>. Only one of both may be specified.</li>
<li><code>maxmem</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Memory upper bound. It is an error when (approximately)
<code>128 * N * r > maxmem</code>. <strong>Default:</strong> <code>32 * 1024 * 1024</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>
<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>derivedKey</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
</ul>
<p>Provides an asynchronous <a href="https://en.wikipedia.org/wiki/Scrypt">scrypt</a> implementation. Scrypt is a password-based
key derivation function that is designed to be expensive computationally and
memory-wise in order to make brute-force attacks unrewarding.</p>
<p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p>
<p>When passing strings for <code>password</code> or <code>salt</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</p>
<p>The <code>callback</code> function is called with two arguments: <code>err</code> and <code>derivedKey</code>.
<code>err</code> is an exception object when key derivation fails, otherwise <code>err</code> is
<code>null</code>. <code>derivedKey</code> is passed to the callback as a <a href="buffer.html"><code>Buffer</code></a>.</p>
<p>An exception is thrown when any of the input arguments specify invalid values
or types.</p>
<pre class="with-9-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">const</span> {
scrypt,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-comment">// Using the factory defaults.</span>
<span class="hljs-title function_">scrypt</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(derivedKey.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '3745e48...08d59ae'</span>
});
<span class="hljs-comment">// Using a custom N parameter. Must be a power of two.</span>
<span class="hljs-title function_">scrypt</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>, { <span class="hljs-attr">N</span>: <span class="hljs-number">1024</span> }, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(derivedKey.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '3745e48...aa39b34'</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
scrypt,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-comment">// Using the factory defaults.</span>
<span class="hljs-title function_">scrypt</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(derivedKey.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '3745e48...08d59ae'</span>
});
<span class="hljs-comment">// Using a custom N parameter. Must be a power of two.</span>
<span class="hljs-title function_">scrypt</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>, { <span class="hljs-attr">N</span>: <span class="hljs-number">1024</span> }, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(derivedKey.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '3745e48...aa39b34'</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.scryptSync(password, salt, keylen[, options])</code><span><a class="mark" href="#all_crypto_cryptoscryptsyncpassword-salt-keylen-options" id="all_crypto_cryptoscryptsyncpassword-salt-keylen-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_scryptsync_password_salt_keylen_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>v12.8.0, v10.17.0</td>
<td><p>The <code>maxmem</code> value can now be any safe integer.</p></td></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>cost</code>, <code>blockSize</code> and <code>parallelization</code> option names have been added.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
<li><code>salt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
<li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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>cost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> CPU/memory cost parameter. Must be a power of two greater
than one. <strong>Default:</strong> <code>16384</code>.</li>
<li><code>blockSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Block size parameter. <strong>Default:</strong> <code>8</code>.</li>
<li><code>parallelization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Parallelization parameter. <strong>Default:</strong> <code>1</code>.</li>
<li><code>N</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>cost</code>. Only one of both may be specified.</li>
<li><code>r</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>blockSize</code>. Only one of both may be specified.</li>
<li><code>p</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>parallelization</code>. Only one of both may be specified.</li>
<li><code>maxmem</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Memory upper bound. It is an error when (approximately)
<code>128 * N * r > maxmem</code>. <strong>Default:</strong> <code>32 * 1024 * 1024</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Provides a synchronous <a href="https://en.wikipedia.org/wiki/Scrypt">scrypt</a> implementation. Scrypt is a password-based
key derivation function that is designed to be expensive computationally and
memory-wise in order to make brute-force attacks unrewarding.</p>
<p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p>
<p>When passing strings for <code>password</code> or <code>salt</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</p>
<p>An exception is thrown when key derivation fails, otherwise the derived key is
returned as a <a href="buffer.html"><code>Buffer</code></a>.</p>
<p>An exception is thrown when any of the input arguments specify invalid values
or types.</p>
<pre class="with-13-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">const</span> {
scryptSync,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-comment">// Using the factory defaults.</span>
<span class="hljs-keyword">const</span> key1 = <span class="hljs-title function_">scryptSync</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '3745e48...08d59ae'</span>
<span class="hljs-comment">// Using a custom N parameter. Must be a power of two.</span>
<span class="hljs-keyword">const</span> key2 = <span class="hljs-title function_">scryptSync</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>, { <span class="hljs-attr">N</span>: <span class="hljs-number">1024</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '3745e48...aa39b34'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
scryptSync,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-comment">// Using the factory defaults.</span>
<span class="hljs-keyword">const</span> key1 = <span class="hljs-title function_">scryptSync</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '3745e48...08d59ae'</span>
<span class="hljs-comment">// Using a custom N parameter. Must be a power of two.</span>
<span class="hljs-keyword">const</span> key2 = <span class="hljs-title function_">scryptSync</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>, { <span class="hljs-attr">N</span>: <span class="hljs-number">1024</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)); <span class="hljs-comment">// '3745e48...aa39b34'</span></code><button class="copy-button">copy</button></pre>
<h4><code>crypto.secureHeapUsed()</code><span><a class="mark" href="#all_crypto_cryptosecureheapused" id="all_crypto_cryptosecureheapused">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_secureheapused"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>total</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total allocated secure heap size as specified
using the <code>--secure-heap=n</code> command-line flag.</li>
<li><code>min</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The minimum allocation from the secure heap as
specified using the <code>--secure-heap-min</code> command-line flag.</li>
<li><code>used</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of bytes currently allocated from
the secure heap.</li>
<li><code>utilization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The calculated ratio of <code>used</code> to <code>total</code>
allocated bytes.</li>
</ul>
</li>
</ul>
<h4><code>crypto.setEngine(engine[, flags])</code><span><a class="mark" href="#all_crypto_cryptosetengineengine-flags" id="all_crypto_cryptosetengineengine-flags">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_setengine_engine_flags"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>Custom engine support in OpenSSL 3 is deprecated.</p></td></tr>
<tr><td>v0.11.11</td>
<td><p><span>Added in: v0.11.11</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>engine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>flags</code> <a href="#all_crypto_cryptoconstants" class="type"><crypto.constants></a> <strong>Default:</strong> <code>crypto.constants.ENGINE_METHOD_ALL</code></li>
</ul>
<p>Load and set the <code>engine</code> for some or all OpenSSL functions (selected by flags).
Support for custom engines in OpenSSL is deprecated from OpenSSL 3.</p>
<p><code>engine</code> could be either an id or a path to the engine's shared library.</p>
<p>The optional <code>flags</code> argument uses <code>ENGINE_METHOD_ALL</code> by default. The <code>flags</code>
is a bit field taking one of or a mix of the following flags (defined in
<code>crypto.constants</code>):</p>
<ul>
<li><code>crypto.constants.ENGINE_METHOD_RSA</code></li>
<li><code>crypto.constants.ENGINE_METHOD_DSA</code></li>
<li><code>crypto.constants.ENGINE_METHOD_DH</code></li>
<li><code>crypto.constants.ENGINE_METHOD_RAND</code></li>
<li><code>crypto.constants.ENGINE_METHOD_EC</code></li>
<li><code>crypto.constants.ENGINE_METHOD_CIPHERS</code></li>
<li><code>crypto.constants.ENGINE_METHOD_DIGESTS</code></li>
<li><code>crypto.constants.ENGINE_METHOD_PKEY_METHS</code></li>
<li><code>crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS</code></li>
<li><code>crypto.constants.ENGINE_METHOD_ALL</code></li>
<li><code>crypto.constants.ENGINE_METHOD_NONE</code></li>
</ul>
<h4><code>crypto.setFips(bool)</code><span><a class="mark" href="#all_crypto_cryptosetfipsbool" id="all_crypto_cryptosetfipsbool">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_setfips_bool"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>bool</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> to enable FIPS mode.</li>
</ul>
<p>Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.
Throws an error if FIPS mode is not available.</p>
<h4><code>crypto.sign(algorithm, data, key[, callback])</code><span><a class="mark" href="#all_crypto_cryptosignalgorithm-data-key-callback" id="all_crypto_cryptosignalgorithm-data-key-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_sign_algorithm_data_key_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>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>v15.12.0</td>
<td><p>Optional callback argument added.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>This function now supports IEEE-P1363 DSA and ECDSA signatures.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p><span>Added in: v12.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>signature</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> if the <code>callback</code> function is not provided.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Calculates and returns the signature for <code>data</code> using the given private key and
algorithm. If <code>algorithm</code> is <code>null</code> or <code>undefined</code>, then the algorithm is
dependent upon the key type (especially Ed25519 and Ed448).</p>
<p>If <code>key</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if <code>key</code> had been
passed to <a href="#all_crypto_cryptocreateprivatekeykey"><code>crypto.createPrivateKey()</code></a>. If it is an object, the following
additional properties can be passed:</p>
<ul>
<li>
<p><code>dsaEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> For DSA and ECDSA, this option specifies the
format of the generated signature. It can be one of the following:</p>
<ul>
<li><code>'der'</code> (default): DER-encoded ASN.1 signature structure encoding <code>(r, s)</code>.</li>
<li><code>'ieee-p1363'</code>: Signature format <code>r || s</code> as proposed in IEEE-P1363.</li>
</ul>
</li>
<li>
<p><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Optional padding value for RSA, one of the following:</p>
<ul>
<li><code>crypto.constants.RSA_PKCS1_PADDING</code> (default)</li>
<li><code>crypto.constants.RSA_PKCS1_PSS_PADDING</code></li>
</ul>
<p><code>RSA_PKCS1_PSS_PADDING</code> will use MGF1 with the same hash function
used to sign the message as specified in section 3.1 of <a href="https://www.rfc-editor.org/rfc/rfc4055.txt">RFC 4055</a>.</p>
</li>
<li>
<p><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Salt length for when padding is
<code>RSA_PKCS1_PSS_PADDING</code>. The special value
<code>crypto.constants.RSA_PSS_SALTLEN_DIGEST</code> sets the salt length to the digest
size, <code>crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN</code> (default) sets it to the
maximum permissible value.</p>
</li>
</ul>
<p>If the <code>callback</code> function is provided this function uses libuv's threadpool.</p>
<h4><code>crypto.subtle</code><span><a class="mark" href="#all_crypto_cryptosubtle" id="all_crypto_cryptosubtle">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_subtle"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0</span>
</div>
<ul>
<li>Type: <a href="#all_webcrypto_class-subtlecrypto" class="type"><SubtleCrypto></a></li>
</ul>
<p>A convenient alias for <a href="#all_webcrypto_class-subtlecrypto"><code>crypto.webcrypto.subtle</code></a>.</p>
<h4><code>crypto.timingSafeEqual(a, b)</code><span><a class="mark" href="#all_crypto_cryptotimingsafeequala-b" id="all_crypto_cryptotimingsafeequala-b">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_timingsafeequal_a_b"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The a and b arguments can also be ArrayBuffer.</p></td></tr>
<tr><td>v6.6.0</td>
<td><p><span>Added in: v6.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>a</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>b</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></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>This function compares the underlying bytes that represent the given
<code>ArrayBuffer</code>, <code>TypedArray</code>, or <code>DataView</code> instances using a constant-time
algorithm.</p>
<p>This function does not leak timing information that
would allow an attacker to guess one of the values. This is suitable for
comparing HMAC digests or secret values like authentication cookies or
<a href="https://www.w3.org/TR/capability-urls/">capability urls</a>.</p>
<p><code>a</code> and <code>b</code> must both be <code>Buffer</code>s, <code>TypedArray</code>s, or <code>DataView</code>s, and they
must have the same byte length. An error is thrown if <code>a</code> and <code>b</code> have
different byte lengths.</p>
<p>If at least one of <code>a</code> and <code>b</code> is a <code>TypedArray</code> with more than one byte per
entry, such as <code>Uint16Array</code>, the result will be computed using the platform
byte order.</p>
<p><strong class="critical">When both of the inputs are <code>Float32Array</code>s or
<code>Float64Array</code>s, this function might return unexpected results due to IEEE 754
encoding of floating-point numbers. In particular, neither <code>x === y</code> nor
<code>Object.is(x, y)</code> implies that the byte representations of two floating-point
numbers <code>x</code> and <code>y</code> are equal.</strong></p>
<p>Use of <code>crypto.timingSafeEqual</code> does not guarantee that the <em>surrounding</em> code
is timing-safe. Care should be taken to ensure that the surrounding code does
not introduce timing vulnerabilities.</p>
<h4><code>crypto.verify(algorithm, data, key, signature[, callback])</code><span><a class="mark" href="#all_crypto_cryptoverifyalgorithm-data-key-signature-callback" id="all_crypto_cryptoverifyalgorithm-data-key-signature-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_verify_algorithm_data_key_signature_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>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>v15.12.0</td>
<td><p>Optional callback argument added.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The data, key, and signature arguments can also be ArrayBuffer.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>This function now supports IEEE-P1363 DSA and ECDSA signatures.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p><span>Added in: v12.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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="#all_crypto_class-keyobject" class="type"><KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li><code>signature</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="#all_buffer_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></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>result</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
</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> or <code>false</code> depending on the validity of the
signature for the data and public key if the <code>callback</code> function is not
provided.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Verifies the given signature for <code>data</code> using the given key and algorithm. If
<code>algorithm</code> is <code>null</code> or <code>undefined</code>, then the algorithm is dependent upon the
key type (especially Ed25519 and Ed448).</p>
<p>If <code>key</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if <code>key</code> had been
passed to <a href="#all_crypto_cryptocreatepublickeykey"><code>crypto.createPublicKey()</code></a>. If it is an object, the following
additional properties can be passed:</p>
<ul>
<li>
<p><code>dsaEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> For DSA and ECDSA, this option specifies the
format of the signature. It can be one of the following:</p>
<ul>
<li><code>'der'</code> (default): DER-encoded ASN.1 signature structure encoding <code>(r, s)</code>.</li>
<li><code>'ieee-p1363'</code>: Signature format <code>r || s</code> as proposed in IEEE-P1363.</li>
</ul>
</li>
<li>
<p><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Optional padding value for RSA, one of the following:</p>
<ul>
<li><code>crypto.constants.RSA_PKCS1_PADDING</code> (default)</li>
<li><code>crypto.constants.RSA_PKCS1_PSS_PADDING</code></li>
</ul>
<p><code>RSA_PKCS1_PSS_PADDING</code> will use MGF1 with the same hash function
used to sign the message as specified in section 3.1 of <a href="https://www.rfc-editor.org/rfc/rfc4055.txt">RFC 4055</a>.</p>
</li>
<li>
<p><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Salt length for when padding is
<code>RSA_PKCS1_PSS_PADDING</code>. The special value
<code>crypto.constants.RSA_PSS_SALTLEN_DIGEST</code> sets the salt length to the digest
size, <code>crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN</code> (default) sets it to the
maximum permissible value.</p>
</li>
</ul>
<p>The <code>signature</code> argument is the previously calculated signature for the <code>data</code>.</p>
<p>Because public keys can be derived from private keys, a private key or a public
key may be passed for <code>key</code>.</p>
<p>If the <code>callback</code> function is provided this function uses libuv's threadpool.</p>
<h4><code>crypto.webcrypto</code><span><a class="mark" href="#all_crypto_cryptowebcrypto" id="all_crypto_cryptowebcrypto">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_webcrypto"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>Type: <a href="#all_webcrypto_class-crypto" class="type"><Crypto></a> An implementation of the Web Crypto API standard.</p>
<p>See the <a href="webcrypto.html">Web Crypto API documentation</a> for details.</p>
</section><section><h3>Notes<span><a class="mark" href="#all_crypto_notes" id="all_crypto_notes">#</a></span><a aria-hidden="true" class="legacy" id="crypto_notes"></a></h3>
<h4>Using strings as inputs to cryptographic APIs<span><a class="mark" href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis" id="all_crypto_using-strings-as-inputs-to-cryptographic-apis">#</a></span><a aria-hidden="true" class="legacy" id="crypto_using_strings_as_inputs_to_cryptographic_apis"></a></h4>
<p>For historical reasons, many cryptographic APIs provided by Node.js accept
strings as inputs where the underlying cryptographic algorithm works on byte
sequences. These instances include plaintexts, ciphertexts, symmetric keys,
initialization vectors, passphrases, salts, authentication tags,
and additional authenticated data.</p>
<p>When passing strings to cryptographic APIs, consider the following factors.</p>
<ul>
<li>
<p>Not all byte sequences are valid UTF-8 strings. Therefore, when a byte
sequence of length <code>n</code> is derived from a string, its entropy is generally
lower than the entropy of a random or pseudorandom <code>n</code> byte sequence.
For example, no UTF-8 string will result in the byte sequence <code>c0 af</code>. Secret
keys should almost exclusively be random or pseudorandom byte sequences.</p>
</li>
<li>
<p>Similarly, when converting random or pseudorandom byte sequences to UTF-8
strings, subsequences that do not represent valid code points may be replaced
by the Unicode replacement character (<code>U+FFFD</code>). The byte representation of
the resulting Unicode string may, therefore, not be equal to the byte sequence
that the string was created from.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> original = [<span class="hljs-number">0xc0</span>, <span class="hljs-number">0xaf</span>];
<span class="hljs-keyword">const</span> bytesAsString = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(original).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>);
<span class="hljs-keyword">const</span> stringAsBytes = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(bytesAsString, <span class="hljs-string">'utf8'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stringAsBytes);
<span class="hljs-comment">// Prints '<Buffer ef bf bd ef bf bd>'.</span></code> <button class="copy-button">copy</button></pre>
<p>The outputs of ciphers, hash functions, signature algorithms, and key
derivation functions are pseudorandom byte sequences and should not be
used as Unicode strings.</p>
</li>
<li>
<p>When strings are obtained from user input, some Unicode characters can be
represented in multiple equivalent ways that result in different byte
sequences. For example, when passing a user passphrase to a key derivation
function, such as PBKDF2 or scrypt, the result of the key derivation function
depends on whether the string uses composed or decomposed characters. Node.js
does not normalize character representations. Developers should consider using
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a> on user inputs before passing them to
cryptographic APIs.</p>
</li>
</ul>
<h4>Legacy streams API (prior to Node.js 0.10)<span><a class="mark" href="#all_crypto_legacy-streams-api-prior-to-nodejs-010" id="all_crypto_legacy-streams-api-prior-to-nodejs-010">#</a></span><a aria-hidden="true" class="legacy" id="crypto_legacy_streams_api_prior_to_node_js_0_10"></a></h4>
<p>The Crypto module was added to Node.js before there was the concept of a
unified Stream API, and before there were <a href="buffer.html"><code>Buffer</code></a> objects for handling
binary data. As such, many <code>crypto</code> classes have methods not
typically found on other Node.js classes that implement the <a href="stream.html">streams</a>
API (e.g. <code>update()</code>, <code>final()</code>, or <code>digest()</code>). Also, many methods accepted
and returned <code>'latin1'</code> encoded strings by default rather than <code>Buffer</code>s. This
default was changed after Node.js v0.8 to use <a href="buffer.html"><code>Buffer</code></a> objects by default
instead.</p>
<h4>Support for weak or compromised algorithms<span><a class="mark" href="#all_crypto_support-for-weak-or-compromised-algorithms" id="all_crypto_support-for-weak-or-compromised-algorithms">#</a></span><a aria-hidden="true" class="legacy" id="crypto_support_for_weak_or_compromised_algorithms"></a></h4>
<p>The <code>node:crypto</code> module still supports some algorithms which are already
compromised and are not recommended for use. The API also allows
the use of ciphers and hashes with a small key size that are too weak for safe
use.</p>
<p>Users should take full responsibility for selecting the crypto
algorithm and key size according to their security requirements.</p>
<p>Based on the recommendations of <a href="https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar2.pdf">NIST SP 800-131A</a>:</p>
<ul>
<li>MD5 and SHA-1 are no longer acceptable where collision resistance is
required such as digital signatures.</li>
<li>The key used with RSA, DSA, and DH algorithms is recommended to have
at least 2048 bits and that of the curve of ECDSA and ECDH at least
224 bits, to be safe to use for several years.</li>
<li>The DH groups of <code>modp1</code>, <code>modp2</code> and <code>modp5</code> have a key size
smaller than 2048 bits and are not recommended.</li>
</ul>
<p>See the reference for other recommendations and details.</p>
<p>Some algorithms that have known weaknesses and are of little relevance in
practice are only available through the <a href="#all_cli_--openssl-legacy-provider">legacy provider</a>, which is not
enabled by default.</p>
<h4>CCM mode<span><a class="mark" href="#all_crypto_ccm-mode" id="all_crypto_ccm-mode">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ccm_mode"></a></h4>
<p>CCM is one of the supported <a href="https://en.wikipedia.org/wiki/Authenticated_encryption">AEAD algorithms</a>. Applications which use this
mode must adhere to certain restrictions when using the cipher API:</p>
<ul>
<li>The authentication tag length must be specified during cipher creation by
setting the <code>authTagLength</code> option and must be one of 4, 6, 8, 10, 12, 14 or
16 bytes.</li>
<li>The length of the initialization vector (nonce) <code>N</code> must be between 7 and 13
bytes (<code>7 ≤ N ≤ 13</code>).</li>
<li>The length of the plaintext is limited to <code>2 ** (8 * (15 - N))</code> bytes.</li>
<li>When decrypting, the authentication tag must be set via <code>setAuthTag()</code> before
calling <code>update()</code>.
Otherwise, decryption will fail and <code>final()</code> will throw an error in
compliance with section 2.6 of <a href="https://www.rfc-editor.org/rfc/rfc3610.txt">RFC 3610</a>.</li>
<li>Using stream methods such as <code>write(data)</code>, <code>end(data)</code> or <code>pipe()</code> in CCM
mode might fail as CCM cannot handle more than one chunk of data per instance.</li>
<li>When passing additional authenticated data (AAD), the length of the actual
message in bytes must be passed to <code>setAAD()</code> via the <code>plaintextLength</code>
option.
Many crypto libraries include the authentication tag in the ciphertext,
which means that they produce ciphertexts of the length
<code>plaintextLength + authTagLength</code>. Node.js does not include the authentication
tag, so the ciphertext length is always <code>plaintextLength</code>.
This is not necessary if no AAD is used.</li>
<li>As CCM processes the whole message at once, <code>update()</code> must be called exactly
once.</li>
<li>Even though calling <code>update()</code> is sufficient to encrypt/decrypt the message,
applications <em>must</em> call <code>final()</code> to compute or verify the
authentication tag.</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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> {
createCipheriv,
createDecipheriv,
randomBytes,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> key = <span class="hljs-string">'keykeykeykeykeykeykeykey'</span>;
<span class="hljs-keyword">const</span> nonce = <span class="hljs-title function_">randomBytes</span>(<span class="hljs-number">12</span>);
<span class="hljs-keyword">const</span> aad = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'0123456789'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(<span class="hljs-string">'aes-192-ccm'</span>, key, nonce, {
<span class="hljs-attr">authTagLength</span>: <span class="hljs-number">16</span>,
});
<span class="hljs-keyword">const</span> plaintext = <span class="hljs-string">'Hello world'</span>;
cipher.<span class="hljs-title function_">setAAD</span>(aad, {
<span class="hljs-attr">plaintextLength</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(plaintext),
});
<span class="hljs-keyword">const</span> ciphertext = cipher.<span class="hljs-title function_">update</span>(plaintext, <span class="hljs-string">'utf8'</span>);
cipher.<span class="hljs-title function_">final</span>();
<span class="hljs-keyword">const</span> tag = cipher.<span class="hljs-title function_">getAuthTag</span>();
<span class="hljs-comment">// Now transmit { ciphertext, nonce, tag }.</span>
<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(<span class="hljs-string">'aes-192-ccm'</span>, key, nonce, {
<span class="hljs-attr">authTagLength</span>: <span class="hljs-number">16</span>,
});
decipher.<span class="hljs-title function_">setAuthTag</span>(tag);
decipher.<span class="hljs-title function_">setAAD</span>(aad, {
<span class="hljs-attr">plaintextLength</span>: ciphertext.<span class="hljs-property">length</span>,
});
<span class="hljs-keyword">const</span> receivedPlaintext = decipher.<span class="hljs-title function_">update</span>(ciphertext, <span class="hljs-literal">null</span>, <span class="hljs-string">'utf8'</span>);
<span class="hljs-keyword">try</span> {
decipher.<span class="hljs-title function_">final</span>();
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Authentication failed!'</span>, { <span class="hljs-attr">cause</span>: err });
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(receivedPlaintext);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> {
createCipheriv,
createDecipheriv,
randomBytes,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> key = <span class="hljs-string">'keykeykeykeykeykeykeykey'</span>;
<span class="hljs-keyword">const</span> nonce = <span class="hljs-title function_">randomBytes</span>(<span class="hljs-number">12</span>);
<span class="hljs-keyword">const</span> aad = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'0123456789'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(<span class="hljs-string">'aes-192-ccm'</span>, key, nonce, {
<span class="hljs-attr">authTagLength</span>: <span class="hljs-number">16</span>,
});
<span class="hljs-keyword">const</span> plaintext = <span class="hljs-string">'Hello world'</span>;
cipher.<span class="hljs-title function_">setAAD</span>(aad, {
<span class="hljs-attr">plaintextLength</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(plaintext),
});
<span class="hljs-keyword">const</span> ciphertext = cipher.<span class="hljs-title function_">update</span>(plaintext, <span class="hljs-string">'utf8'</span>);
cipher.<span class="hljs-title function_">final</span>();
<span class="hljs-keyword">const</span> tag = cipher.<span class="hljs-title function_">getAuthTag</span>();
<span class="hljs-comment">// Now transmit { ciphertext, nonce, tag }.</span>
<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(<span class="hljs-string">'aes-192-ccm'</span>, key, nonce, {
<span class="hljs-attr">authTagLength</span>: <span class="hljs-number">16</span>,
});
decipher.<span class="hljs-title function_">setAuthTag</span>(tag);
decipher.<span class="hljs-title function_">setAAD</span>(aad, {
<span class="hljs-attr">plaintextLength</span>: ciphertext.<span class="hljs-property">length</span>,
});
<span class="hljs-keyword">const</span> receivedPlaintext = decipher.<span class="hljs-title function_">update</span>(ciphertext, <span class="hljs-literal">null</span>, <span class="hljs-string">'utf8'</span>);
<span class="hljs-keyword">try</span> {
decipher.<span class="hljs-title function_">final</span>();
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Authentication failed!'</span>, { <span class="hljs-attr">cause</span>: err });
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(receivedPlaintext);</code><button class="copy-button">copy</button></pre>
<h4>FIPS mode<span><a class="mark" href="#all_crypto_fips-mode" id="all_crypto_fips-mode">#</a></span><a aria-hidden="true" class="legacy" id="crypto_fips_mode"></a></h4>
<p>When using OpenSSL 3, Node.js supports FIPS 140-2 when used with an appropriate
OpenSSL 3 provider, such as the <a href="https://www.openssl.org/docs/man3.0/man7/crypto.html#FIPS-provider">FIPS provider from OpenSSL 3</a> which can be
installed by following the instructions in <a href="https://github.com/openssl/openssl/blob/openssl-3.0/README-FIPS.md">OpenSSL's FIPS README file</a>.</p>
<p>For FIPS support in Node.js you will need:</p>
<ul>
<li>A correctly installed OpenSSL 3 FIPS provider.</li>
<li>An OpenSSL 3 <a href="https://www.openssl.org/docs/man3.0/man5/fips_config.html">FIPS module configuration file</a>.</li>
<li>An OpenSSL 3 configuration file that references the FIPS module
configuration file.</li>
</ul>
<p>Node.js will need to be configured with an OpenSSL configuration file that
points to the FIPS provider. An example configuration file looks like this:</p>
<pre><code class="language-text">nodejs_conf = nodejs_init
.include /<absolute path>/fipsmodule.cnf
[nodejs_init]
providers = provider_sect
[provider_sect]
default = default_sect
# The fips section name should match the section name inside the
# included fipsmodule.cnf.
fips = fips_sect
[default_sect]
activate = 1</code> <button class="copy-button">copy</button></pre>
<p>where <code>fipsmodule.cnf</code> is the FIPS module configuration file generated from the
FIPS provider installation step:</p>
<pre><code class="language-bash">openssl fipsinstall</code> <button class="copy-button">copy</button></pre>
<p>Set the <code>OPENSSL_CONF</code> environment variable to point to
your configuration file and <code>OPENSSL_MODULES</code> to the location of the FIPS
provider dynamic library. e.g.</p>
<pre><code class="language-bash"><span class="hljs-built_in">export</span> OPENSSL_CONF=/<path to configuration file>/nodejs.cnf
<span class="hljs-built_in">export</span> OPENSSL_MODULES=/<path to openssl lib>/ossl-modules</code> <button class="copy-button">copy</button></pre>
<p>FIPS mode can then be enabled in Node.js either by:</p>
<ul>
<li>Starting Node.js with <code>--enable-fips</code> or <code>--force-fips</code> command line flags.</li>
<li>Programmatically calling <code>crypto.setFips(true)</code>.</li>
</ul>
<p>Optionally FIPS mode can be enabled in Node.js via the OpenSSL configuration
file. e.g.</p>
<pre><code class="language-text">nodejs_conf = nodejs_init
.include /<absolute path>/fipsmodule.cnf
[nodejs_init]
providers = provider_sect
alg_section = algorithm_sect
[provider_sect]
default = default_sect
# The fips section name should match the section name inside the
# included fipsmodule.cnf.
fips = fips_sect
[default_sect]
activate = 1
[algorithm_sect]
default_properties = fips=yes</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Crypto constants<span><a class="mark" href="#all_crypto_crypto-constants" id="all_crypto_crypto-constants">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_constants_1"></a></h3>
<p>The following constants exported by <code>crypto.constants</code> apply to various uses of
the <code>node:crypto</code>, <code>node:tls</code>, and <code>node:https</code> modules and are generally
specific to OpenSSL.</p>
<h4>OpenSSL options<span><a class="mark" href="#all_crypto_openssl-options" id="all_crypto_openssl-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_openssl_options"></a></h4>
<p>See the <a href="https://wiki.openssl.org/index.php/List_of_SSL_OP_Flags#Table_of_Options">list of SSL OP Flags</a> for details.</p>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>SSL_OP_ALL</code></td>
<td>Applies multiple bug workarounds within OpenSSL. See
<a href="https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html">https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html</a>
for detail.</td>
</tr>
<tr>
<td><code>SSL_OP_ALLOW_NO_DHE_KEX</code></td>
<td>Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode
for TLS v1.3</td>
</tr>
<tr>
<td><code>SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION</code></td>
<td>Allows legacy insecure renegotiation between OpenSSL and unpatched
clients or servers. See
<a href="https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html">https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html</a>.</td>
</tr>
<tr>
<td><code>SSL_OP_CIPHER_SERVER_PREFERENCE</code></td>
<td>Attempts to use the server's preferences instead of the client's when
selecting a cipher. Behavior depends on protocol version. See
<a href="https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html">https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html</a>.</td>
</tr>
<tr>
<td><code>SSL_OP_CISCO_ANYCONNECT</code></td>
<td>Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER.</td>
</tr>
<tr>
<td><code>SSL_OP_COOKIE_EXCHANGE</code></td>
<td>Instructs OpenSSL to turn on cookie exchange.</td>
</tr>
<tr>
<td><code>SSL_OP_CRYPTOPRO_TLSEXT_BUG</code></td>
<td>Instructs OpenSSL to add server-hello extension from an early version
of the cryptopro draft.</td>
</tr>
<tr>
<td><code>SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS</code></td>
<td>Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability
workaround added in OpenSSL 0.9.6d.</td>
</tr>
<tr>
<td><code>SSL_OP_LEGACY_SERVER_CONNECT</code></td>
<td>Allows initial connection to servers that do not support RI.</td>
</tr>
<tr>
<td><code>SSL_OP_NO_COMPRESSION</code></td>
<td>Instructs OpenSSL to disable support for SSL/TLS compression.</td>
</tr>
<tr>
<td><code>SSL_OP_NO_ENCRYPT_THEN_MAC</code></td>
<td>Instructs OpenSSL to disable encrypt-then-MAC.</td>
</tr>
<tr>
<td><code>SSL_OP_NO_QUERY_MTU</code></td>
<td></td>
</tr>
<tr>
<td><code>SSL_OP_NO_RENEGOTIATION</code></td>
<td>Instructs OpenSSL to disable renegotiation.</td>
</tr>
<tr>
<td><code>SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION</code></td>
<td>Instructs OpenSSL to always start a new session when performing
renegotiation.</td>
</tr>
<tr>
<td><code>SSL_OP_NO_SSLv2</code></td>
<td>Instructs OpenSSL to turn off SSL v2</td>
</tr>
<tr>
<td><code>SSL_OP_NO_SSLv3</code></td>
<td>Instructs OpenSSL to turn off SSL v3</td>
</tr>
<tr>
<td><code>SSL_OP_NO_TICKET</code></td>
<td>Instructs OpenSSL to disable use of RFC4507bis tickets.</td>
</tr>
<tr>
<td><code>SSL_OP_NO_TLSv1</code></td>
<td>Instructs OpenSSL to turn off TLS v1</td>
</tr>
<tr>
<td><code>SSL_OP_NO_TLSv1_1</code></td>
<td>Instructs OpenSSL to turn off TLS v1.1</td>
</tr>
<tr>
<td><code>SSL_OP_NO_TLSv1_2</code></td>
<td>Instructs OpenSSL to turn off TLS v1.2</td>
</tr>
<tr>
<td><code>SSL_OP_NO_TLSv1_3</code></td>
<td>Instructs OpenSSL to turn off TLS v1.3</td>
</tr>
<tr>
<td><code>SSL_OP_PRIORITIZE_CHACHA</code></td>
<td>Instructs OpenSSL server to prioritize ChaCha20-Poly1305
when the client does.
This option has no effect if
<code>SSL_OP_CIPHER_SERVER_PREFERENCE</code>
is not enabled.</td>
</tr>
<tr>
<td><code>SSL_OP_TLS_ROLLBACK_BUG</code></td>
<td>Instructs OpenSSL to disable version rollback attack detection.</td>
</tr>
</tbody></table>
<h4>OpenSSL engine constants<span><a class="mark" href="#all_crypto_openssl-engine-constants" id="all_crypto_openssl-engine-constants">#</a></span><a aria-hidden="true" class="legacy" id="crypto_openssl_engine_constants"></a></h4>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>ENGINE_METHOD_RSA</code></td>
<td>Limit engine usage to RSA</td>
</tr>
<tr>
<td><code>ENGINE_METHOD_DSA</code></td>
<td>Limit engine usage to DSA</td>
</tr>
<tr>
<td><code>ENGINE_METHOD_DH</code></td>
<td>Limit engine usage to DH</td>
</tr>
<tr>
<td><code>ENGINE_METHOD_RAND</code></td>
<td>Limit engine usage to RAND</td>
</tr>
<tr>
<td><code>ENGINE_METHOD_EC</code></td>
<td>Limit engine usage to EC</td>
</tr>
<tr>
<td><code>ENGINE_METHOD_CIPHERS</code></td>
<td>Limit engine usage to CIPHERS</td>
</tr>
<tr>
<td><code>ENGINE_METHOD_DIGESTS</code></td>
<td>Limit engine usage to DIGESTS</td>
</tr>
<tr>
<td><code>ENGINE_METHOD_PKEY_METHS</code></td>
<td>Limit engine usage to PKEY_METHDS</td>
</tr>
<tr>
<td><code>ENGINE_METHOD_PKEY_ASN1_METHS</code></td>
<td>Limit engine usage to PKEY_ASN1_METHS</td>
</tr>
<tr>
<td><code>ENGINE_METHOD_ALL</code></td>
<td></td>
</tr>
<tr>
<td><code>ENGINE_METHOD_NONE</code></td>
<td></td>
</tr>
</tbody></table>
<h4>Other OpenSSL constants<span><a class="mark" href="#all_crypto_other-openssl-constants" id="all_crypto_other-openssl-constants">#</a></span><a aria-hidden="true" class="legacy" id="crypto_other_openssl_constants"></a></h4>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>DH_CHECK_P_NOT_SAFE_PRIME</code></td>
<td></td>
</tr>
<tr>
<td><code>DH_CHECK_P_NOT_PRIME</code></td>
<td></td>
</tr>
<tr>
<td><code>DH_UNABLE_TO_CHECK_GENERATOR</code></td>
<td></td>
</tr>
<tr>
<td><code>DH_NOT_SUITABLE_GENERATOR</code></td>
<td></td>
</tr>
<tr>
<td><code>RSA_PKCS1_PADDING</code></td>
<td></td>
</tr>
<tr>
<td><code>RSA_SSLV23_PADDING</code></td>
<td></td>
</tr>
<tr>
<td><code>RSA_NO_PADDING</code></td>
<td></td>
</tr>
<tr>
<td><code>RSA_PKCS1_OAEP_PADDING</code></td>
<td></td>
</tr>
<tr>
<td><code>RSA_X931_PADDING</code></td>
<td></td>
</tr>
<tr>
<td><code>RSA_PKCS1_PSS_PADDING</code></td>
<td></td>
</tr>
<tr>
<td><code>RSA_PSS_SALTLEN_DIGEST</code></td>
<td>Sets the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to the
digest size when signing or verifying.</td>
</tr>
<tr>
<td><code>RSA_PSS_SALTLEN_MAX_SIGN</code></td>
<td>Sets the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to the
maximum permissible value when signing data.</td>
</tr>
<tr>
<td><code>RSA_PSS_SALTLEN_AUTO</code></td>
<td>Causes the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to be
determined automatically when verifying a signature.</td>
</tr>
<tr>
<td><code>POINT_CONVERSION_COMPRESSED</code></td>
<td></td>
</tr>
<tr>
<td><code>POINT_CONVERSION_UNCOMPRESSED</code></td>
<td></td>
</tr>
<tr>
<td><code>POINT_CONVERSION_HYBRID</code></td>
<td></td>
</tr>
</tbody></table>
<h4>Node.js crypto constants<span><a class="mark" href="#all_crypto_nodejs-crypto-constants" id="all_crypto_nodejs-crypto-constants">#</a></span><a aria-hidden="true" class="legacy" id="crypto_node_js_crypto_constants"></a></h4>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>defaultCoreCipherList</code></td>
<td>Specifies the built-in default cipher list used by Node.js.</td>
</tr>
<tr>
<td><code>defaultCipherList</code></td>
<td>Specifies the active default cipher list used by the current Node.js
process.</td>
</tr>
</tbody></table></section>
</section>
<section><h2>Debugger<span><a class="mark" href="#all_debugger_debugger" id="all_debugger_debugger">#</a></span><a aria-hidden="true" class="legacy" id="debugger_debugger"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Node.js includes a command-line debugging utility. The Node.js debugger client
is not a full-featured debugger, but simple stepping and inspection are
possible.</p>
<p>To use it, start Node.js with the <code>inspect</code> argument followed by the path to the
script to debug.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node inspect myscript.js</span>
< Debugger listening on ws://127.0.0.1:9229/621111f9-ffcb-4e82-b718-48a145fa5db8
< For help, see: https://nodejs.org/en/docs/inspector
<
connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
<
ok
Break on start in myscript.js:2
1 // myscript.js
<span class="hljs-meta prompt_">> </span><span class="language-bash">2 global.x = 5;</span>
3 setTimeout(() => {
4 debugger;
<span class="hljs-meta prompt_">debug></span></code> <button class="copy-button">copy</button></pre>
<p>The debugger automatically breaks on the first executable line. To instead
run until the first breakpoint (specified by a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger"><code>debugger</code></a> statement), set
the <code>NODE_INSPECT_RESUME_ON_START</code> environment variable to <code>1</code>.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">cat</span> myscript.js</span>
// myscript.js
global.x = 5;
setTimeout(() => {
debugger;
console.log('world');
}, 1000);
console.log('hello');
<span class="hljs-meta prompt_">$ </span><span class="language-bash">NODE_INSPECT_RESUME_ON_START=1 node inspect myscript.js</span>
< Debugger listening on ws://127.0.0.1:9229/f1ed133e-7876-495b-83ae-c32c6fc319c2
< For help, see: https://nodejs.org/en/docs/inspector
<
connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
<
< hello
<
break in myscript.js:4
2 global.x = 5;
3 setTimeout(() => {
<span class="hljs-meta prompt_">> </span><span class="language-bash">4 debugger;</span>
5 console.log('world');
6 }, 1000);
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">next</span>
break in myscript.js:5
3 setTimeout(() => {
4 debugger;
<span class="hljs-meta prompt_">> </span><span class="language-bash">5 console.log(<span class="hljs-string">'world'</span>);</span>
6 }, 1000);
7 console.log('hello');
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">repl</span>
Press Ctrl+C to leave debug repl
<span class="hljs-meta prompt_">> </span><span class="language-bash">x</span>
5
<span class="hljs-meta prompt_">> </span><span class="language-bash">2 + 2</span>
4
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">next</span>
< world
<
break in myscript.js:6
4 debugger;
5 console.log('world');
<span class="hljs-meta prompt_">> </span><span class="language-bash">6 }, 1000);</span>
7 console.log('hello');
8
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">.<span class="hljs-built_in">exit</span></span>
<span class="hljs-meta prompt_">$</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>repl</code> command allows code to be evaluated remotely. The <code>next</code> command
steps to the next line. Type <code>help</code> to see what other commands are available.</p>
<p>Pressing <code>enter</code> without typing a command will repeat the previous debugger
command.</p>
<section><h3>Watchers<span><a class="mark" href="#all_debugger_watchers" id="all_debugger_watchers">#</a></span><a aria-hidden="true" class="legacy" id="debugger_watchers"></a></h3>
<p>It is possible to watch expression and variable values while debugging. On
every breakpoint, each expression from the watchers list will be evaluated
in the current context and displayed immediately before the breakpoint's
source code listing.</p>
<p>To begin watching an expression, type <code>watch('my_expression')</code>. The command
<code>watchers</code> will print the active watchers. To remove a watcher, type
<code>unwatch('my_expression')</code>.</p>
</section><section><h3>Command reference<span><a class="mark" href="#all_debugger_command-reference" id="all_debugger_command-reference">#</a></span><a aria-hidden="true" class="legacy" id="debugger_command_reference"></a></h3>
<h4>Stepping<span><a class="mark" href="#all_debugger_stepping" id="all_debugger_stepping">#</a></span><a aria-hidden="true" class="legacy" id="debugger_stepping"></a></h4>
<ul>
<li><code>cont</code>, <code>c</code>: Continue execution</li>
<li><code>next</code>, <code>n</code>: Step next</li>
<li><code>step</code>, <code>s</code>: Step in</li>
<li><code>out</code>, <code>o</code>: Step out</li>
<li><code>pause</code>: Pause running code (like pause button in Developer Tools)</li>
</ul>
<h4>Breakpoints<span><a class="mark" href="#all_debugger_breakpoints" id="all_debugger_breakpoints">#</a></span><a aria-hidden="true" class="legacy" id="debugger_breakpoints"></a></h4>
<ul>
<li><code>setBreakpoint()</code>, <code>sb()</code>: Set breakpoint on current line</li>
<li><code>setBreakpoint(line)</code>, <code>sb(line)</code>: Set breakpoint on specific line</li>
<li><code>setBreakpoint('fn()')</code>, <code>sb(...)</code>: Set breakpoint on a first statement in
function's body</li>
<li><code>setBreakpoint('script.js', 1)</code>, <code>sb(...)</code>: Set breakpoint on first line of
<code>script.js</code></li>
<li><code>setBreakpoint('script.js', 1, 'num < 4')</code>, <code>sb(...)</code>: Set conditional
breakpoint on first line of <code>script.js</code> that only breaks when <code>num < 4</code>
evaluates to <code>true</code></li>
<li><code>clearBreakpoint('script.js', 1)</code>, <code>cb(...)</code>: Clear breakpoint in <code>script.js</code>
on line 1</li>
</ul>
<p>It is also possible to set a breakpoint in a file (module) that
is not loaded yet:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node inspect main.js</span>
< Debugger listening on ws://127.0.0.1:9229/48a5b28a-550c-471b-b5e1-d13dd7165df9
< For help, see: https://nodejs.org/en/docs/inspector
<
connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
<
Break on start in main.js:1
<span class="hljs-meta prompt_">> </span><span class="language-bash">1 const mod = require(<span class="hljs-string">'./mod.js'</span>);</span>
2 mod.hello();
3 mod.hello();
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">setBreakpoint(<span class="hljs-string">'mod.js'</span>, 22)</span>
Warning: script 'mod.js' was not loaded yet.
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">c</span>
break in mod.js:22
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21
<span class="hljs-meta prompt_">></span><span class="language-bash">22 exports.hello = <span class="hljs-function"><span class="hljs-title">function</span></span>() {</span>
23 return 'hello from module';
24 };
<span class="hljs-meta prompt_">debug></span></code> <button class="copy-button">copy</button></pre>
<p>It is also possible to set a conditional breakpoint that only breaks when a
given expression evaluates to <code>true</code>:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node inspect main.js</span>
< Debugger listening on ws://127.0.0.1:9229/ce24daa8-3816-44d4-b8ab-8273c8a66d35
< For help, see: https://nodejs.org/en/docs/inspector
<
connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
Break on start in main.js:7
5 }
6
<span class="hljs-meta prompt_">> </span><span class="language-bash">7 addOne(10);</span>
8 addOne(-1);
9
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">setBreakpoint(<span class="hljs-string">'main.js'</span>, 4, <span class="hljs-string">'num < 0'</span>)</span>
1 'use strict';
2
3 function addOne(num) {
<span class="hljs-meta prompt_">> </span><span class="language-bash">4 <span class="hljs-built_in">return</span> num + 1;</span>
5 }
6
7 addOne(10);
8 addOne(-1);
9
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">cont</span>
break in main.js:4
2
3 function addOne(num) {
<span class="hljs-meta prompt_">> </span><span class="language-bash">4 <span class="hljs-built_in">return</span> num + 1;</span>
5 }
6
<span class="hljs-meta prompt_">debug> </span><span class="language-bash"><span class="hljs-built_in">exec</span>(<span class="hljs-string">'num'</span>)</span>
-1
<span class="hljs-meta prompt_">debug></span></code> <button class="copy-button">copy</button></pre>
<h4>Information<span><a class="mark" href="#all_debugger_information" id="all_debugger_information">#</a></span><a aria-hidden="true" class="legacy" id="debugger_information"></a></h4>
<ul>
<li><code>backtrace</code>, <code>bt</code>: Print backtrace of current execution frame</li>
<li><code>list(5)</code>: List scripts source code with 5 line context (5 lines before and
after)</li>
<li><code>watch(expr)</code>: Add expression to watch list</li>
<li><code>unwatch(expr)</code>: Remove expression from watch list</li>
<li><code>unwatch(index)</code>: Remove expression at specific index from watch list</li>
<li><code>watchers</code>: List all watchers and their values (automatically listed on each
breakpoint)</li>
<li><code>repl</code>: Open debugger's repl for evaluation in debugging script's context</li>
<li><code>exec expr</code>, <code>p expr</code>: Execute an expression in debugging script's context and
print its value</li>
<li><code>profile</code>: Start CPU profiling session</li>
<li><code>profileEnd</code>: Stop current CPU profiling session</li>
<li><code>profiles</code>: List all completed CPU profiling sessions</li>
<li><code>profiles[n].save(filepath = 'node.cpuprofile')</code>: Save CPU profiling session
to disk as JSON</li>
<li><code>takeHeapSnapshot(filepath = 'node.heapsnapshot')</code>: Take a heap snapshot
and save to disk as JSON</li>
</ul>
<h4>Execution control<span><a class="mark" href="#all_debugger_execution-control" id="all_debugger_execution-control">#</a></span><a aria-hidden="true" class="legacy" id="debugger_execution_control"></a></h4>
<ul>
<li><code>run</code>: Run script (automatically runs on debugger's start)</li>
<li><code>restart</code>: Restart script</li>
<li><code>kill</code>: Kill script</li>
</ul>
<h4>Various<span><a class="mark" href="#all_debugger_various" id="all_debugger_various">#</a></span><a aria-hidden="true" class="legacy" id="debugger_various"></a></h4>
<ul>
<li><code>scripts</code>: List all loaded scripts</li>
<li><code>version</code>: Display V8's version</li>
</ul>
</section><section><h3>Advanced usage<span><a class="mark" href="#all_debugger_advanced-usage" id="all_debugger_advanced-usage">#</a></span><a aria-hidden="true" class="legacy" id="debugger_advanced_usage"></a></h3>
<h4>V8 inspector integration for Node.js<span><a class="mark" href="#all_debugger_v8-inspector-integration-for-nodejs" id="all_debugger_v8-inspector-integration-for-nodejs">#</a></span><a aria-hidden="true" class="legacy" id="debugger_v8_inspector_integration_for_node_js"></a></h4>
<p>V8 Inspector integration allows attaching Chrome DevTools to Node.js
instances for debugging and profiling. It uses the
<a href="https://chromedevtools.github.io/devtools-protocol/">Chrome DevTools Protocol</a>.</p>
<p>V8 Inspector can be enabled by passing the <code>--inspect</code> flag when starting a
Node.js application. It is also possible to supply a custom port with that flag,
e.g. <code>--inspect=9222</code> will accept DevTools connections on port 9222.</p>
<p>Using the <code>--inspect</code> flag will execute the code immediately before debugger is connected.
This means that the code will start running before you can start debugging, which might
not be ideal if you want to debug from the very beginning.</p>
<p>In such cases, you have two alternatives:</p>
<ol>
<li><code>--inspect-wait</code> flag: This flag will wait for debugger to be attached before executing the code.
This allows you to start debugging right from the beginning of the execution.</li>
<li><code>--inspect-brk</code> flag: Unlike <code>--inspect</code>, this flag will break on the first line of the code
as soon as debugger is attached. This is useful when you want to debug the code step by step
from the very beginning, without any code execution prior to debugging.</li>
</ol>
<p>So, when deciding between <code>--inspect</code>, <code>--inspect-wait</code>, and <code>--inspect-brk</code>, consider whether you want
the code to start executing immediately, wait for debugger to be attached before execution,
or break on the first line for step-by-step debugging.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --inspect index.js</span>
Debugger listening on ws://127.0.0.1:9229/dc9010dd-f8b8-4ac5-a510-c1a114ec7d29
For help, see: https://nodejs.org/en/docs/inspector</code> <button class="copy-button">copy</button></pre>
<p>(In the example above, the UUID dc9010dd-f8b8-4ac5-a510-c1a114ec7d29
at the end of the URL is generated on the fly, it varies in different
debugging sessions.)</p>
<p>If the Chrome browser is older than 66.0.3345.0,
use <code>inspector.html</code> instead of <code>js_app.html</code> in the above URL.</p>
<p>Chrome DevTools doesn't support debugging <a href="worker_threads.html">worker threads</a> yet.
<a href="https://github.com/GoogleChromeLabs/ndb/">ndb</a> can be used to debug them.</p></section>
</section>
<section><h2>Deprecated APIs<span><a class="mark" href="#all_deprecations_deprecated-apis" id="all_deprecations_deprecated-apis">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_deprecated_apis"></a></h2>
<p>Node.js APIs might be deprecated for any of the following reasons:</p>
<ul>
<li>Use of the API is unsafe.</li>
<li>An improved alternative API is available.</li>
<li>Breaking changes to the API are expected in a future major release.</li>
</ul>
<p>Node.js uses four kinds of deprecations:</p>
<ul>
<li>Documentation-only</li>
<li>Application (non-<code>node_modules</code> code only)</li>
<li>Runtime (all code)</li>
<li>End-of-Life</li>
</ul>
<p>A Documentation-only deprecation is one that is expressed only within the
Node.js API docs. These generate no side-effects while running Node.js.
Some Documentation-only deprecations trigger a runtime warning when launched
with <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a> flag (or its alternative,
<code>NODE_PENDING_DEPRECATION=1</code> environment variable), similarly to Runtime
deprecations below. Documentation-only deprecations that support that flag
are explicitly labeled as such in the
<a href="#all_deprecations_list-of-deprecated-apis">list of Deprecated APIs</a>.</p>
<p>An Application deprecation for only non-<code>node_modules</code> code will, by default,
generate a process warning that will be printed to <code>stderr</code> the first time
the deprecated API is used in code that's not loaded from <code>node_modules</code>.
When the <a href="#all_cli_--throw-deprecation"><code>--throw-deprecation</code></a> command-line flag is used, a Runtime
deprecation will cause an error to be thrown. When
<a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a> is used, warnings will also be emitted for
code loaded from <code>node_modules</code>.</p>
<p>A runtime deprecation for all code is similar to the runtime deprecation
for non-<code>node_modules</code> code, except that it also emits a warning for
code loaded from <code>node_modules</code>.</p>
<p>An End-of-Life deprecation is used when functionality is or will soon be removed
from Node.js.</p>
<section><h3>Revoking deprecations<span><a class="mark" href="#all_deprecations_revoking-deprecations" id="all_deprecations_revoking-deprecations">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_revoking_deprecations"></a></h3>
<p>Occasionally, the deprecation of an API might be reversed. In such situations,
this document will be updated with information relevant to the decision.
However, the deprecation identifier will not be modified.</p>
</section><section><h3>List of deprecated APIs<span><a class="mark" href="#all_deprecations_list-of-deprecated-apis" id="all_deprecations_list-of-deprecated-apis">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_list_of_deprecated_apis"></a></h3>
<h4 id="DEP0001">DEP0001: <code>http.OutgoingMessage.prototype.flush</code><span><a class="mark" href="#all_deprecations_dep0001-httpoutgoingmessageprototypeflush" id="all_deprecations_dep0001-httpoutgoingmessageprototypeflush">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0001_http_outgoingmessage_prototype_flush"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v1.6.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>OutgoingMessage.prototype.flush()</code> has been removed. Use
<code>OutgoingMessage.prototype.flushHeaders()</code> instead.</p>
<h4 id="DEP0002">DEP0002: <code>require('_linklist')</code><span><a class="mark" href="#all_deprecations_dep0002-require_linklist" id="all_deprecations_dep0002-require_linklist">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0002_require_linklist"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>_linklist</code> module is deprecated. Please use a userland alternative.</p>
<h4 id="DEP0003">DEP0003: <code>_writableState.buffer</code><span><a class="mark" href="#all_deprecations_dep0003-_writablestatebuffer" id="all_deprecations_dep0003-_writablestatebuffer">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0003_writablestate_buffer"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>_writableState.buffer</code> has been removed. Use <code>_writableState.getBuffer()</code>
instead.</p>
<h4 id="DEP0004">DEP0004: <code>CryptoStream.prototype.readyState</code><span><a class="mark" href="#all_deprecations_dep0004-cryptostreamprototypereadystate" id="all_deprecations_dep0004-cryptostreamprototypereadystate">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0004_cryptostream_prototype_readystate"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.4.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>CryptoStream.prototype.readyState</code> property was removed.</p>
<h4 id="DEP0005">DEP0005: <code>Buffer()</code> constructor<span><a class="mark" href="#all_deprecations_dep0005-buffer-constructor" id="all_deprecations_dep0005-buffer-constructor">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0005_buffer_constructor"></a></h4>
<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>Runtime deprecation.</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Application (non-<code>node_modules</code> code only)</p>
<p>The <code>Buffer()</code> function and <code>new Buffer()</code> constructor are deprecated due to
API usability issues that can lead to accidental security issues.</p>
<p>As an alternative, use one of the following methods of constructing <code>Buffer</code>
objects:</p>
<ul>
<li><a href="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc(size[, fill[, encoding]])</code></a>: Create a <code>Buffer</code> with
<em>initialized</em> memory.</li>
<li><a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe(size)</code></a>: Create a <code>Buffer</code> with
<em>uninitialized</em> memory.</li>
<li><a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow(size)</code></a>: Create a <code>Buffer</code> with <em>uninitialized</em>
memory.</li>
<li><a href="#all_buffer_static-method-bufferfromarray"><code>Buffer.from(array)</code></a>: Create a <code>Buffer</code> with a copy of <code>array</code></li>
<li><a href="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a> -
Create a <code>Buffer</code> that wraps the given <code>arrayBuffer</code>.</li>
<li><a href="#all_buffer_static-method-bufferfrombuffer"><code>Buffer.from(buffer)</code></a>: Create a <code>Buffer</code> that copies <code>buffer</code>.</li>
<li><a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string[, encoding])</code></a>: Create a <code>Buffer</code>
that copies <code>string</code>.</li>
</ul>
<p>Without <code>--pending-deprecation</code>, runtime warnings occur only for code not in
<code>node_modules</code>. This means there will not be deprecation warnings for
<code>Buffer()</code> usage in dependencies. With <code>--pending-deprecation</code>, a runtime
warning results no matter where the <code>Buffer()</code> usage occurs.</p>
<h4 id="DEP0006">DEP0006: <code>child_process</code> <code>options.customFds</code><span><a class="mark" href="#all_deprecations_dep0006-child_process-optionscustomfds" id="all_deprecations_dep0006-child_process-optionscustomfds">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0006_child_process_options_customfds"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.14</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v0.5.10</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Within the <a href="child_process.html"><code>child_process</code></a> module's <code>spawn()</code>, <code>fork()</code>, and <code>exec()</code>
methods, the <code>options.customFds</code> option is deprecated. The <code>options.stdio</code>
option should be used instead.</p>
<h4 id="DEP0007">DEP0007: Replace <code>cluster</code> <code>worker.suicide</code> with <code>worker.exitedAfterDisconnect</code><span><a class="mark" href="#all_deprecations_dep0007-replace-cluster-workersuicide-with-workerexitedafterdisconnect" id="all_deprecations_dep0007-replace-cluster-workersuicide-with-workerexitedafterdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0007_replace_cluster_worker_suicide_with_worker_exitedafterdisconnect"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>In an earlier version of the Node.js <code>cluster</code>, a boolean property with the name
<code>suicide</code> was added to the <code>Worker</code> object. The intent of this property was to
provide an indication of how and why the <code>Worker</code> instance exited. In Node.js
6.0.0, the old property was deprecated and replaced with a new
<a href="#all_cluster_workerexitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a> property. The old property name did not
precisely describe the actual semantics and was unnecessarily emotion-laden.</p>
<h4 id="DEP0008">DEP0008: <code>require('node:constants')</code><span><a class="mark" href="#all_deprecations_dep0008-requirenodeconstants" id="all_deprecations_dep0008-requirenodeconstants">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0008_require_node_constants"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>node:constants</code> module is deprecated. When requiring access to constants
relevant to specific Node.js builtin modules, developers should instead refer
to the <code>constants</code> property exposed by the relevant module. For instance,
<code>require('node:fs').constants</code> and <code>require('node:os').constants</code>.</p>
<h4 id="DEP0009">DEP0009: <code>crypto.pbkdf2</code> without digest<span><a class="mark" href="#all_deprecations_dep0009-cryptopbkdf2-without-digest" id="all_deprecations_dep0009-cryptopbkdf2-without-digest">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0009_crypto_pbkdf2_without_digest"></a></h4>
<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>End-of-Life (for <code>digest === null</code>).</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation (for <code>digest === null</code>).</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>End-of-Life (for <code>digest === undefined</code>).</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Runtime deprecation (for <code>digest === undefined</code>).</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Use of the <a href="#all_crypto_cryptopbkdf2password-salt-iterations-keylen-digest-callback"><code>crypto.pbkdf2()</code></a> API without specifying a digest was deprecated
in Node.js 6.0 because the method defaulted to using the non-recommended
<code>'SHA1'</code> digest. Previously, a deprecation warning was printed. Starting in
Node.js 8.0.0, calling <code>crypto.pbkdf2()</code> or <code>crypto.pbkdf2Sync()</code> with
<code>digest</code> set to <code>undefined</code> will throw a <code>TypeError</code>.</p>
<p>Beginning in Node.js v11.0.0, calling these functions with <code>digest</code> set to
<code>null</code> would print a deprecation warning to align with the behavior when <code>digest</code>
is <code>undefined</code>.</p>
<p>Now, however, passing either <code>undefined</code> or <code>null</code> will throw a <code>TypeError</code>.</p>
<h4 id="DEP0010">DEP0010: <code>crypto.createCredentials</code><span><a class="mark" href="#all_deprecations_dep0010-cryptocreatecredentials" id="all_deprecations_dep0010-cryptocreatecredentials">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0010_crypto_createcredentials"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>crypto.createCredentials()</code> API was removed. Please use
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> instead.</p>
<h4 id="DEP0011">DEP0011: <code>crypto.Credentials</code><span><a class="mark" href="#all_deprecations_dep0011-cryptocredentials" id="all_deprecations_dep0011-cryptocredentials">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0011_crypto_credentials"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>crypto.Credentials</code> class was removed. Please use <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.SecureContext</code></a>
instead.</p>
<h4 id="DEP0012">DEP0012: <code>Domain.dispose</code><span><a class="mark" href="#all_deprecations_dep0012-domaindispose" id="all_deprecations_dep0012-domaindispose">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0012_domain_dispose"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.7</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>Domain.dispose()</code> has been removed. Recover from failed I/O actions
explicitly via error event handlers set on the domain instead.</p>
<h4 id="DEP0013">DEP0013: <code>fs</code> asynchronous function without callback<span><a class="mark" href="#all_deprecations_dep0013-fs-asynchronous-function-without-callback" id="all_deprecations_dep0013-fs-asynchronous-function-without-callback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0013_fs_asynchronous_function_without_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>v10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Calling an asynchronous function without a callback throws a <code>TypeError</code>
in Node.js 10.0.0 onwards. See <a href="https://github.com/nodejs/node/pull/12562">https://github.com/nodejs/node/pull/12562</a>.</p>
<h4 id="DEP0014">DEP0014: <code>fs.read</code> legacy String interface<span><a class="mark" href="#all_deprecations_dep0014-fsread-legacy-string-interface" id="all_deprecations_dep0014-fsread-legacy-string-interface">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0014_fs_read_legacy_string_interface"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.1.96</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <a href="#all_fs_fsreadfd-buffer-offset-length-position-callback"><code>fs.read()</code></a> legacy <code>String</code> interface is deprecated. Use the <code>Buffer</code>
API as mentioned in the documentation instead.</p>
<h4 id="DEP0015">DEP0015: <code>fs.readSync</code> legacy String interface<span><a class="mark" href="#all_deprecations_dep0015-fsreadsync-legacy-string-interface" id="all_deprecations_dep0015-fsreadsync-legacy-string-interface">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0015_fs_readsync_legacy_string_interface"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.1.96</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <a href="#all_fs_fsreadsyncfd-buffer-offset-length-position"><code>fs.readSync()</code></a> legacy <code>String</code> interface is deprecated. Use the
<code>Buffer</code> API as mentioned in the documentation instead.</p>
<h4 id="DEP0016">DEP0016: <code>GLOBAL</code>/<code>root</code><span><a class="mark" href="#all_deprecations_dep0016-globalroot" id="all_deprecations_dep0016-globalroot">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0016_global_root"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>GLOBAL</code> and <code>root</code> aliases for the <code>global</code> property were deprecated
in Node.js 6.0.0 and have since been removed.</p>
<h4 id="DEP0017">DEP0017: <code>Intl.v8BreakIterator</code><span><a class="mark" href="#all_deprecations_dep0017-intlv8breakiterator" id="all_deprecations_dep0017-intlv8breakiterator">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0017_intl_v8breakiterator"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>Intl.v8BreakIterator</code> was a non-standard extension and has been removed.
See <a href="https://github.com/tc39/proposal-intl-segmenter"><code>Intl.Segmenter</code></a>.</p>
<h4 id="DEP0018">DEP0018: Unhandled promise rejections<span><a class="mark" href="#all_deprecations_dep0018-unhandled-promise-rejections" id="all_deprecations_dep0018-unhandled-promise-rejections">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0018_unhandled_promise_rejections"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Unhandled promise rejections are deprecated. By default, promise rejections
that are not handled terminate the Node.js process with a non-zero exit
code. To change the way Node.js treats unhandled rejections, use the
<a href="#all_cli_--unhandled-rejectionsmode"><code>--unhandled-rejections</code></a> command-line option.</p>
<h4 id="DEP0019">DEP0019: <code>require('.')</code> resolved outside directory<span><a class="mark" href="#all_deprecations_dep0019-require-resolved-outside-directory" id="all_deprecations_dep0019-require-resolved-outside-directory">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0019_require_resolved_outside_directory"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Removed functionality.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v1.8.1</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>In certain cases, <code>require('.')</code> could resolve outside the package directory.
This behavior has been removed.</p>
<h4 id="DEP0020">DEP0020: <code>Server.connections</code><span><a class="mark" href="#all_deprecations_dep0020-serverconnections" id="all_deprecations_dep0020-serverconnections">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0020_server_connections"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Server.connections has been removed.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.9.7</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>Server.connections</code> property was deprecated in Node.js v0.9.7 and has
been removed. Please use the <a href="#all_net_servergetconnectionscallback"><code>Server.getConnections()</code></a> method instead.</p>
<h4 id="DEP0021">DEP0021: <code>Server.listenFD</code><span><a class="mark" href="#all_deprecations_dep0021-serverlistenfd" id="all_deprecations_dep0021-serverlistenfd">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0021_server_listenfd"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.7.12</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>Server.listenFD()</code> method was deprecated and removed. Please use
<a href="#all_net_serverlistenhandle-backlog-callback"><code>Server.listen({fd: <number>})</code></a> instead.</p>
<h4 id="DEP0022">DEP0022: <code>os.tmpDir()</code><span><a class="mark" href="#all_deprecations_dep0022-ostmpdir" id="all_deprecations_dep0022-ostmpdir">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0022_os_tmpdir"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>os.tmpDir()</code> API was deprecated in Node.js 7.0.0 and has since been
removed. Please use <a href="#all_os_ostmpdir"><code>os.tmpdir()</code></a> instead.</p>
<h4 id="DEP0023">DEP0023: <code>os.getNetworkInterfaces()</code><span><a class="mark" href="#all_deprecations_dep0023-osgetnetworkinterfaces" id="all_deprecations_dep0023-osgetnetworkinterfaces">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0023_os_getnetworkinterfaces"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>os.getNetworkInterfaces()</code> method is deprecated. Please use the
<a href="#all_os_osnetworkinterfaces"><code>os.networkInterfaces()</code></a> method instead.</p>
<h4 id="DEP0024">DEP0024: <code>REPLServer.prototype.convertToContext()</code><span><a class="mark" href="#all_deprecations_dep0024-replserverprototypeconverttocontext" id="all_deprecations_dep0024-replserverprototypeconverttocontext">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0024_replserver_prototype_converttocontext"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>REPLServer.prototype.convertToContext()</code> API has been removed.</p>
<h4 id="DEP0025">DEP0025: <code>require('node:sys')</code><span><a class="mark" href="#all_deprecations_dep0025-requirenodesys" id="all_deprecations_dep0025-requirenodesys">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0025_require_node_sys"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v1.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>node:sys</code> module is deprecated. Please use the <a href="util.html"><code>util</code></a> module instead.</p>
<h4 id="DEP0026">DEP0026: <code>util.print()</code><span><a class="mark" href="#all_deprecations_dep0026-utilprint" id="all_deprecations_dep0026-utilprint">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0026_util_print"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>util.print()</code> has been removed. Please use <a href="#all_console_consolelogdata-args"><code>console.log()</code></a> instead.</p>
<h4 id="DEP0027">DEP0027: <code>util.puts()</code><span><a class="mark" href="#all_deprecations_dep0027-utilputs" id="all_deprecations_dep0027-utilputs">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0027_util_puts"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>util.puts()</code> has been removed. Please use <a href="#all_console_consolelogdata-args"><code>console.log()</code></a> instead.</p>
<h4 id="DEP0028">DEP0028: <code>util.debug()</code><span><a class="mark" href="#all_deprecations_dep0028-utildebug" id="all_deprecations_dep0028-utildebug">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0028_util_debug"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>util.debug()</code> has been removed. Please use <a href="#all_console_consoleerrordata-args"><code>console.error()</code></a> instead.</p>
<h4 id="DEP0029">DEP0029: <code>util.error()</code><span><a class="mark" href="#all_deprecations_dep0029-utilerror" id="all_deprecations_dep0029-utilerror">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0029_util_error"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>util.error()</code> has been removed. Please use <a href="#all_console_consoleerrordata-args"><code>console.error()</code></a> instead.</p>
<h4 id="DEP0030">DEP0030: <code>SlowBuffer</code><span><a class="mark" href="#all_deprecations_dep0030-slowbuffer" id="all_deprecations_dep0030-slowbuffer">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0030_slowbuffer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_buffer_class-slowbuffer"><code>SlowBuffer</code></a> class is deprecated. Please use
<a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow(size)</code></a> instead.</p>
<h4 id="DEP0031">DEP0031: <code>ecdh.setPublicKey()</code><span><a class="mark" href="#all_deprecations_dep0031-ecdhsetpublickey" id="all_deprecations_dep0031-ecdhsetpublickey">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0031_ecdh_setpublickey"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v5.2.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_crypto_ecdhsetpublickeypublickey-encoding"><code>ecdh.setPublicKey()</code></a> method is now deprecated as its inclusion in the
API is not useful.</p>
<h4 id="DEP0032">DEP0032: <code>node:domain</code> module<span><a class="mark" href="#all_deprecations_dep0032-nodedomain-module" id="all_deprecations_dep0032-nodedomain-module">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0032_node_domain_module"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v1.4.2</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="domain.html"><code>domain</code></a> module is deprecated and should not be used.</p>
<h4 id="DEP0033">DEP0033: <code>EventEmitter.listenerCount()</code><span><a class="mark" href="#all_deprecations_dep0033-eventemitterlistenercount" id="all_deprecations_dep0033-eventemitterlistenercount">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0033_eventemitter_listenercount"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.2.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_events_eventslistenercountemitter-eventname"><code>events.listenerCount(emitter, eventName)</code></a> API is
deprecated. Please use <a href="#all_events_emitterlistenercounteventname-listener"><code>emitter.listenerCount(eventName)</code></a> instead.</p>
<h4 id="DEP0034">DEP0034: <code>fs.exists(path, callback)</code><span><a class="mark" href="#all_deprecations_dep0034-fsexistspath-callback" id="all_deprecations_dep0034-fsexistspath-callback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0034_fs_exists_path_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>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v1.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_fs_fsexistspath-callback"><code>fs.exists(path, callback)</code></a> API is deprecated. Please use
<a href="#all_fs_fsstatpath-options-callback"><code>fs.stat()</code></a> or <a href="#all_fs_fsaccesspath-mode-callback"><code>fs.access()</code></a> instead.</p>
<h4 id="DEP0035">DEP0035: <code>fs.lchmod(path, mode, callback)</code><span><a class="mark" href="#all_deprecations_dep0035-fslchmodpath-mode-callback" id="all_deprecations_dep0035-fslchmodpath-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0035_fs_lchmod_path_mode_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>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_fs_fslchmodpath-mode-callback"><code>fs.lchmod(path, mode, callback)</code></a> API is deprecated.</p>
<h4 id="DEP0036">DEP0036: <code>fs.lchmodSync(path, mode)</code><span><a class="mark" href="#all_deprecations_dep0036-fslchmodsyncpath-mode" id="all_deprecations_dep0036-fslchmodsyncpath-mode">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0036_fs_lchmodsync_path_mode"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_fs_fslchmodsyncpath-mode"><code>fs.lchmodSync(path, mode)</code></a> API is deprecated.</p>
<h4 id="DEP0037">DEP0037: <code>fs.lchown(path, uid, gid, callback)</code><span><a class="mark" href="#all_deprecations_dep0037-fslchownpath-uid-gid-callback" id="all_deprecations_dep0037-fslchownpath-uid-gid-callback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0037_fs_lchown_path_uid_gid_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>v10.6.0</td>
<td><p>Deprecation revoked.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Deprecation revoked</p>
<p>The <a href="#all_fs_fslchownpath-uid-gid-callback"><code>fs.lchown(path, uid, gid, callback)</code></a> API was deprecated. The
deprecation was revoked because the requisite supporting APIs were added in
libuv.</p>
<h4 id="DEP0038">DEP0038: <code>fs.lchownSync(path, uid, gid)</code><span><a class="mark" href="#all_deprecations_dep0038-fslchownsyncpath-uid-gid" id="all_deprecations_dep0038-fslchownsyncpath-uid-gid">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0038_fs_lchownsync_path_uid_gid"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.6.0</td>
<td><p>Deprecation revoked.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Deprecation revoked</p>
<p>The <a href="#all_fs_fslchownsyncpath-uid-gid"><code>fs.lchownSync(path, uid, gid)</code></a> API was deprecated. The deprecation was
revoked because the requisite supporting APIs were added in libuv.</p>
<h4 id="DEP0039">DEP0039: <code>require.extensions</code><span><a class="mark" href="#all_deprecations_dep0039-requireextensions" id="all_deprecations_dep0039-requireextensions">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0039_require_extensions"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.10.6</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_modules_requireextensions"><code>require.extensions</code></a> property is deprecated.</p>
<h4 id="DEP0040">DEP0040: <code>node:punycode</code> module<span><a class="mark" href="#all_deprecations_dep0040-nodepunycode-module" id="all_deprecations_dep0040-nodepunycode-module">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0040_node_punycode_module"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.6.0</td>
<td><p>Added support for <code>--pending-deprecation</code>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p>The <a href="punycode.html"><code>punycode</code></a> module is deprecated. Please use a userland alternative
instead.</p>
<h4 id="DEP0041">DEP0041: <code>NODE_REPL_HISTORY_FILE</code> environment variable<span><a class="mark" href="#all_deprecations_dep0041-node_repl_history_file-environment-variable" id="all_deprecations_dep0041-node_repl_history_file-environment-variable">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0041_node_repl_history_file_environment_variable"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>NODE_REPL_HISTORY_FILE</code> environment variable was removed. Please use
<code>NODE_REPL_HISTORY</code> instead.</p>
<h4 id="DEP0042">DEP0042: <code>tls.CryptoStream</code><span><a class="mark" href="#all_deprecations_dep0042-tlscryptostream" id="all_deprecations_dep0042-tlscryptostream">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0042_tls_cryptostream"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <a href="#all_tls_class-tlscryptostream"><code>tls.CryptoStream</code></a> class was removed. Please use
<a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a> instead.</p>
<h4 id="DEP0043">DEP0043: <code>tls.SecurePair</code><span><a class="mark" href="#all_deprecations_dep0043-tlssecurepair" id="all_deprecations_dep0043-tlssecurepair">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0043_tls_securepair"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p>Deprecation revoked.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_tls_class-tlssecurepair"><code>tls.SecurePair</code></a> class is deprecated. Please use
<a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a> instead.</p>
<h4 id="DEP0044">DEP0044: <code>util.isArray()</code><span><a class="mark" href="#all_deprecations_dep0044-utilisarray" id="all_deprecations_dep0044-utilisarray">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0044_util_isarray"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisarrayobject"><code>util.isArray()</code></a> API is deprecated. Please use <code>Array.isArray()</code>
instead.</p>
<h4 id="DEP0045">DEP0045: <code>util.isBoolean()</code><span><a class="mark" href="#all_deprecations_dep0045-utilisboolean" id="all_deprecations_dep0045-utilisboolean">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0045_util_isboolean"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisbooleanobject"><code>util.isBoolean()</code></a> API is deprecated.</p>
<h4 id="DEP0046">DEP0046: <code>util.isBuffer()</code><span><a class="mark" href="#all_deprecations_dep0046-utilisbuffer" id="all_deprecations_dep0046-utilisbuffer">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0046_util_isbuffer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisbufferobject"><code>util.isBuffer()</code></a> API is deprecated. Please use
<a href="#all_buffer_static-method-bufferisbufferobj"><code>Buffer.isBuffer()</code></a> instead.</p>
<h4 id="DEP0047">DEP0047: <code>util.isDate()</code><span><a class="mark" href="#all_deprecations_dep0047-utilisdate" id="all_deprecations_dep0047-utilisdate">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0047_util_isdate"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisdateobject"><code>util.isDate()</code></a> API is deprecated.</p>
<h4 id="DEP0048">DEP0048: <code>util.isError()</code><span><a class="mark" href="#all_deprecations_dep0048-utiliserror" id="all_deprecations_dep0048-utiliserror">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0048_util_iserror"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utiliserrorobject"><code>util.isError()</code></a> API is deprecated.</p>
<h4 id="DEP0049">DEP0049: <code>util.isFunction()</code><span><a class="mark" href="#all_deprecations_dep0049-utilisfunction" id="all_deprecations_dep0049-utilisfunction">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0049_util_isfunction"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisfunctionobject"><code>util.isFunction()</code></a> API is deprecated.</p>
<h4 id="DEP0050">DEP0050: <code>util.isNull()</code><span><a class="mark" href="#all_deprecations_dep0050-utilisnull" id="all_deprecations_dep0050-utilisnull">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0050_util_isnull"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisnullobject"><code>util.isNull()</code></a> API is deprecated.</p>
<h4 id="DEP0051">DEP0051: <code>util.isNullOrUndefined()</code><span><a class="mark" href="#all_deprecations_dep0051-utilisnullorundefined" id="all_deprecations_dep0051-utilisnullorundefined">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0051_util_isnullorundefined"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisnullorundefinedobject"><code>util.isNullOrUndefined()</code></a> API is deprecated.</p>
<h4 id="DEP0052">DEP0052: <code>util.isNumber()</code><span><a class="mark" href="#all_deprecations_dep0052-utilisnumber" id="all_deprecations_dep0052-utilisnumber">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0052_util_isnumber"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisnumberobject"><code>util.isNumber()</code></a> API is deprecated.</p>
<h4 id="DEP0053">DEP0053: <code>util.isObject()</code><span><a class="mark" href="#all_deprecations_dep0053-utilisobject" id="all_deprecations_dep0053-utilisobject">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0053_util_isobject"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisobjectobject"><code>util.isObject()</code></a> API is deprecated.</p>
<h4 id="DEP0054">DEP0054: <code>util.isPrimitive()</code><span><a class="mark" href="#all_deprecations_dep0054-utilisprimitive" id="all_deprecations_dep0054-utilisprimitive">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0054_util_isprimitive"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisprimitiveobject"><code>util.isPrimitive()</code></a> API is deprecated.</p>
<h4 id="DEP0055">DEP0055: <code>util.isRegExp()</code><span><a class="mark" href="#all_deprecations_dep0055-utilisregexp" id="all_deprecations_dep0055-utilisregexp">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0055_util_isregexp"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisregexpobject"><code>util.isRegExp()</code></a> API is deprecated.</p>
<h4 id="DEP0056">DEP0056: <code>util.isString()</code><span><a class="mark" href="#all_deprecations_dep0056-utilisstring" id="all_deprecations_dep0056-utilisstring">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0056_util_isstring"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisstringobject"><code>util.isString()</code></a> API is deprecated.</p>
<h4 id="DEP0057">DEP0057: <code>util.isSymbol()</code><span><a class="mark" href="#all_deprecations_dep0057-utilissymbol" id="all_deprecations_dep0057-utilissymbol">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0057_util_issymbol"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilissymbolobject"><code>util.isSymbol()</code></a> API is deprecated.</p>
<h4 id="DEP0058">DEP0058: <code>util.isUndefined()</code><span><a class="mark" href="#all_deprecations_dep0058-utilisundefined" id="all_deprecations_dep0058-utilisundefined">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0058_util_isundefined"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisundefinedobject"><code>util.isUndefined()</code></a> API is deprecated.</p>
<h4 id="DEP0059">DEP0059: <code>util.log()</code><span><a class="mark" href="#all_deprecations_dep0059-utillog" id="all_deprecations_dep0059-utillog">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0059_util_log"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utillogstring"><code>util.log()</code></a> API is deprecated.</p>
<h4 id="DEP0060">DEP0060: <code>util._extend()</code><span><a class="mark" href="#all_deprecations_dep0060-util_extend" id="all_deprecations_dep0060-util_extend">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0060_util_extend"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_util_extendtarget-source"><code>util._extend()</code></a> API is deprecated.</p>
<h4 id="DEP0061">DEP0061: <code>fs.SyncWriteStream</code><span><a class="mark" href="#all_deprecations_dep0061-fssyncwritestream" id="all_deprecations_dep0061-fssyncwritestream">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0061_fs_syncwritestream"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>fs.SyncWriteStream</code> class was never intended to be a publicly accessible
API and has been removed. No alternative API is available. Please use a userland
alternative.</p>
<h4 id="DEP0062">DEP0062: <code>node --debug</code><span><a class="mark" href="#all_deprecations_dep0062-node---debug" id="all_deprecations_dep0062-node---debug">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0062_node_debug"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>--debug</code> activates the legacy V8 debugger interface, which was removed as
of V8 5.8. It is replaced by Inspector which is activated with <code>--inspect</code>
instead.</p>
<h4 id="DEP0063">DEP0063: <code>ServerResponse.prototype.writeHeader()</code><span><a class="mark" href="#all_deprecations_dep0063-serverresponseprototypewriteheader" id="all_deprecations_dep0063-serverresponseprototypewriteheader">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0063_serverresponse_prototype_writeheader"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>node:http</code> module <code>ServerResponse.prototype.writeHeader()</code> API is
deprecated. Please use <code>ServerResponse.prototype.writeHead()</code> instead.</p>
<p>The <code>ServerResponse.prototype.writeHeader()</code> method was never documented as an
officially supported API.</p>
<h4 id="DEP0064">DEP0064: <code>tls.createSecurePair()</code><span><a class="mark" href="#all_deprecations_dep0064-tlscreatesecurepair" id="all_deprecations_dep0064-tlscreatesecurepair">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0064_tls_createsecurepair"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p>Deprecation revoked.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>tls.createSecurePair()</code> API was deprecated in documentation in Node.js
0.11.3. Users should use <code>tls.Socket</code> instead.</p>
<h4 id="DEP0065">DEP0065: <code>repl.REPL_MODE_MAGIC</code> and <code>NODE_REPL_MODE=magic</code><span><a class="mark" href="#all_deprecations_dep0065-replrepl_mode_magic-and-node_repl_modemagic" id="all_deprecations_dep0065-replrepl_mode_magic-and-node_repl_modemagic">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0065_repl_repl_mode_magic_and_node_repl_mode_magic"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>node:repl</code> module's <code>REPL_MODE_MAGIC</code> constant, used for <code>replMode</code> option,
has been removed. Its behavior has been functionally identical to that of
<code>REPL_MODE_SLOPPY</code> since Node.js 6.0.0, when V8 5.0 was imported. Please use
<code>REPL_MODE_SLOPPY</code> instead.</p>
<p>The <code>NODE_REPL_MODE</code> environment variable is used to set the underlying
<code>replMode</code> of an interactive <code>node</code> session. Its value, <code>magic</code>, is also
removed. Please use <code>sloppy</code> instead.</p>
<h4 id="DEP0066">DEP0066: <code>OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames</code><span><a class="mark" href="#all_deprecations_dep0066-outgoingmessageprototype_headers-outgoingmessageprototype_headernames" id="all_deprecations_dep0066-outgoingmessageprototype_headers-outgoingmessageprototype_headernames">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0066_outgoingmessage_prototype_headers_outgoingmessage_prototype_headernames"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>node:http</code> module <code>OutgoingMessage.prototype._headers</code> and
<code>OutgoingMessage.prototype._headerNames</code> properties are deprecated. Use one of
the public methods (e.g. <code>OutgoingMessage.prototype.getHeader()</code>,
<code>OutgoingMessage.prototype.getHeaders()</code>,
<code>OutgoingMessage.prototype.getHeaderNames()</code>,
<code>OutgoingMessage.prototype.getRawHeaderNames()</code>,
<code>OutgoingMessage.prototype.hasHeader()</code>,
<code>OutgoingMessage.prototype.removeHeader()</code>,
<code>OutgoingMessage.prototype.setHeader()</code>) for working with outgoing headers.</p>
<p>The <code>OutgoingMessage.prototype._headers</code> and
<code>OutgoingMessage.prototype._headerNames</code> properties were never documented as
officially supported properties.</p>
<h4 id="DEP0067">DEP0067: <code>OutgoingMessage.prototype._renderHeaders</code><span><a class="mark" href="#all_deprecations_dep0067-outgoingmessageprototype_renderheaders" id="all_deprecations_dep0067-outgoingmessageprototype_renderheaders">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0067_outgoingmessage_prototype_renderheaders"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>node:http</code> module <code>OutgoingMessage.prototype._renderHeaders()</code> API is
deprecated.</p>
<p>The <code>OutgoingMessage.prototype._renderHeaders</code> property was never documented as
an officially supported API.</p>
<h4 id="DEP0068">DEP0068: <code>node debug</code><span><a class="mark" href="#all_deprecations_dep0068-node-debug" id="all_deprecations_dep0068-node-debug">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0068_node_debug"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The legacy <code>node debug</code> command was removed.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>node debug</code> corresponds to the legacy CLI debugger which has been replaced with
a V8-inspector based CLI debugger available through <code>node inspect</code>.</p>
<h4 id="DEP0069">DEP0069: <code>vm.runInDebugContext(string)</code><span><a class="mark" href="#all_deprecations_dep0069-vmrunindebugcontextstring" id="all_deprecations_dep0069-vmrunindebugcontextstring">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0069_vm_runindebugcontext_string"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>DebugContext has been removed in V8 and is not available in Node.js 10+.</p>
<p>DebugContext was an experimental API.</p>
<h4 id="DEP0070">DEP0070: <code>async_hooks.currentId()</code><span><a class="mark" href="#all_deprecations_dep0070-async_hookscurrentid" id="all_deprecations_dep0070-async_hookscurrentid">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0070_async_hooks_currentid"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.2.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>async_hooks.currentId()</code> was renamed to <code>async_hooks.executionAsyncId()</code> for
clarity.</p>
<p>This change was made while <code>async_hooks</code> was an experimental API.</p>
<h4 id="DEP0071">DEP0071: <code>async_hooks.triggerId()</code><span><a class="mark" href="#all_deprecations_dep0071-async_hookstriggerid" id="all_deprecations_dep0071-async_hookstriggerid">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0071_async_hooks_triggerid"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.2.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>async_hooks.triggerId()</code> was renamed to <code>async_hooks.triggerAsyncId()</code> for
clarity.</p>
<p>This change was made while <code>async_hooks</code> was an experimental API.</p>
<h4 id="DEP0072">DEP0072: <code>async_hooks.AsyncResource.triggerId()</code><span><a class="mark" href="#all_deprecations_dep0072-async_hooksasyncresourcetriggerid" id="all_deprecations_dep0072-async_hooksasyncresourcetriggerid">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0072_async_hooks_asyncresource_triggerid"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.2.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>async_hooks.AsyncResource.triggerId()</code> was renamed to
<code>async_hooks.AsyncResource.triggerAsyncId()</code> for clarity.</p>
<p>This change was made while <code>async_hooks</code> was an experimental API.</p>
<h4 id="DEP0073">DEP0073: Several internal properties of <code>net.Server</code><span><a class="mark" href="#all_deprecations_dep0073-several-internal-properties-of-netserver" id="all_deprecations_dep0073-several-internal-properties-of-netserver">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0073_several_internal_properties_of_net_server"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Accessing several internal, undocumented properties of <code>net.Server</code> instances
with inappropriate names is deprecated.</p>
<p>As the original API was undocumented and not generally useful for non-internal
code, no replacement API is provided.</p>
<h4 id="DEP0074">DEP0074: <code>REPLServer.bufferedCommand</code><span><a class="mark" href="#all_deprecations_dep0074-replserverbufferedcommand" id="all_deprecations_dep0074-replserverbufferedcommand">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0074_replserver_bufferedcommand"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>REPLServer.bufferedCommand</code> property was deprecated in favor of
<a href="#all_repl_replserverclearbufferedcommand"><code>REPLServer.clearBufferedCommand()</code></a>.</p>
<h4 id="DEP0075">DEP0075: <code>REPLServer.parseREPLKeyword()</code><span><a class="mark" href="#all_deprecations_dep0075-replserverparsereplkeyword" id="all_deprecations_dep0075-replserverparsereplkeyword">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0075_replserver_parsereplkeyword"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>REPLServer.parseREPLKeyword()</code> was removed from userland visibility.</p>
<h4 id="DEP0076">DEP0076: <code>tls.parseCertString()</code><span><a class="mark" href="#all_deprecations_dep0076-tlsparsecertstring" id="all_deprecations_dep0076-tlsparsecertstring">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0076_tls_parsecertstring"></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</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v8.6.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>tls.parseCertString()</code> was a trivial parsing helper that was made public by
mistake. While it was supposed to parse certificate subject and issuer strings,
it never handled multi-value Relative Distinguished Names correctly.</p>
<p>Earlier versions of this document suggested using <code>querystring.parse()</code> as an
alternative to <code>tls.parseCertString()</code>. However, <code>querystring.parse()</code> also does
not handle all certificate subjects correctly and should not be used.</p>
<h4 id="DEP0077">DEP0077: <code>Module._debug()</code><span><a class="mark" href="#all_deprecations_dep0077-module_debug" id="all_deprecations_dep0077-module_debug">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0077_module_debug"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>Module._debug()</code> is deprecated.</p>
<p>The <code>Module._debug()</code> function was never documented as an officially
supported API.</p>
<h4 id="DEP0078">DEP0078: <code>REPLServer.turnOffEditorMode()</code><span><a class="mark" href="#all_deprecations_dep0078-replserverturnoffeditormode" id="all_deprecations_dep0078-replserverturnoffeditormode">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0078_replserver_turnoffeditormode"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>REPLServer.turnOffEditorMode()</code> was removed from userland visibility.</p>
<h4 id="DEP0079">DEP0079: Custom inspection function on objects via <code>.inspect()</code><span><a class="mark" href="#all_deprecations_dep0079-custom-inspection-function-on-objects-via-inspect" id="all_deprecations_dep0079-custom-inspection-function-on-objects-via-inspect">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0079_custom_inspection_function_on_objects_via_inspect"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v8.7.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Using a property named <code>inspect</code> on an object to specify a custom inspection
function for <a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> is deprecated. Use <a href="#all_util_utilinspectcustom"><code>util.inspect.custom</code></a>
instead. For backward compatibility with Node.js prior to version 6.4.0, both
can be specified.</p>
<h4 id="DEP0080">DEP0080: <code>path._makeLong()</code><span><a class="mark" href="#all_deprecations_dep0080-path_makelong" id="all_deprecations_dep0080-path_makelong">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0080_path_makelong"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The internal <code>path._makeLong()</code> was not intended for public use. However,
userland modules have found it useful. The internal API is deprecated
and replaced with an identical, public <code>path.toNamespacedPath()</code> method.</p>
<h4 id="DEP0081">DEP0081: <code>fs.truncate()</code> using a file descriptor<span><a class="mark" href="#all_deprecations_dep0081-fstruncate-using-a-file-descriptor" id="all_deprecations_dep0081-fstruncate-using-a-file-descriptor">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0081_fs_truncate_using_a_file_descriptor"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>fs.truncate()</code> <code>fs.truncateSync()</code> usage with a file descriptor is
deprecated. Please use <code>fs.ftruncate()</code> or <code>fs.ftruncateSync()</code> to work with
file descriptors.</p>
<h4 id="DEP0082">DEP0082: <code>REPLServer.prototype.memory()</code><span><a class="mark" href="#all_deprecations_dep0082-replserverprototypememory" id="all_deprecations_dep0082-replserverprototypememory">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0082_replserver_prototype_memory"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>REPLServer.prototype.memory()</code> is only necessary for the internal mechanics of
the <code>REPLServer</code> itself. Do not use this function.</p>
<h4 id="DEP0083">DEP0083: Disabling ECDH by setting <code>ecdhCurve</code> to <code>false</code><span><a class="mark" href="#all_deprecations_dep0083-disabling-ecdh-by-setting-ecdhcurve-to-false" id="all_deprecations_dep0083-disabling-ecdh-by-setting-ecdhcurve-to-false">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0083_disabling_ecdh_by_setting_ecdhcurve_to_false"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v9.2.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life.</p>
<p>The <code>ecdhCurve</code> option to <code>tls.createSecureContext()</code> and <code>tls.TLSSocket</code> could
be set to <code>false</code> to disable ECDH entirely on the server only. This mode was
deprecated in preparation for migrating to OpenSSL 1.1.0 and consistency with
the client and is now unsupported. Use the <code>ciphers</code> parameter instead.</p>
<h4 id="DEP0084">DEP0084: requiring bundled internal dependencies<span><a class="mark" href="#all_deprecations_dep0084-requiring-bundled-internal-dependencies" id="all_deprecations_dep0084-requiring-bundled-internal-dependencies">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0084_requiring_bundled_internal_dependencies"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>This functionality has been removed.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Since Node.js versions 4.4.0 and 5.2.0, several modules only intended for
internal usage were mistakenly exposed to user code through <code>require()</code>. These
modules were:</p>
<ul>
<li><code>v8/tools/codemap</code></li>
<li><code>v8/tools/consarray</code></li>
<li><code>v8/tools/csvparser</code></li>
<li><code>v8/tools/logreader</code></li>
<li><code>v8/tools/profile_view</code></li>
<li><code>v8/tools/profile</code></li>
<li><code>v8/tools/SourceMap</code></li>
<li><code>v8/tools/splaytree</code></li>
<li><code>v8/tools/tickprocessor-driver</code></li>
<li><code>v8/tools/tickprocessor</code></li>
<li><code>node-inspect/lib/_inspect</code> (from 7.6.0)</li>
<li><code>node-inspect/lib/internal/inspect_client</code> (from 7.6.0)</li>
<li><code>node-inspect/lib/internal/inspect_repl</code> (from 7.6.0)</li>
</ul>
<p>The <code>v8/*</code> modules do not have any exports, and if not imported in a specific
order would in fact throw errors. As such there are virtually no legitimate use
cases for importing them through <code>require()</code>.</p>
<p>On the other hand, <code>node-inspect</code> can be installed locally through a package
manager, as it is published on the npm registry under the same name. No source
code modification is necessary if that is done.</p>
<h4 id="DEP0085">DEP0085: AsyncHooks sensitive API<span><a class="mark" href="#all_deprecations_dep0085-asynchooks-sensitive-api" id="all_deprecations_dep0085-asynchooks-sensitive-api">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0085_asynchooks_sensitive_api"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v9.4.0, v8.10.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The AsyncHooks sensitive API was never documented and had various minor issues.
Use the <code>AsyncResource</code> API instead. See
<a href="https://github.com/nodejs/node/issues/15572">https://github.com/nodejs/node/issues/15572</a>.</p>
<h4 id="DEP0086">DEP0086: Remove <code>runInAsyncIdScope</code><span><a class="mark" href="#all_deprecations_dep0086-remove-runinasyncidscope" id="all_deprecations_dep0086-remove-runinasyncidscope">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0086_remove_runinasyncidscope"></a></h4>
<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>End-of-Life.</p></td></tr>
<tr><td>v9.4.0, v8.10.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>runInAsyncIdScope</code> doesn't emit the <code>'before'</code> or <code>'after'</code> event and can thus
cause a lot of issues. See <a href="https://github.com/nodejs/node/issues/14328">https://github.com/nodejs/node/issues/14328</a>.</p>
<!-- md-lint skip-deprecation DEP0087 -->
<!-- md-lint skip-deprecation DEP0088 -->
<h4 id="DEP0089">DEP0089: <code>require('node:assert')</code><span><a class="mark" href="#all_deprecations_dep0089-requirenodeassert" id="all_deprecations_dep0089-requirenodeassert">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0089_require_node_assert"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.8.0</td>
<td><p>Deprecation revoked.</p></td></tr>
<tr><td>v9.9.0, v8.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Deprecation revoked</p>
<p>Importing assert directly was not recommended as the exposed functions use
loose equality checks. The deprecation was revoked because use of the
<code>node:assert</code> module is not discouraged, and the deprecation caused developer
confusion.</p>
<h4 id="DEP0090">DEP0090: Invalid GCM authentication tag lengths<span><a class="mark" href="#all_deprecations_dep0090-invalid-gcm-authentication-tag-lengths" id="all_deprecations_dep0090-invalid-gcm-authentication-tag-lengths">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0090_invalid_gcm_authentication_tag_lengths"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Node.js used to support all GCM authentication tag lengths which are accepted by
OpenSSL when calling <a href="#all_crypto_deciphersetauthtagbuffer-encoding"><code>decipher.setAuthTag()</code></a>. Beginning with Node.js
v11.0.0, only authentication tag lengths of 128, 120, 112, 104, 96, 64, and 32
bits are allowed. Authentication tags of other lengths are invalid per
<a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf">NIST SP 800-38D</a>.</p>
<h4 id="DEP0091">DEP0091: <code>crypto.DEFAULT_ENCODING</code><span><a class="mark" href="#all_deprecations_dep0091-cryptodefault_encoding" id="all_deprecations_dep0091-cryptodefault_encoding">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0091_crypto_default_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>crypto.DEFAULT_ENCODING</code> property only existed for compatibility with
Node.js releases prior to versions 0.9.3 and has been removed.</p>
<h4 id="DEP0092">DEP0092: Top-level <code>this</code> bound to <code>module.exports</code><span><a class="mark" href="#all_deprecations_dep0092-top-level-this-bound-to-moduleexports" id="all_deprecations_dep0092-top-level-this-bound-to-moduleexports">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0092_top_level_this_bound_to_module_exports"></a></h4>
<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>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Assigning properties to the top-level <code>this</code> as an alternative
to <code>module.exports</code> is deprecated. Developers should use <code>exports</code>
or <code>module.exports</code> instead.</p>
<h4 id="DEP0093">DEP0093: <code>crypto.fips</code> is deprecated and replaced<span><a class="mark" href="#all_deprecations_dep0093-cryptofips-is-deprecated-and-replaced" id="all_deprecations_dep0093-cryptofips-is-deprecated-and-replaced">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0093_crypto_fips_is_deprecated_and_replaced"></a></h4>
<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>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_crypto_cryptofips"><code>crypto.fips</code></a> property is deprecated. Please use <code>crypto.setFips()</code>
and <code>crypto.getFips()</code> instead.</p>
<h4 id="DEP0094">DEP0094: Using <code>assert.fail()</code> with more than one argument<span><a class="mark" href="#all_deprecations_dep0094-using-assertfail-with-more-than-one-argument" id="all_deprecations_dep0094-using-assertfail-with-more-than-one-argument">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0094_using_assert_fail_with_more_than_one_argument"></a></h4>
<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>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Using <code>assert.fail()</code> with more than one argument is deprecated. Use
<code>assert.fail()</code> with only one argument or use a different <code>node:assert</code> module
method.</p>
<h4 id="DEP0095">DEP0095: <code>timers.enroll()</code><span><a class="mark" href="#all_deprecations_dep0095-timersenroll" id="all_deprecations_dep0095-timersenroll">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0095_timers_enroll"></a></h4>
<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>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>timers.enroll()</code> is deprecated. Please use the publicly documented
<a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a> or <a href="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a> instead.</p>
<h4 id="DEP0096">DEP0096: <code>timers.unenroll()</code><span><a class="mark" href="#all_deprecations_dep0096-timersunenroll" id="all_deprecations_dep0096-timersunenroll">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0096_timers_unenroll"></a></h4>
<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>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>timers.unenroll()</code> is deprecated. Please use the publicly documented
<a href="#all_timers_cleartimeouttimeout"><code>clearTimeout()</code></a> or <a href="#all_timers_clearintervaltimeout"><code>clearInterval()</code></a> instead.</p>
<h4 id="DEP0097">DEP0097: <code>MakeCallback</code> with <code>domain</code> property<span><a class="mark" href="#all_deprecations_dep0097-makecallback-with-domain-property" id="all_deprecations_dep0097-makecallback-with-domain-property">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0097_makecallback_with_domain_property"></a></h4>
<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>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Users of <code>MakeCallback</code> that add the <code>domain</code> property to carry context,
should start using the <code>async_context</code> variant of <code>MakeCallback</code> or
<code>CallbackScope</code>, or the high-level <code>AsyncResource</code> class.</p>
<h4 id="DEP0098">DEP0098: AsyncHooks embedder <code>AsyncResource.emitBefore</code> and <code>AsyncResource.emitAfter</code> APIs<span><a class="mark" href="#all_deprecations_dep0098-asynchooks-embedder-asyncresourceemitbefore-and-asyncresourceemitafter-apis" id="all_deprecations_dep0098-asynchooks-embedder-asyncresourceemitbefore-and-asyncresourceemitafter-apis">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0098_asynchooks_embedder_asyncresource_emitbefore_and_asyncresource_emitafter_apis"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v10.0.0, v9.6.0, v8.12.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The embedded API provided by AsyncHooks exposes <code>.emitBefore()</code> and
<code>.emitAfter()</code> methods which are very easy to use incorrectly which can lead
to unrecoverable errors.</p>
<p>Use <a href="#all_async_context_asyncresourceruninasyncscopefn-thisarg-args"><code>asyncResource.runInAsyncScope()</code></a> API instead which provides a much
safer, and more convenient, alternative. See
<a href="https://github.com/nodejs/node/pull/18513">https://github.com/nodejs/node/pull/18513</a>.</p>
<h4 id="DEP0099">DEP0099: Async context-unaware <code>node::MakeCallback</code> C++ APIs<span><a class="mark" href="#all_deprecations_dep0099-async-context-unaware-nodemakecallback-c-apis" id="all_deprecations_dep0099-async-context-unaware-nodemakecallback-c-apis">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0099_async_context_unaware_node_makecallback_c_apis"></a></h4>
<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>Compile-time deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Compile-time</p>
<p>Certain versions of <code>node::MakeCallback</code> APIs available to native addons are
deprecated. Please use the versions of the API that accept an <code>async_context</code>
parameter.</p>
<h4 id="DEP0100">DEP0100: <code>process.assert()</code><span><a class="mark" href="#all_deprecations_dep0100-processassert" id="all_deprecations_dep0100-processassert">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0100_process_assert"></a></h4>
<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>Runtime deprecation.</p></td></tr>
<tr><td>v0.3.7</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>process.assert()</code> is deprecated. Please use the <a href="assert.html"><code>assert</code></a> module instead.</p>
<p>This was never a documented feature.</p>
<h4 id="DEP0101">DEP0101: <code>--with-lttng</code><span><a class="mark" href="#all_deprecations_dep0101---with-lttng" id="all_deprecations_dep0101---with-lttng">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0101_with_lttng"></a></h4>
<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>End-of-Life.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>--with-lttng</code> compile-time option has been removed.</p>
<h4 id="DEP0102">DEP0102: Using <code>noAssert</code> in <code>Buffer#(read|write)</code> operations<span><a class="mark" href="#all_deprecations_dep0102-using-noassert-in-bufferreadwrite-operations" id="all_deprecations_dep0102-using-noassert-in-bufferreadwrite-operations">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0102_using_noassert_in_buffer_read_write_operations"></a></h4>
<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>End-of-Life.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Using the <code>noAssert</code> argument has no functionality anymore. All input is
verified regardless of the value of <code>noAssert</code>. Skipping the verification
could lead to hard-to-find errors and crashes.</p>
<h4 id="DEP0103">DEP0103: <code>process.binding('util').is[...]</code> typechecks<span><a class="mark" href="#all_deprecations_dep0103-processbindingutilis-typechecks" id="all_deprecations_dep0103-processbindingutilis-typechecks">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0103_process_binding_util_is_typechecks"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.9.0</td>
<td><p>Superseded by <a href="#DEP0111">DEP0111</a>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p>Using <code>process.binding()</code> in general should be avoided. The type checking
methods in particular can be replaced by using <a href="#all_util_utiltypes"><code>util.types</code></a>.</p>
<p>This deprecation has been superseded by the deprecation of the
<code>process.binding()</code> API (<a href="#DEP0111">DEP0111</a>).</p>
<h4 id="DEP0104">DEP0104: <code>process.env</code> string coercion<span><a class="mark" href="#all_deprecations_dep0104-processenv-string-coercion" id="all_deprecations_dep0104-processenv-string-coercion">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0104_process_env_string_coercion"></a></h4>
<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>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p>When assigning a non-string property to <a href="#all_process_processenv"><code>process.env</code></a>, the assigned value is
implicitly converted to a string. This behavior is deprecated if the assigned
value is not a string, boolean, or number. In the future, such assignment might
result in a thrown error. Please convert the property to a string before
assigning it to <code>process.env</code>.</p>
<h4 id="DEP0105">DEP0105: <code>decipher.finaltol</code><span><a class="mark" href="#all_deprecations_dep0105-decipherfinaltol" id="all_deprecations_dep0105-decipherfinaltol">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0105_decipher_finaltol"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>decipher.finaltol()</code> has never been documented and was an alias for
<a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a>. This API has been removed, and it is recommended to use
<a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> instead.</p>
<h4 id="DEP0106">DEP0106: <code>crypto.createCipher</code> and <code>crypto.createDecipher</code><span><a class="mark" href="#all_deprecations_dep0106-cryptocreatecipher-and-cryptocreatedecipher" id="all_deprecations_dep0106-cryptocreatecipher-and-cryptocreatedecipher">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0106_crypto_createcipher_and_crypto_createdecipher"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Using <a href="#all_crypto_cryptocreatecipheralgorithm-password-options"><code>crypto.createCipher()</code></a> and <a href="#all_crypto_cryptocreatedecipheralgorithm-password-options"><code>crypto.createDecipher()</code></a> must be
avoided as they use a weak key derivation function (MD5 with no salt) and static
initialization vectors. It is recommended to derive a key using
<a href="#all_crypto_cryptopbkdf2password-salt-iterations-keylen-digest-callback"><code>crypto.pbkdf2()</code></a> or <a href="#all_crypto_cryptoscryptpassword-salt-keylen-options-callback"><code>crypto.scrypt()</code></a> with random salts and to use
<a href="#all_crypto_cryptocreatecipherivalgorithm-key-iv-options"><code>crypto.createCipheriv()</code></a> and <a href="#all_crypto_cryptocreatedecipherivalgorithm-key-iv-options"><code>crypto.createDecipheriv()</code></a> to obtain the
<a href="#all_crypto_class-cipher"><code>Cipher</code></a> and <a href="#all_crypto_class-decipher"><code>Decipher</code></a> objects respectively.</p>
<h4 id="DEP0107">DEP0107: <code>tls.convertNPNProtocols()</code><span><a class="mark" href="#all_deprecations_dep0107-tlsconvertnpnprotocols" id="all_deprecations_dep0107-tlsconvertnpnprotocols">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0107_tls_convertnpnprotocols"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>This was an undocumented helper function not intended for use outside Node.js
core and obsoleted by the removal of NPN (Next Protocol Negotiation) support.</p>
<h4 id="DEP0108">DEP0108: <code>zlib.bytesRead</code><span><a class="mark" href="#all_deprecations_dep0108-zlibbytesread" id="all_deprecations_dep0108-zlibbytesread">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0108_zlib_bytesread"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Deprecated alias for <a href="#all_zlib_zlibbyteswritten"><code>zlib.bytesWritten</code></a>. This original name was chosen
because it also made sense to interpret the value as the number of bytes
read by the engine, but is inconsistent with other streams in Node.js that
expose values under these names.</p>
<h4 id="DEP0109">DEP0109: <code>http</code>, <code>https</code>, and <code>tls</code> support for invalid URLs<span><a class="mark" href="#all_deprecations_dep0109-http-https-and-tls-support-for-invalid-urls" id="all_deprecations_dep0109-http-https-and-tls-support-for-invalid-urls">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0109_http_https_and_tls_support_for_invalid_urls"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Some previously supported (but strictly invalid) URLs were accepted through the
<a href="#all_http_httprequestoptions-callback"><code>http.request()</code></a>, <a href="#all_http_httpgetoptions-callback"><code>http.get()</code></a>, <a href="#all_https_httpsrequestoptions-callback"><code>https.request()</code></a>,
<a href="#all_https_httpsgetoptions-callback"><code>https.get()</code></a>, and <a href="#all_tls_tlscheckserveridentityhostname-cert"><code>tls.checkServerIdentity()</code></a> APIs because those were
accepted by the legacy <code>url.parse()</code> API. The mentioned APIs now use the WHATWG
URL parser that requires strictly valid URLs. Passing an invalid URL is
deprecated and support will be removed in the future.</p>
<h4 id="DEP0110">DEP0110: <code>vm.Script</code> cached data<span><a class="mark" href="#all_deprecations_dep0110-vmscript-cached-data" id="all_deprecations_dep0110-vmscript-cached-data">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0110_vm_script_cached_data"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.6.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>produceCachedData</code> option is deprecated. Use
<a href="#all_vm_scriptcreatecacheddata"><code>script.createCachedData()</code></a> instead.</p>
<h4 id="DEP0111">DEP0111: <code>process.binding()</code><span><a class="mark" href="#all_deprecations_dep0111-processbinding" id="all_deprecations_dep0111-processbinding">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0111_process_binding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.12.0</td>
<td><p>Added support for <code>--pending-deprecation</code>.</p></td></tr>
<tr><td>v10.9.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p><code>process.binding()</code> is for use by Node.js internal code only.</p>
<p>While <code>process.binding()</code> has not reached End-of-Life status in general, it is
unavailable when <a href="#all_permissions_policies">policies</a> or the <a href="#all_permissions_permission-model">permission model</a> are enabled.</p>
<h4 id="DEP0112">DEP0112: <code>dgram</code> private APIs<span><a class="mark" href="#all_deprecations_dep0112-dgram-private-apis" id="all_deprecations_dep0112-dgram-private-apis">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0112_dgram_private_apis"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>node:dgram</code> module previously contained several APIs that were never meant
to accessed outside of Node.js core: <code>Socket.prototype._handle</code>,
<code>Socket.prototype._receiving</code>, <code>Socket.prototype._bindState</code>,
<code>Socket.prototype._queue</code>, <code>Socket.prototype._reuseAddr</code>,
<code>Socket.prototype._healthCheck()</code>, <code>Socket.prototype._stopReceiving()</code>, and
<code>dgram._createSocketHandle()</code>.</p>
<h4 id="DEP0113">DEP0113: <code>Cipher.setAuthTag()</code>, <code>Decipher.getAuthTag()</code><span><a class="mark" href="#all_deprecations_dep0113-ciphersetauthtag-deciphergetauthtag" id="all_deprecations_dep0113-ciphersetauthtag-deciphergetauthtag">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0113_cipher_setauthtag_decipher_getauthtag"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>Cipher.setAuthTag()</code> and <code>Decipher.getAuthTag()</code> are no longer available. They
were never documented and would throw when called.</p>
<h4 id="DEP0114">DEP0114: <code>crypto._toBuf()</code><span><a class="mark" href="#all_deprecations_dep0114-crypto_tobuf" id="all_deprecations_dep0114-crypto_tobuf">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0114_crypto_tobuf"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>crypto._toBuf()</code> function was not designed to be used by modules outside
of Node.js core and was removed.</p>
<!--lint disable nodejs-yaml-comments -->
<h4 id="DEP0115">DEP0115: <code>crypto.prng()</code>, <code>crypto.pseudoRandomBytes()</code>, <code>crypto.rng()</code><span><a class="mark" href="#all_deprecations_dep0115-cryptoprng-cryptopseudorandombytes-cryptorng" id="all_deprecations_dep0115-cryptoprng-cryptopseudorandombytes-cryptorng">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0115_crypto_prng_crypto_pseudorandombytes_crypto_rng"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Added documentation-only deprecation with <code>--pending-deprecation</code> support.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<!--lint enable nodejs-yaml-comments -->
<p>In recent versions of Node.js, there is no difference between
<a href="#all_crypto_cryptorandombytessize-callback"><code>crypto.randomBytes()</code></a> and <code>crypto.pseudoRandomBytes()</code>. The latter is
deprecated along with the undocumented aliases <code>crypto.prng()</code> and
<code>crypto.rng()</code> in favor of <a href="#all_crypto_cryptorandombytessize-callback"><code>crypto.randomBytes()</code></a> and might be removed in a
future release.</p>
<h4 id="DEP0116">DEP0116: Legacy URL API<span><a class="mark" href="#all_deprecations_dep0116-legacy-url-api" id="all_deprecations_dep0116-legacy-url-api">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0116_legacy_url_api"></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.0.0, v18.13.0</td>
<td><p>`url.parse()` is deprecated again in DEP0169.</p></td></tr>
<tr><td>v15.13.0, v14.17.0</td>
<td><p>Deprecation revoked. Status changed to "Legacy".</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Deprecation revoked</p>
<p>The <a href="#all_url_legacy-url-api">legacy URL API</a> is deprecated. This includes <a href="#all_url_urlformaturlobject"><code>url.format()</code></a>,
<a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a>, <a href="#all_url_urlresolvefrom-to"><code>url.resolve()</code></a>, and the <a href="#all_url_legacy-urlobject">legacy <code>urlObject</code></a>. Please
use the <a href="#all_url_the-whatwg-url-api">WHATWG URL API</a> instead.</p>
<h4 id="DEP0117">DEP0117: Native crypto handles<span><a class="mark" href="#all_deprecations_dep0117-native-crypto-handles" id="all_deprecations_dep0117-native-crypto-handles">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0117_native_crypto_handles"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Previous versions of Node.js exposed handles to internal native objects through
the <code>_handle</code> property of the <code>Cipher</code>, <code>Decipher</code>, <code>DiffieHellman</code>,
<code>DiffieHellmanGroup</code>, <code>ECDH</code>, <code>Hash</code>, <code>Hmac</code>, <code>Sign</code>, and <code>Verify</code> classes.
The <code>_handle</code> property has been removed because improper use of the native
object can lead to crashing the application.</p>
<h4 id="DEP0118">DEP0118: <code>dns.lookup()</code> support for a falsy host name<span><a class="mark" href="#all_deprecations_dep0118-dnslookup-support-for-a-falsy-host-name" id="all_deprecations_dep0118-dnslookup-support-for-a-falsy-host-name">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0118_dns_lookup_support_for_a_falsy_host_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Previous versions of Node.js supported <code>dns.lookup()</code> with a falsy host name
like <code>dns.lookup(false)</code> due to backward compatibility.
This behavior is undocumented and is thought to be unused in real world apps.
It will become an error in future versions of Node.js.</p>
<h4 id="DEP0119">DEP0119: <code>process.binding('uv').errname()</code> private API<span><a class="mark" href="#all_deprecations_dep0119-processbindinguverrname-private-api" id="all_deprecations_dep0119-processbindinguverrname-private-api">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0119_process_binding_uv_errname_private_api"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p><code>process.binding('uv').errname()</code> is deprecated. Please use
<a href="#all_util_utilgetsystemerrornameerr"><code>util.getSystemErrorName()</code></a> instead.</p>
<h4 id="DEP0120">DEP0120: Windows Performance Counter support<span><a class="mark" href="#all_deprecations_dep0120-windows-performance-counter-support" id="all_deprecations_dep0120-windows-performance-counter-support">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0120_windows_performance_counter_support"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Windows Performance Counter support has been removed from Node.js. The
undocumented <code>COUNTER_NET_SERVER_CONNECTION()</code>,
<code>COUNTER_NET_SERVER_CONNECTION_CLOSE()</code>, <code>COUNTER_HTTP_SERVER_REQUEST()</code>,
<code>COUNTER_HTTP_SERVER_RESPONSE()</code>, <code>COUNTER_HTTP_CLIENT_REQUEST()</code>, and
<code>COUNTER_HTTP_CLIENT_RESPONSE()</code> functions have been deprecated.</p>
<h4 id="DEP0121">DEP0121: <code>net._setSimultaneousAccepts()</code><span><a class="mark" href="#all_deprecations_dep0121-net_setsimultaneousaccepts" id="all_deprecations_dep0121-net_setsimultaneousaccepts">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0121_net_setsimultaneousaccepts"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The undocumented <code>net._setSimultaneousAccepts()</code> function was originally
intended for debugging and performance tuning when using the
<code>node:child_process</code> and <code>node:cluster</code> modules on Windows. The function is not
generally useful and is being removed. See discussion here:
<a href="https://github.com/nodejs/node/issues/18391">https://github.com/nodejs/node/issues/18391</a></p>
<h4 id="DEP0122">DEP0122: <code>tls</code> <code>Server.prototype.setOptions()</code><span><a class="mark" href="#all_deprecations_dep0122-tls-serverprototypesetoptions" id="all_deprecations_dep0122-tls-serverprototypesetoptions">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0122_tls_server_prototype_setoptions"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Please use <code>Server.prototype.setSecureContext()</code> instead.</p>
<h4 id="DEP0123">DEP0123: setting the TLS ServerName to an IP address<span><a class="mark" href="#all_deprecations_dep0123-setting-the-tls-servername-to-an-ip-address" id="all_deprecations_dep0123-setting-the-tls-servername-to-an-ip-address">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0123_setting_the_tls_servername_to_an_ip_address"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Setting the TLS ServerName to an IP address is not permitted by
<a href="https://tools.ietf.org/html/rfc6066#section-3">RFC 6066</a>. This will be ignored in a future version.</p>
<h4 id="DEP0124">DEP0124: using <code>REPLServer.rli</code><span><a class="mark" href="#all_deprecations_dep0124-using-replserverrli" id="all_deprecations_dep0124-using-replserverrli">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0124_using_replserver_rli"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>This property is a reference to the instance itself.</p>
<h4 id="DEP0125">DEP0125: <code>require('node:_stream_wrap')</code><span><a class="mark" href="#all_deprecations_dep0125-requirenode_stream_wrap" id="all_deprecations_dep0125-requirenode_stream_wrap">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0125_require_node_stream_wrap"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>node:_stream_wrap</code> module is deprecated.</p>
<h4 id="DEP0126">DEP0126: <code>timers.active()</code><span><a class="mark" href="#all_deprecations_dep0126-timersactive" id="all_deprecations_dep0126-timersactive">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0126_timers_active"></a></h4>
<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>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The previously undocumented <code>timers.active()</code> is deprecated.
Please use the publicly documented <a href="#all_timers_timeoutrefresh"><code>timeout.refresh()</code></a> instead.
If re-referencing the timeout is necessary, <a href="#all_timers_timeoutref"><code>timeout.ref()</code></a> can be used
with no performance impact since Node.js 10.</p>
<h4 id="DEP0127">DEP0127: <code>timers._unrefActive()</code><span><a class="mark" href="#all_deprecations_dep0127-timers_unrefactive" id="all_deprecations_dep0127-timers_unrefactive">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0127_timers_unrefactive"></a></h4>
<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>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The previously undocumented and "private" <code>timers._unrefActive()</code> is deprecated.
Please use the publicly documented <a href="#all_timers_timeoutrefresh"><code>timeout.refresh()</code></a> instead.
If unreferencing the timeout is necessary, <a href="#all_timers_timeoutunref"><code>timeout.unref()</code></a> can be used
with no performance impact since Node.js 10.</p>
<h4 id="DEP0128">DEP0128: modules with an invalid <code>main</code> entry and an <code>index.js</code> file<span><a class="mark" href="#all_deprecations_dep0128-modules-with-an-invalid-main-entry-and-an-indexjs-file" id="all_deprecations_dep0128-modules-with-an-invalid-main-entry-and-an-indexjs-file">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0128_modules_with_an_invalid_main_entry_and_an_index_js_file"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Documentation-only.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Modules that have an invalid <code>main</code> entry (e.g., <code>./does-not-exist.js</code>) and
also have an <code>index.js</code> file in the top level directory will resolve the
<code>index.js</code> file. That is deprecated and is going to throw an error in future
Node.js versions.</p>
<h4 id="DEP0129">DEP0129: <code>ChildProcess._channel</code><span><a class="mark" href="#all_deprecations_dep0129-childprocess_channel" id="all_deprecations_dep0129-childprocess_channel">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0129_childprocess_channel"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v11.14.0</td>
<td><p>Documentation-only.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>_channel</code> property of child process objects returned by <code>spawn()</code> and
similar functions is not intended for public use. Use <code>ChildProcess.channel</code>
instead.</p>
<h4 id="DEP0130">DEP0130: <code>Module.createRequireFromPath()</code><span><a class="mark" href="#all_deprecations_dep0130-modulecreaterequirefrompath" id="all_deprecations_dep0130-modulecreaterequirefrompath">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0130_module_createrequirefrompath"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>End-of-life.</p></td></tr>
<tr><td>v13.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v12.2.0</td>
<td><p>Documentation-only.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Use <a href="#all_module_modulecreaterequirefilename"><code>module.createRequire()</code></a> instead.</p>
<h4 id="DEP0131">DEP0131: Legacy HTTP parser<span><a class="mark" href="#all_deprecations_dep0131-legacy-http-parser" id="all_deprecations_dep0131-legacy-http-parser">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0131_legacy_http_parser"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>This feature has been removed.</p></td></tr>
<tr><td>v12.22.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v12.3.0</td>
<td><p>Documentation-only.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The legacy HTTP parser, used by default in versions of Node.js prior to 12.0.0,
is deprecated and has been removed in v13.0.0. Prior to v13.0.0, the
<code>--http-parser=legacy</code> command-line flag could be used to revert to using the
legacy parser.</p>
<h4 id="DEP0132">DEP0132: <code>worker.terminate()</code> with callback<span><a class="mark" href="#all_deprecations_dep0132-workerterminate-with-callback" id="all_deprecations_dep0132-workerterminate-with-callback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0132_worker_terminate_with_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>v12.5.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Passing a callback to <a href="#all_worker_threads_workerterminate"><code>worker.terminate()</code></a> is deprecated. Use the returned
<code>Promise</code> instead, or a listener to the worker's <code>'exit'</code> event.</p>
<h4 id="DEP0133">DEP0133: <code>http</code> <code>connection</code><span><a class="mark" href="#all_deprecations_dep0133-http-connection" id="all_deprecations_dep0133-http-connection">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0133_http_connection"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.12.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Prefer <a href="#all_http_responsesocket"><code>response.socket</code></a> over <a href="#all_http_responseconnection"><code>response.connection</code></a> and
<a href="#all_http_requestsocket"><code>request.socket</code></a> over <a href="#all_http_requestconnection"><code>request.connection</code></a>.</p>
<h4 id="DEP0134">DEP0134: <code>process._tickCallback</code><span><a class="mark" href="#all_deprecations_dep0134-process_tickcallback" id="all_deprecations_dep0134-process_tickcallback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0134_process_tickcallback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.12.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p>The <code>process._tickCallback</code> property was never documented as
an officially supported API.</p>
<h4 id="DEP0135">DEP0135: <code>WriteStream.open()</code> and <code>ReadStream.open()</code> are internal<span><a class="mark" href="#all_deprecations_dep0135-writestreamopen-and-readstreamopen-are-internal" id="all_deprecations_dep0135-writestreamopen-and-readstreamopen-are-internal">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0135_writestream_open_and_readstream_open_are_internal"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><a href="#all_fs_class-fswritestream"><code>WriteStream.open()</code></a> and <a href="#all_fs_class-fsreadstream"><code>ReadStream.open()</code></a> are undocumented internal
APIs that do not make sense to use in userland. File streams should always be
opened through their corresponding factory methods <a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a>
and <a href="#all_fs_fscreatereadstreampath-options"><code>fs.createReadStream()</code></a>) or by passing a file descriptor in options.</p>
<h4 id="DEP0136">DEP0136: <code>http</code> <code>finished</code><span><a class="mark" href="#all_deprecations_dep0136-http-finished" id="all_deprecations_dep0136-http-finished">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0136_http_finished"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.4.0, v12.16.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p><a href="#all_http_responsefinished"><code>response.finished</code></a> indicates whether <a href="#all_http_responseenddata-encoding-callback"><code>response.end()</code></a> has been
called, not whether <code>'finish'</code> has been emitted and the underlying data
is flushed.</p>
<p>Use <a href="#all_http_responsewritablefinished"><code>response.writableFinished</code></a> or <a href="#all_http_responsewritableended"><code>response.writableEnded</code></a>
accordingly instead to avoid the ambiguity.</p>
<p>To maintain existing behavior <code>response.finished</code> should be replaced with
<code>response.writableEnded</code>.</p>
<h4 id="DEP0137">DEP0137: Closing fs.FileHandle on garbage collection<span><a class="mark" href="#all_deprecations_dep0137-closing-fsfilehandle-on-garbage-collection" id="all_deprecations_dep0137-closing-fsfilehandle-on-garbage-collection">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0137_closing_fs_filehandle_on_garbage_collection"></a></h4>
<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>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Allowing a <a href="#all_fs_class-filehandle"><code>fs.FileHandle</code></a> object to be closed on garbage collection is
deprecated. In the future, doing so might result in a thrown error that will
terminate the process.</p>
<p>Please ensure that all <code>fs.FileHandle</code> objects are explicitly closed using
<code>FileHandle.prototype.close()</code> when the <code>fs.FileHandle</code> is no longer needed:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fsPromises = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>).<span class="hljs-property">promises</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">openAndClose</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">let</span> filehandle;
<span class="hljs-keyword">try</span> {
filehandle = <span class="hljs-keyword">await</span> fsPromises.<span class="hljs-title function_">open</span>(<span class="hljs-string">'thefile.txt'</span>, <span class="hljs-string">'r'</span>);
} <span class="hljs-keyword">finally</span> {
<span class="hljs-keyword">if</span> (filehandle !== <span class="hljs-literal">undefined</span>)
<span class="hljs-keyword">await</span> filehandle.<span class="hljs-title function_">close</span>();
}
}</code> <button class="copy-button">copy</button></pre>
<h4 id="DEP0138">DEP0138: <code>process.mainModule</code><span><a class="mark" href="#all_deprecations_dep0138-processmainmodule" id="all_deprecations_dep0138-processmainmodule">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0138_process_mainmodule"></a></h4>
<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>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p><a href="#all_process_processmainmodule"><code>process.mainModule</code></a> is a CommonJS-only feature while <code>process</code> global
object is shared with non-CommonJS environment. Its use within ECMAScript
modules is unsupported.</p>
<p>It is deprecated in favor of <a href="#all_modules_accessing-the-main-module"><code>require.main</code></a>, because it serves the same
purpose and is only available on CommonJS environment.</p>
<h4 id="DEP0139">DEP0139: <code>process.umask()</code> with no arguments<span><a class="mark" href="#all_deprecations_dep0139-processumask-with-no-arguments" id="all_deprecations_dep0139-processumask-with-no-arguments">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0139_process_umask_with_no_arguments"></a></h4>
<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, v12.19.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Calling <code>process.umask()</code> with no argument causes the process-wide umask to be
written twice. This introduces a race condition between threads, and is a
potential security vulnerability. There is no safe, cross-platform alternative
API.</p>
<h4 id="DEP0140">DEP0140: Use <code>request.destroy()</code> instead of <code>request.abort()</code><span><a class="mark" href="#all_deprecations_dep0140-use-requestdestroy-instead-of-requestabort" id="all_deprecations_dep0140-use-requestdestroy-instead-of-requestabort">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0140_use_request_destroy_instead_of_request_abort"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.1.0, v13.14.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Use <a href="#all_http_requestdestroyerror"><code>request.destroy()</code></a> instead of <a href="#all_http_requestabort"><code>request.abort()</code></a>.</p>
<h4 id="DEP0141">DEP0141: <code>repl.inputStream</code> and <code>repl.outputStream</code><span><a class="mark" href="#all_deprecations_dep0141-replinputstream-and-reploutputstream" id="all_deprecations_dep0141-replinputstream-and-reploutputstream">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0141_repl_inputstream_and_repl_outputstream"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.3.0</td>
<td><p>Documentation-only (supports [<code>--pending-deprecation</code>][]).</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p>The <code>node:repl</code> module exported the input and output stream twice. Use <code>.input</code>
instead of <code>.inputStream</code> and <code>.output</code> instead of <code>.outputStream</code>.</p>
<h4 id="DEP0142">DEP0142: <code>repl._builtinLibs</code><span><a class="mark" href="#all_deprecations_dep0142-repl_builtinlibs" id="all_deprecations_dep0142-repl_builtinlibs">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0142_repl_builtinlibs"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.3.0</td>
<td><p>Documentation-only (supports [<code>--pending-deprecation</code>][]).</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>node:repl</code> module exports a <code>_builtinLibs</code> property that contains an array
of built-in modules. It was incomplete so far and instead it's better to rely
upon <code>require('node:module').builtinModules</code>.</p>
<h4 id="DEP0143">DEP0143: <code>Transform._transformState</code><span><a class="mark" href="#all_deprecations_dep0143-transform_transformstate" id="all_deprecations_dep0143-transform_transformstate">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0143_transform_transformstate"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime
<code>Transform._transformState</code> will be removed in future versions where it is
no longer required due to simplification of the implementation.</p>
<h4 id="DEP0144">DEP0144: <code>module.parent</code><span><a class="mark" href="#all_deprecations_dep0144-moduleparent" id="all_deprecations_dep0144-moduleparent">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0144_module_parent"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.6.0, v12.19.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p>A CommonJS module can access the first module that required it using
<code>module.parent</code>. This feature is deprecated because it does not work
consistently in the presence of ECMAScript modules and because it gives an
inaccurate representation of the CommonJS module graph.</p>
<p>Some modules use it to check if they are the entry point of the current process.
Instead, it is recommended to compare <code>require.main</code> and <code>module</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">if</span> (<span class="hljs-built_in">require</span>.<span class="hljs-property">main</span> === <span class="hljs-variable language_">module</span>) {
<span class="hljs-comment">// Code section that will run only if current file is the entry point.</span>
}</code> <button class="copy-button">copy</button></pre>
<p>When looking for the CommonJS modules that have required the current one,
<code>require.cache</code> and <code>module.children</code> can be used:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> moduleParents = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">values</span>(<span class="hljs-built_in">require</span>.<span class="hljs-property">cache</span>)
.<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">m</span>) =></span> m.<span class="hljs-property">children</span>.<span class="hljs-title function_">includes</span>(<span class="hljs-variable language_">module</span>));</code> <button class="copy-button">copy</button></pre>
<h4 id="DEP0145">DEP0145: <code>socket.bufferSize</code><span><a class="mark" href="#all_deprecations_dep0145-socketbuffersize" id="all_deprecations_dep0145-socketbuffersize">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0145_socket_buffersize"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.6.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p><a href="#all_net_socketbuffersize"><code>socket.bufferSize</code></a> is just an alias for <a href="#all_stream_writablewritablelength"><code>writable.writableLength</code></a>.</p>
<h4 id="DEP0146">DEP0146: <code>new crypto.Certificate()</code><span><a class="mark" href="#all_deprecations_dep0146-new-cryptocertificate" id="all_deprecations_dep0146-new-cryptocertificate">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0146_new_crypto_certificate"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_crypto_legacy-api"><code>crypto.Certificate()</code> constructor</a> is deprecated. Use
<a href="#all_crypto_class-certificate">static methods of <code>crypto.Certificate()</code></a> instead.</p>
<h4 id="DEP0147">DEP0147: <code>fs.rmdir(path, { recursive: true })</code><span><a class="mark" href="#all_deprecations_dep0147-fsrmdirpath--recursive-true-" id="all_deprecations_dep0147-fsrmdirpath--recursive-true-">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0147_fs_rmdir_path_recursive_true"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Runtime deprecation for permissive behavior.</p></td></tr>
<tr><td>v14.14.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>In future versions of Node.js, <code>recursive</code> option will be ignored for
<code>fs.rmdir</code>, <code>fs.rmdirSync</code>, and <code>fs.promises.rmdir</code>.</p>
<p>Use <code>fs.rm(path, { recursive: true, force: true })</code>,
<code>fs.rmSync(path, { recursive: true, force: true })</code> or
<code>fs.promises.rm(path, { recursive: true, force: true })</code> instead.</p>
<h4 id="DEP0148">DEP0148: Folder mappings in <code>"exports"</code> (trailing <code>"/"</code>)<span><a class="mark" href="#all_deprecations_dep0148-folder-mappings-in-exports-trailing-" id="all_deprecations_dep0148-folder-mappings-in-exports-trailing-">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0148_folder_mappings_in_exports_trailing"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v15.1.0</td>
<td><p>Runtime deprecation for self-referencing imports.</p></td></tr>
<tr><td>v14.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Using a trailing <code>"/"</code> to define subpath folder mappings in the
<a href="#all_packages_subpath-exports">subpath exports</a> or <a href="#all_packages_subpath-imports">subpath imports</a> fields is deprecated. Use
<a href="#all_packages_subpath-patterns">subpath patterns</a> instead.</p>
<h4 id="DEP0149">DEP0149: <code>http.IncomingMessage#connection</code><span><a class="mark" href="#all_deprecations_dep0149-httpincomingmessageconnection" id="all_deprecations_dep0149-httpincomingmessageconnection">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0149_http_incomingmessage_connection"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only.</p>
<p>Prefer <a href="#all_http_messagesocket"><code>message.socket</code></a> over <a href="#all_http_messageconnection"><code>message.connection</code></a>.</p>
<h4 id="DEP0150">DEP0150: Changing the value of <code>process.config</code><span><a class="mark" href="#all_deprecations_dep0150-changing-the-value-of-processconfig" id="all_deprecations_dep0150-changing-the-value-of-processconfig">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0150_changing_the_value_of_process_config"></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.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>process.config</code> property provides access to Node.js compile-time settings.
However, the property is mutable and therefore subject to tampering. The ability
to change the value will be removed in a future version of Node.js.</p>
<h4 id="DEP0151">DEP0151: Main index lookup and extension searching<span><a class="mark" href="#all_deprecations_dep0151-main-index-lookup-and-extension-searching" id="all_deprecations_dep0151-main-index-lookup-and-extension-searching">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0151_main_index_lookup_and_extension_searching"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v15.8.0, v14.18.0</td>
<td><p>Documentation-only deprecation with <code>--pending-deprecation</code> support.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Previously, <code>index.js</code> and extension searching lookups would apply to
<code>import 'pkg'</code> main entry point resolution, even when resolving ES modules.</p>
<p>With this deprecation, all ES module main entry point resolutions require
an explicit <a href="#all_packages_main-entry-point-export"><code>"exports"</code> or <code>"main"</code> entry</a> with the exact file extension.</p>
<h4 id="DEP0152">DEP0152: Extension PerformanceEntry properties<span><a class="mark" href="#all_deprecations_dep0152-extension-performanceentry-properties" id="all_deprecations_dep0152-extension-performanceentry-properties">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0152_extension_performanceentry_properties"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>'gc'</code>, <code>'http2'</code>, and <code>'http'</code> <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry></a> object types have
additional properties assigned to them that provide additional information.
These properties are now available within the standard <code>detail</code> property
of the <code>PerformanceEntry</code> object. The existing accessors have been
deprecated and should no longer be used.</p>
<h4 id="DEP0153">DEP0153: <code>dns.lookup</code> and <code>dnsPromises.lookup</code> options type coercion<span><a class="mark" href="#all_deprecations_dep0153-dnslookup-and-dnspromiseslookup-options-type-coercion" id="all_deprecations_dep0153-dnslookup-and-dnspromiseslookup-options-type-coercion">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0153_dns_lookup_and_dnspromises_lookup_options_type_coercion"></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</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v16.8.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Using a non-nullish non-integer value for <code>family</code> option, a non-nullish
non-number value for <code>hints</code> option, a non-nullish non-boolean value for <code>all</code>
option, or a non-nullish non-boolean value for <code>verbatim</code> option in
<a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> and <a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup()</code></a> throws an
<code>ERR_INVALID_ARG_TYPE</code> error.</p>
<h4 id="DEP0154">DEP0154: RSA-PSS generate key pair options<span><a class="mark" href="#all_deprecations_dep0154-rsa-pss-generate-key-pair-options" id="all_deprecations_dep0154-rsa-pss-generate-key-pair-options">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0154_rsa_pss_generate_key_pair_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>v20.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v16.10.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>'hash'</code> and <code>'mgf1Hash'</code> options are replaced with <code>'hashAlgorithm'</code>
and <code>'mgf1HashAlgorithm'</code>.</p>
<h4 id="DEP0155">DEP0155: Trailing slashes in pattern specifier resolutions<span><a class="mark" href="#all_deprecations_dep0155-trailing-slashes-in-pattern-specifier-resolutions" id="all_deprecations_dep0155-trailing-slashes-in-pattern-specifier-resolutions">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0155_trailing_slashes_in_pattern_specifier_resolutions"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v16.10.0</td>
<td><p>Documentation-only deprecation with <code>--pending-deprecation</code> support.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The remapping of specifiers ending in <code>"/"</code> like <code>import 'pkg/x/'</code> is deprecated
for package <code>"exports"</code> and <code>"imports"</code> pattern resolutions.</p>
<h4 id="DEP0156">DEP0156: <code>.aborted</code> property and <code>'abort'</code>, <code>'aborted'</code> event in <code>http</code><span><a class="mark" href="#all_deprecations_dep0156-aborted-property-and-abort-aborted-event-in-http" id="all_deprecations_dep0156-aborted-property-and-abort-aborted-event-in-http">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0156_aborted_property_and_abort_aborted_event_in_http"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Move to <a href="#all_stream_stream" class="type"><Stream></a> API instead, as the <a href="#all_http_class-httpclientrequest"><code>http.ClientRequest</code></a>,
<a href="#all_http_class-httpserverresponse"><code>http.ServerResponse</code></a>, and <a href="#all_http_class-httpincomingmessage"><code>http.IncomingMessage</code></a> are all stream-based.
Check <code>stream.destroyed</code> instead of the <code>.aborted</code> property, and listen for
<code>'close'</code> instead of <code>'abort'</code>, <code>'aborted'</code> event.</p>
<p>The <code>.aborted</code> property and <code>'abort'</code> event are only useful for detecting
<code>.abort()</code> calls. For closing a request early, use the Stream
<code>.destroy([error])</code> then check the <code>.destroyed</code> property and <code>'close'</code> event
should have the same effect. The receiving end should also check the
<a href="#all_stream_readablereadableended"><code>readable.readableEnded</code></a> value on <a href="#all_http_class-httpincomingmessage"><code>http.IncomingMessage</code></a> to get whether
it was an aborted or graceful destroy.</p>
<h4 id="DEP0157">DEP0157: Thenable support in streams<span><a class="mark" href="#all_deprecations_dep0157-thenable-support-in-streams" id="all_deprecations_dep0157-thenable-support-in-streams">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0157_thenable_support_in_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>v18.0.0</td>
<td><p>End-of-life.</p></td></tr>
<tr><td>v17.2.0, v16.14.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>An undocumented feature of Node.js streams was to support thenables in
implementation methods. This is now deprecated, use callbacks instead and avoid
use of async function for streams implementation methods.</p>
<p>This feature caused users to encounter unexpected problems where the user
implements the function in callback style but uses e.g. an async method which
would cause an error since mixing promise and callback semantics is not valid.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> w = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({
<span class="hljs-keyword">async</span> <span class="hljs-title function_">final</span>(<span class="hljs-params">callback</span>) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">someOp</span>();
<span class="hljs-title function_">callback</span>();
},
});</code> <button class="copy-button">copy</button></pre>
<h4 id="DEP0158">DEP0158: <code>buffer.slice(start, end)</code><span><a class="mark" href="#all_deprecations_dep0158-bufferslicestart-end" id="all_deprecations_dep0158-bufferslicestart-end">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0158_buffer_slice_start_end"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>This method was deprecated because it is not compatible with
<code>Uint8Array.prototype.slice()</code>, which is a superclass of <code>Buffer</code>.</p>
<p>Use <a href="#all_buffer_bufsubarraystart-end"><code>buffer.subarray</code></a> which does the same thing instead.</p>
<h4 id="DEP0159">DEP0159: <code>ERR_INVALID_CALLBACK</code><span><a class="mark" href="#all_deprecations_dep0159-err_invalid_callback" id="all_deprecations_dep0159-err_invalid_callback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0159_err_invalid_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>v18.0.0</td>
<td><p>End-of-Life.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>This error code was removed due to adding more confusion to
the errors used for value type validation.</p>
<h4 id="DEP0160">DEP0160: <code>process.on('multipleResolves', handler)</code><span><a class="mark" href="#all_deprecations_dep0160-processonmultipleresolves-handler" id="all_deprecations_dep0160-processonmultipleresolves-handler">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0160_process_on_multipleresolves_handler"></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</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime.</p>
<p>This event was deprecated because it did not work with V8 promise combinators
which diminished its usefulness.</p>
<h4 id="DEP0161">DEP0161: <code>process._getActiveRequests()</code> and <code>process._getActiveHandles()</code><span><a class="mark" href="#all_deprecations_dep0161-process_getactiverequests-and-process_getactivehandles" id="all_deprecations_dep0161-process_getactiverequests-and-process_getactivehandles">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0161_process_getactiverequests_and_process_getactivehandles"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>process._getActiveHandles()</code> and <code>process._getActiveRequests()</code>
functions are not intended for public use and can be removed in future
releases.</p>
<p>Use <a href="#all_process_processgetactiveresourcesinfo"><code>process.getActiveResourcesInfo()</code></a> to get a list of types of active
resources and not the actual references.</p>
<h4 id="DEP0162">DEP0162: <code>fs.write()</code>, <code>fs.writeFileSync()</code> coercion to string<span><a class="mark" href="#all_deprecations_dep0162-fswrite-fswritefilesync-coercion-to-string" id="all_deprecations_dep0162-fswrite-fswritefilesync-coercion-to-string">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0162_fs_write_fs_writefilesync_coercion_to_string"></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.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v17.8.0, v16.15.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Implicit coercion of objects with own <code>toString</code> property, passed as second
parameter in <a href="#all_fs_fswritefd-buffer-offset-length-position-callback"><code>fs.write()</code></a>, <a href="#all_fs_fswritefilefile-data-options-callback"><code>fs.writeFile()</code></a>, <a href="#all_fs_fsappendfilepath-data-options-callback"><code>fs.appendFile()</code></a>,
<a href="#all_fs_fswritefilesyncfile-data-options"><code>fs.writeFileSync()</code></a>, and <a href="#all_fs_fsappendfilesyncpath-data-options"><code>fs.appendFileSync()</code></a> is deprecated.
Convert them to primitive strings.</p>
<h4 id="DEP0163">DEP0163: <code>channel.subscribe(onMessage)</code>, <code>channel.unsubscribe(onMessage)</code><span><a class="mark" href="#all_deprecations_dep0163-channelsubscribeonmessage-channelunsubscribeonmessage" id="all_deprecations_dep0163-channelsubscribeonmessage-channelunsubscribeonmessage">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0163_channel_subscribe_onmessage_channel_unsubscribe_onmessage"></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.7.0, v16.17.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>These methods were deprecated because they can be used in a way which does not
hold the channel reference alive long enough to receive the events.</p>
<p>Use <a href="#all_diagnostics_channel_diagnostics_channelsubscribename-onmessage"><code>diagnostics_channel.subscribe(name, onMessage)</code></a> or
<a href="#all_diagnostics_channel_diagnostics_channelunsubscribename-onmessage"><code>diagnostics_channel.unsubscribe(name, onMessage)</code></a> which does the same
thing instead.</p>
<h4 id="DEP0164">DEP0164: <code>process.exit(code)</code>, <code>process.exitCode</code> coercion to integer<span><a class="mark" href="#all_deprecations_dep0164-processexitcode-processexitcode-coercion-to-integer" id="all_deprecations_dep0164-processexitcode-processexitcode-coercion-to-integer">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0164_process_exit_code_process_exitcode_coercion_to_integer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v19.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v18.10.0, v16.18.0</td>
<td><p>Documentation-only deprecation of <code>process.exitCode</code> integer coercion.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p>Documentation-only deprecation of <code>process.exit(code)</code> integer coercion.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Values other than <code>undefined</code>, <code>null</code>, integer numbers, and integer strings
(e.g., <code>'1'</code>) are deprecated as value for the <code>code</code> parameter in
<a href="#all_process_processexitcode"><code>process.exit()</code></a> and as value to assign to <a href="#all_process_processexitcode_1"><code>process.exitCode</code></a>.</p>
<h4 id="DEP0165">DEP0165: <code>--trace-atomics-wait</code><span><a class="mark" href="#all_deprecations_dep0165---trace-atomics-wait" id="all_deprecations_dep0165---trace-atomics-wait">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0165_trace_atomics_wait"></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.8.0, v16.18.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_cli_--trace-atomics-wait"><code>--trace-atomics-wait</code></a> flag is deprecated.</p>
<h4 id="DEP0166">DEP0166: Double slashes in imports and exports targets<span><a class="mark" href="#all_deprecations_dep0166-double-slashes-in-imports-and-exports-targets" id="all_deprecations_dep0166-double-slashes-in-imports-and-exports-targets">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0166_double_slashes_in_imports_and_exports_targets"></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.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v18.10.0</td>
<td><p>Documentation-only deprecation with <code>--pending-deprecation</code> support.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Package imports and exports targets mapping into paths including a double slash
(of <em>"/"</em> or <em>"\"</em>) are deprecated and will fail with a resolution validation
error in a future release. This same deprecation also applies to pattern matches
starting or ending in a slash.</p>
<h4 id="DEP0167">DEP0167: Weak <code>DiffieHellmanGroup</code> instances (<code>modp1</code>, <code>modp2</code>, <code>modp5</code>)<span><a class="mark" href="#all_deprecations_dep0167-weak-diffiehellmangroup-instances-modp1-modp2-modp5" id="all_deprecations_dep0167-weak-diffiehellmangroup-instances-modp1-modp2-modp5">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0167_weak_diffiehellmangroup_instances_modp1_modp2_modp5"></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.10.0, v16.18.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The well-known MODP groups <code>modp1</code>, <code>modp2</code>, and <code>modp5</code> are deprecated because
they are not secure against practical attacks. See <a href="https://www.rfc-editor.org/rfc/rfc8247#section-2.4">RFC 8247 Section 2.4</a> for
details.</p>
<p>These groups might be removed in future versions of Node.js. Applications that
rely on these groups should evaluate using stronger MODP groups instead.</p>
<h4 id="DEP0168">DEP0168: Unhandled exception in Node-API callbacks<span><a class="mark" href="#all_deprecations_dep0168-unhandled-exception-in-node-api-callbacks" id="all_deprecations_dep0168-unhandled-exception-in-node-api-callbacks">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0168_unhandled_exception_in_node_api_callbacks"></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.3.0, v16.17.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The implicit suppression of uncaught exceptions in Node-API callbacks is now
deprecated.</p>
<p>Set the flag <a href="#all_cli_--force-node-api-uncaught-exceptions-policy"><code>--force-node-api-uncaught-exceptions-policy</code></a> to force Node.js
to emit an <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a> event if the exception is not handled in
Node-API callbacks.</p>
<h4 id="DEP0169">DEP0169: Insecure url.parse()<span><a class="mark" href="#all_deprecations_dep0169-insecure-urlparse" id="all_deprecations_dep0169-insecure-urlparse">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0169_insecure_url_parse"></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.9.0</td>
<td><p>Added support for <code>--pending-deprecation</code>.</p></td></tr>
<tr><td>v19.0.0, v18.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p><a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a> behavior is not standardized and prone to errors that
have security implications. Use the <a href="#all_url_the-whatwg-url-api">WHATWG URL API</a> instead. CVEs are not
issued for <code>url.parse()</code> vulnerabilities.</p>
<h4 id="DEP0170">DEP0170: Invalid port when using <code>url.parse()</code><span><a class="mark" href="#all_deprecations_dep0170-invalid-port-when-using-urlparse" id="all_deprecations_dep0170-invalid-port-when-using-urlparse">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0170_invalid_port_when_using_url_parse"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a> accepts URLs with ports that are not numbers. This behavior
might result in host name spoofing with unexpected input. These URLs will throw
an error in future versions of Node.js, as the <a href="#all_url_the-whatwg-url-api">WHATWG URL API</a> does already.</p>
<h4 id="DEP0171">DEP0171: Setters for <code>http.IncomingMessage</code> headers and trailers<span><a class="mark" href="#all_deprecations_dep0171-setters-for-httpincomingmessage-headers-and-trailers" id="all_deprecations_dep0171-setters-for-httpincomingmessage-headers-and-trailers">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0171_setters_for_http_incomingmessage_headers_and_trailers"></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.3.0, v18.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>In a future version of Node.js, <a href="#all_http_messageheaders"><code>message.headers</code></a>,
<a href="#all_http_messageheadersdistinct"><code>message.headersDistinct</code></a>, <a href="#all_http_messagetrailers"><code>message.trailers</code></a>, and
<a href="#all_http_messagetrailersdistinct"><code>message.trailersDistinct</code></a> will be read-only.</p>
<h4 id="DEP0172">DEP0172: The <code>asyncResource</code> property of <code>AsyncResource</code> bound functions<span><a class="mark" href="#all_deprecations_dep0172-the-asyncresource-property-of-asyncresource-bound-functions" id="all_deprecations_dep0172-the-asyncresource-property-of-asyncresource-bound-functions">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0172_the_asyncresource_property_of_asyncresource_bound_functions"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Runtime-deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>In a future version of Node.js, the <code>asyncResource</code> property will no longer
be added when a function is bound to an <code>AsyncResource</code>.</p>
<h4 id="DEP0173">DEP0173: the <code>assert.CallTracker</code> class<span><a class="mark" href="#all_deprecations_dep0173-the-assertcalltracker-class" id="all_deprecations_dep0173-the-assertcalltracker-class">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0173_the_assert_calltracker_class"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>In a future version of Node.js, <a href="#all_assert_class-assertcalltracker"><code>assert.CallTracker</code></a>,
will be removed.
Consider using alternatives such as the <a href="#all_test_mocking"><code>mock</code></a> helper function.</p>
<h4 id="DEP0174">DEP0174: calling <code>promisify</code> on a function that returns a <code>Promise</code><span><a class="mark" href="#all_deprecations_dep0174-calling-promisify-on-a-function-that-returns-a-promise" id="all_deprecations_dep0174-calling-promisify-on-a-function-that-returns-a-promise">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0174_calling_promisify_on_a_function_that_returns_a_promise"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.8.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Calling <a href="#all_util_utilpromisifyoriginal"><code>util.promisify</code></a> on a function that returns a <promise> will ignore
the result of said promise, which can lead to unhandled promise rejections.</promise></p>
<h4 id="DEP0175">DEP0175: <code>util.toUSVString</code><span><a class="mark" href="#all_deprecations_dep0175-utiltousvstring" id="all_deprecations_dep0175-utiltousvstring">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0175_util_tousvstring"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.8.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utiltousvstringstring"><code>util.toUSVString()</code></a> API is deprecated. Please use
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toWellFormed"><code>String.prototype.toWellFormed</code></a> instead.</p>
<h4 id="DEP0176">DEP0176: <code>fs.F_OK</code>, <code>fs.R_OK</code>, <code>fs.W_OK</code>, <code>fs.X_OK</code><span><a class="mark" href="#all_deprecations_dep0176-fsf_ok-fsr_ok-fsw_ok-fsx_ok" id="all_deprecations_dep0176-fsf_ok-fsr_ok-fsw_ok-fsx_ok">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0176_fs_f_ok_fs_r_ok_fs_w_ok_fs_x_ok"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.8.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p><code>F_OK</code>, <code>R_OK</code>, <code>W_OK</code> and <code>X_OK</code> getters exposed directly on <code>node:fs</code> are
deprecated. Get them from <code>fs.constants</code> or <code>fs.promises.constants</code> instead.</p>
<h4 id="DEP0177">DEP0177: <code>util.types.isWebAssemblyCompiledModule</code><span><a class="mark" href="#all_deprecations_dep0177-utiltypesiswebassemblycompiledmodule" id="all_deprecations_dep0177-utiltypesiswebassemblycompiledmodule">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0177_util_types_iswebassemblycompiledmodule"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v20.11.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>util.types.isWebAssemblyCompiledModule</code> API has been removed.
Please use <code>value instanceof WebAssembly.Module</code> instead.</p>
<h4 id="DEP0178">DEP0178: <code>dirent.path</code><span><a class="mark" href="#all_deprecations_dep0178-direntpath" id="all_deprecations_dep0178-direntpath">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0178_dirent_path"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_fs_direntpath"><code>dirent.path</code></a> is deprecated due to its lack of consistency across
release lines. Please use <a href="#all_fs_direntparentpath"><code>dirent.parentPath</code></a> instead.</p>
<h4 id="DEP0179">DEP0179: <code>Hash</code> constructor<span><a class="mark" href="#all_deprecations_dep0179-hash-constructor" id="all_deprecations_dep0179-hash-constructor">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0179_hash_constructor"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Calling <code>Hash</code> class directly with <code>Hash()</code> or <code>new Hash()</code> is
deprecated due to being internals, not intended for public use.
Please use the <a href="#all_crypto_cryptocreatehashalgorithm-options"><code>crypto.createHash()</code></a> method to create Hash instances.</p>
<h4 id="DEP0180">DEP0180: <code>fs.Stats</code> constructor<span><a class="mark" href="#all_deprecations_dep0180-fsstats-constructor" id="all_deprecations_dep0180-fsstats-constructor">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0180_fs_stats_constructor"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Calling <code>fs.Stats</code> class directly with <code>Stats()</code> or <code>new Stats()</code> is
deprecated due to being internals, not intended for public use.</p>
<h4 id="DEP0181">DEP0181: <code>Hmac</code> constructor<span><a class="mark" href="#all_deprecations_dep0181-hmac-constructor" id="all_deprecations_dep0181-hmac-constructor">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0181_hmac_constructor"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Calling <code>Hmac</code> class directly with <code>Hmac()</code> or <code>new Hmac()</code> is
deprecated due to being internals, not intended for public use.
Please use the <a href="#all_crypto_cryptocreatehmacalgorithm-key-options"><code>crypto.createHmac()</code></a> method to create Hmac instances.</p>
<h4 id="DEP0182">DEP0182: Short GCM authentication tags without explicit <code>authTagLength</code><span><a class="mark" href="#all_deprecations_dep0182-short-gcm-authentication-tags-without-explicit-authtaglength" id="all_deprecations_dep0182-short-gcm-authentication-tags-without-explicit-authtaglength">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0182_short_gcm_authentication_tags_without_explicit_authtaglength"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p>Applications that intend to use authentication tags that are shorter than the
default authentication tag length should set the <code>authTagLength</code> option of the
<a href="#all_crypto_cryptocreatedecipherivalgorithm-key-iv-options"><code>crypto.createDecipheriv()</code></a> function to the appropriate length.</p>
<p>For ciphers in GCM mode, the <a href="#all_crypto_deciphersetauthtagbuffer-encoding"><code>decipher.setAuthTag()</code></a> function accepts
authentication tags of any valid length (see <a href="#DEP0090">DEP0090</a>). This behavior
is deprecated to better align with recommendations per <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf">NIST SP 800-38D</a>.</p>
<h4 id="DEP0183">DEP0183: OpenSSL engine-based APIs<span><a class="mark" href="#all_deprecations_dep0183-openssl-engine-based-apis" id="all_deprecations_dep0183-openssl-engine-based-apis">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0183_openssl_engine_based_apis"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>OpenSSL 3 has deprecated support for custom engines with a recommendation to
switch to its new provider model. The <code>clientCertEngine</code> option for
<code>https.request()</code>, <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>, and <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a>;
the <code>privateKeyEngine</code> and <code>privateKeyIdentifier</code> for <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>;
and <a href="#all_crypto_cryptosetengineengine-flags"><code>crypto.setEngine()</code></a> all depend on this functionality from OpenSSL.</p>
<h4 id="DEP0184">DEP0184: Instantiating <code>node:zlib</code> classes without <code>new</code><span><a class="mark" href="#all_deprecations_dep0184-instantiating-nodezlib-classes-without-new" id="all_deprecations_dep0184-instantiating-nodezlib-classes-without-new">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0184_instantiating_node_zlib_classes_without_new"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Instantiating classes without the <code>new</code> qualifier exported by the <code>node:zlib</code> module is deprecated.
It is recommended to use the <code>new</code> qualifier instead. This applies to all Zlib classes, such as <code>Deflate</code>,
<code>DeflateRaw</code>, <code>Gunzip</code>, <code>Inflate</code>, <code>InflateRaw</code>, <code>Unzip</code>, and <code>Zlib</code>.</p>
<h4 id="DEP0185">DEP0185: Instantiating <code>node:repl</code> classes without <code>new</code><span><a class="mark" href="#all_deprecations_dep0185-instantiating-noderepl-classes-without-new" id="all_deprecations_dep0185-instantiating-noderepl-classes-without-new">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0185_instantiating_node_repl_classes_without_new"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Instantiating classes without the <code>new</code> qualifier exported by the <code>node:repl</code> module is deprecated.
It is recommended to use the <code>new</code> qualifier instead. This applies to all REPL classes, including
<code>REPLServer</code> and <code>Recoverable</code>.</p></section>
</section>
<section><h2>Diagnostics Channel<span><a class="mark" href="#all_diagnostics_channel_diagnostics-channel" id="all_diagnostics_channel_diagnostics-channel">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_diagnostics_channel"></a></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p>diagnostics_channel is now Stable.</p></td></tr>
<tr><td>v15.1.0, v14.17.0</td>
<td><p><span>Added in: v15.1.0, v14.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/diagnostics_channel.js">lib/diagnostics_channel.js</a></p>
<p>The <code>node:diagnostics_channel</code> module provides an API to create named channels
to report arbitrary message data for diagnostics purposes.</p>
<p>It can be accessed using:</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);</code><button class="copy-button">copy</button></pre>
<p>It is intended that a module writer wanting to report diagnostics messages
will create one or many top-level channels to report messages through.
Channels may also be acquired at runtime but it is not encouraged
due to the additional overhead of doing so. Channels may be exported for
convenience, but as long as the name is known it can be acquired anywhere.</p>
<p>If you intend for your module to produce diagnostics data for others to
consume it is recommended that you include documentation of what named
channels are used along with the shape of the message data. Channel names
should generally include the module name to avoid collisions with data from
other modules.</p>
<section><h3>Public API<span><a class="mark" href="#all_diagnostics_channel_public-api" id="all_diagnostics_channel_public-api">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_public_api"></a></h3>
<h4>Overview<span><a class="mark" href="#all_diagnostics_channel_overview" id="all_diagnostics_channel_overview">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_overview"></a></h4>
<p>Following is a simple overview of the public API.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-comment">// Get a reusable channel object</span>
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">onMessage</span>(<span class="hljs-params">message, name</span>) {
<span class="hljs-comment">// Received data</span>
}
<span class="hljs-comment">// Subscribe to the channel</span>
diagnostics_channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);
<span class="hljs-comment">// Check if the channel has an active subscriber</span>
<span class="hljs-keyword">if</span> (channel.<span class="hljs-property">hasSubscribers</span>) {
<span class="hljs-comment">// Publish data to the channel</span>
channel.<span class="hljs-title function_">publish</span>({
<span class="hljs-attr">some</span>: <span class="hljs-string">'data'</span>,
});
}
<span class="hljs-comment">// Unsubscribe from the channel</span>
diagnostics_channel.<span class="hljs-title function_">unsubscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-comment">// Get a reusable channel object</span>
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">onMessage</span>(<span class="hljs-params">message, name</span>) {
<span class="hljs-comment">// Received data</span>
}
<span class="hljs-comment">// Subscribe to the channel</span>
diagnostics_channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);
<span class="hljs-comment">// Check if the channel has an active subscriber</span>
<span class="hljs-keyword">if</span> (channel.<span class="hljs-property">hasSubscribers</span>) {
<span class="hljs-comment">// Publish data to the channel</span>
channel.<span class="hljs-title function_">publish</span>({
<span class="hljs-attr">some</span>: <span class="hljs-string">'data'</span>,
});
}
<span class="hljs-comment">// Unsubscribe from the channel</span>
diagnostics_channel.<span class="hljs-title function_">unsubscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);</code><button class="copy-button">copy</button></pre>
<h5><code>diagnostics_channel.hasSubscribers(name)</code><span><a class="mark" href="#all_diagnostics_channel_diagnostics_channelhassubscribersname" id="all_diagnostics_channel_diagnostics_channelhassubscribersname">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_diagnostics_channel_hassubscribers_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<ul>
<li><code>name</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#Symbol_type" class="type"><symbol></a> The channel name</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If there are active subscribers</li>
</ul>
<p>Check if there are active subscribers to the named channel. This is helpful if
the message you want to send might be expensive to prepare.</p>
<p>This API is optional but helpful when trying to publish messages from very
performance-sensitive code.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">if</span> (diagnostics_channel.<span class="hljs-title function_">hasSubscribers</span>(<span class="hljs-string">'my-channel'</span>)) {
<span class="hljs-comment">// There are subscribers, prepare and publish message</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">if</span> (diagnostics_channel.<span class="hljs-title function_">hasSubscribers</span>(<span class="hljs-string">'my-channel'</span>)) {
<span class="hljs-comment">// There are subscribers, prepare and publish message</span>
}</code><button class="copy-button">copy</button></pre>
<h5><code>diagnostics_channel.channel(name)</code><span><a class="mark" href="#all_diagnostics_channel_diagnostics_channelchannelname" id="all_diagnostics_channel_diagnostics_channelchannelname">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_diagnostics_channel_channel_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<ul>
<li><code>name</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#Symbol_type" class="type"><symbol></a> The channel name</li>
<li>Returns: <a href="#all_diagnostics_channel_class-channel" class="type"><Channel></a> The named channel object</li>
</ul>
<p>This is the primary entry-point for anyone wanting to publish to a named
channel. It produces a channel object which is optimized to reduce overhead at
publish time as much as possible.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);</code><button class="copy-button">copy</button></pre>
<h5><code>diagnostics_channel.subscribe(name, onMessage)</code><span><a class="mark" href="#all_diagnostics_channel_diagnostics_channelsubscribename-onmessage" id="all_diagnostics_channel_diagnostics_channelsubscribename-onmessage">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_diagnostics_channel_subscribe_name_onmessage"></a></h5>
<div class="api_metadata">
<span>Added in: v18.7.0, v16.17.0</span>
</div>
<ul>
<li><code>name</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#Symbol_type" class="type"><symbol></a> The channel name</li>
<li><code>onMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The handler to receive channel messages
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The message data</li>
<li><code>name</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#Symbol_type" class="type"><symbol></a> The name of the channel</li>
</ul>
</li>
</ul>
<p>Register a message handler to subscribe to this channel. This message handler
will be run synchronously whenever a message is published to the channel. Any
errors thrown in the message handler will trigger an <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a>.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
diagnostics_channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-string">'my-channel'</span>, <span class="hljs-function">(<span class="hljs-params">message, name</span>) =></span> {
<span class="hljs-comment">// Received data</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
diagnostics_channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-string">'my-channel'</span>, <span class="hljs-function">(<span class="hljs-params">message, name</span>) =></span> {
<span class="hljs-comment">// Received data</span>
});</code><button class="copy-button">copy</button></pre>
<h5><code>diagnostics_channel.unsubscribe(name, onMessage)</code><span><a class="mark" href="#all_diagnostics_channel_diagnostics_channelunsubscribename-onmessage" id="all_diagnostics_channel_diagnostics_channelunsubscribename-onmessage">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_diagnostics_channel_unsubscribe_name_onmessage"></a></h5>
<div class="api_metadata">
<span>Added in: v18.7.0, v16.17.0</span>
</div>
<ul>
<li><code>name</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#Symbol_type" class="type"><symbol></a> The channel name</li>
<li><code>onMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The previous subscribed handler to remove</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 the handler was found, <code>false</code> otherwise.</li>
</ul>
<p>Remove a message handler previously registered to this channel with
<a href="#all_diagnostics_channel_diagnostics_channelsubscribename-onmessage"><code>diagnostics_channel.subscribe(name, onMessage)</code></a>.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">onMessage</span>(<span class="hljs-params">message, name</span>) {
<span class="hljs-comment">// Received data</span>
}
diagnostics_channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);
diagnostics_channel.<span class="hljs-title function_">unsubscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">onMessage</span>(<span class="hljs-params">message, name</span>) {
<span class="hljs-comment">// Received data</span>
}
diagnostics_channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);
diagnostics_channel.<span class="hljs-title function_">unsubscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);</code><button class="copy-button">copy</button></pre>
<h5><code>diagnostics_channel.tracingChannel(nameOrChannels)</code><span><a class="mark" href="#all_diagnostics_channel_diagnostics_channeltracingchannelnameorchannels" id="all_diagnostics_channel_diagnostics_channeltracingchannelnameorchannels">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_diagnostics_channel_tracingchannel_nameorchannels"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>nameOrChannels</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_diagnostics_channel_class-tracingchannel" class="type"><TracingChannel></a> Channel name or
object containing all the <a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a></li>
<li>Returns: <a href="#all_diagnostics_channel_class-tracingchannel" class="type"><TracingChannel></a> Collection of channels to trace with</li>
</ul>
<p>Creates a <a href="#all_diagnostics_channel_class-tracingchannel"><code>TracingChannel</code></a> wrapper for the given
<a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a>. If a name is given, the corresponding tracing
channels will be created in the form of <code>tracing:${name}:${eventType}</code> where
<code>eventType</code> corresponds to the types of <a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a>.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">const</span> channelsByName = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-comment">// or...</span>
<span class="hljs-keyword">const</span> channelsByCollection = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>({
<span class="hljs-attr">start</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:start'</span>),
<span class="hljs-attr">end</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:end'</span>),
<span class="hljs-attr">asyncStart</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:asyncStart'</span>),
<span class="hljs-attr">asyncEnd</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:asyncEnd'</span>),
<span class="hljs-attr">error</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:error'</span>),
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> channelsByName = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-comment">// or...</span>
<span class="hljs-keyword">const</span> channelsByCollection = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>({
<span class="hljs-attr">start</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:start'</span>),
<span class="hljs-attr">end</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:end'</span>),
<span class="hljs-attr">asyncStart</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:asyncStart'</span>),
<span class="hljs-attr">asyncEnd</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:asyncEnd'</span>),
<span class="hljs-attr">error</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:error'</span>),
});</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>Channel</code><span><a class="mark" href="#all_diagnostics_channel_class-channel" id="all_diagnostics_channel_class-channel">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_class_channel"></a></h4>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<p>The class <code>Channel</code> represents an individual named channel within the data
pipeline. It is used to track subscribers and to publish messages when there
are subscribers present. It exists as a separate object to avoid channel
lookups at publish time, enabling very fast publish speeds and allowing
for heavy use while incurring very minimal cost. Channels are created with
<a href="#all_diagnostics_channel_diagnostics_channelchannelname"><code>diagnostics_channel.channel(name)</code></a>, constructing a channel directly
with <code>new Channel(name)</code> is not supported.</p>
<h5><code>channel.hasSubscribers</code><span><a class="mark" href="#all_diagnostics_channel_channelhassubscribers" id="all_diagnostics_channel_channelhassubscribers">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_hassubscribers"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If there are active subscribers</li>
</ul>
<p>Check if there are active subscribers to this channel. This is helpful if
the message you want to send might be expensive to prepare.</p>
<p>This API is optional but helpful when trying to publish messages from very
performance-sensitive code.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-keyword">if</span> (channel.<span class="hljs-property">hasSubscribers</span>) {
<span class="hljs-comment">// There are subscribers, prepare and publish message</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-keyword">if</span> (channel.<span class="hljs-property">hasSubscribers</span>) {
<span class="hljs-comment">// There are subscribers, prepare and publish message</span>
}</code><button class="copy-button">copy</button></pre>
<h5><code>channel.publish(message)</code><span><a class="mark" href="#all_diagnostics_channel_channelpublishmessage" id="all_diagnostics_channel_channelpublishmessage">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_publish_message"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The message to send to the channel subscribers</li>
</ul>
<p>Publish a message to any subscribers to the channel. This will trigger
message handlers synchronously so they will execute within the same context.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
channel.<span class="hljs-title function_">publish</span>({
<span class="hljs-attr">some</span>: <span class="hljs-string">'message'</span>,
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
channel.<span class="hljs-title function_">publish</span>({
<span class="hljs-attr">some</span>: <span class="hljs-string">'message'</span>,
});</code><button class="copy-button">copy</button></pre>
<h5><code>channel.subscribe(onMessage)</code><span><a class="mark" href="#all_diagnostics_channel_channelsubscribeonmessage" id="all_diagnostics_channel_channelsubscribeonmessage">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_subscribe_onmessage"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span><span>Deprecated since: v18.7.0, v16.17.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_diagnostics_channel_diagnostics_channelsubscribename-onmessage"><code>diagnostics_channel.subscribe(name, onMessage)</code></a></div><p></p>
<ul>
<li><code>onMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The handler to receive channel messages
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The message data</li>
<li><code>name</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#Symbol_type" class="type"><symbol></a> The name of the channel</li>
</ul>
</li>
</ul>
<p>Register a message handler to subscribe to this channel. This message handler
will be run synchronously whenever a message is published to the channel. Any
errors thrown in the message handler will trigger an <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a>.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-function">(<span class="hljs-params">message, name</span>) =></span> {
<span class="hljs-comment">// Received data</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-function">(<span class="hljs-params">message, name</span>) =></span> {
<span class="hljs-comment">// Received data</span>
});</code><button class="copy-button">copy</button></pre>
<h5><code>channel.unsubscribe(onMessage)</code><span><a class="mark" href="#all_diagnostics_channel_channelunsubscribeonmessage" id="all_diagnostics_channel_channelunsubscribeonmessage">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_unsubscribe_onmessage"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p><span>Deprecated since: v18.7.0, v16.17.0</span></p></td></tr>
<tr><td>v17.1.0, v16.14.0, v14.19.0</td>
<td><p>Added return value. Added to channels without subscribers.</p></td></tr>
<tr><td>v15.1.0, v14.17.0</td>
<td><p><span>Added in: v15.1.0, v14.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_diagnostics_channel_diagnostics_channelunsubscribename-onmessage"><code>diagnostics_channel.unsubscribe(name, onMessage)</code></a></div><p></p>
<ul>
<li><code>onMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The previous subscribed handler to remove</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 the handler was found, <code>false</code> otherwise.</li>
</ul>
<p>Remove a message handler previously registered to this channel with
<a href="#all_diagnostics_channel_channelsubscribeonmessage"><code>channel.subscribe(onMessage)</code></a>.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">onMessage</span>(<span class="hljs-params">message, name</span>) {
<span class="hljs-comment">// Received data</span>
}
channel.<span class="hljs-title function_">subscribe</span>(onMessage);
channel.<span class="hljs-title function_">unsubscribe</span>(onMessage);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">onMessage</span>(<span class="hljs-params">message, name</span>) {
<span class="hljs-comment">// Received data</span>
}
channel.<span class="hljs-title function_">subscribe</span>(onMessage);
channel.<span class="hljs-title function_">unsubscribe</span>(onMessage);</code><button class="copy-button">copy</button></pre>
<h5><code>channel.bindStore(store[, transform])</code><span><a class="mark" href="#all_diagnostics_channel_channelbindstorestore-transform" id="all_diagnostics_channel_channelbindstorestore-transform">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_bindstore_store_transform"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>store</code> <a href="#all_async_context_class-asynclocalstorage" class="type"><AsyncLocalStorage></a> The store to which to bind the context data</li>
<li><code>transform</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Transform context data before setting the store context</li>
</ul>
<p>When <a href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args"><code>channel.runStores(context, ...)</code></a> is called, the given context data
will be applied to any store bound to the channel. If the store has already been
bound the previous <code>transform</code> function will be replaced with the new one.
The <code>transform</code> function may be omitted to set the given context data as the
context directly.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
channel.<span class="hljs-title function_">bindStore</span>(store, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-keyword">return</span> { data };
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
channel.<span class="hljs-title function_">bindStore</span>(store, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-keyword">return</span> { data };
});</code><button class="copy-button">copy</button></pre>
<h5><code>channel.unbindStore(store)</code><span><a class="mark" href="#all_diagnostics_channel_channelunbindstorestore" id="all_diagnostics_channel_channelunbindstorestore">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_unbindstore_store"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>store</code> <a href="#all_async_context_class-asynclocalstorage" class="type"><AsyncLocalStorage></a> The store to unbind from the channel.</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 the store was found, <code>false</code> otherwise.</li>
</ul>
<p>Remove a message handler previously registered to this channel with
<a href="#all_diagnostics_channel_channelbindstorestore-transform"><code>channel.bindStore(store)</code></a>.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
channel.<span class="hljs-title function_">bindStore</span>(store);
channel.<span class="hljs-title function_">unbindStore</span>(store);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
channel.<span class="hljs-title function_">bindStore</span>(store);
channel.<span class="hljs-title function_">unbindStore</span>(store);</code><button class="copy-button">copy</button></pre>
<h5><code>channel.runStores(context, fn[, thisArg[, ...args]])</code><span><a class="mark" href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args" id="all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_runstores_context_fn_thisarg_args"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Message to send to subscribers and bind to stores</li>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Handler to run within the entered storage context</li>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The receiver to be used for the function call.</li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional arguments to pass to the function.</li>
</ul>
<p>Applies the given data to any AsyncLocalStorage instances bound to the channel
for the duration of the given function, then publishes to the channel within
the scope of that data is applied to the stores.</p>
<p>If a transform function was given to <a href="#all_diagnostics_channel_channelbindstorestore-transform"><code>channel.bindStore(store)</code></a> it will be
applied to transform the message data before it becomes the context value for
the store. The prior storage context is accessible from within the transform
function in cases where context linking is required.</p>
<p>The context applied to the store should be accessible in any async code which
continues from execution which began during the given function, however
there are some situations in which <a href="#all_async_context_troubleshooting-context-loss">context loss</a> may occur.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
channel.<span class="hljs-title function_">bindStore</span>(store, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
<span class="hljs-keyword">const</span> parent = store.<span class="hljs-title function_">getStore</span>();
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Span</span>(message, parent);
});
channel.<span class="hljs-title function_">runStores</span>({ <span class="hljs-attr">some</span>: <span class="hljs-string">'message'</span> }, <span class="hljs-function">() =></span> {
store.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Span({ some: 'message' })</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);
channel.<span class="hljs-title function_">bindStore</span>(store, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
<span class="hljs-keyword">const</span> parent = store.<span class="hljs-title function_">getStore</span>();
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Span</span>(message, parent);
});
channel.<span class="hljs-title function_">runStores</span>({ <span class="hljs-attr">some</span>: <span class="hljs-string">'message'</span> }, <span class="hljs-function">() =></span> {
store.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Span({ some: 'message' })</span>
});</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>TracingChannel</code><span><a class="mark" href="#all_diagnostics_channel_class-tracingchannel" id="all_diagnostics_channel_class-tracingchannel">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_class_tracingchannel"></a></h4>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>The class <code>TracingChannel</code> is a collection of <a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a> which
together express a single traceable action. It is used to formalize and
simplify the process of producing events for tracing application flow.
<a href="#all_diagnostics_channel_diagnostics_channeltracingchannelnameorchannels"><code>diagnostics_channel.tracingChannel()</code></a> is used to construct a
<code>TracingChannel</code>. As with <code>Channel</code> it is recommended to create and reuse a
single <code>TracingChannel</code> at the top-level of the file rather than creating them
dynamically.</p>
<h5><code>tracingChannel.subscribe(subscribers)</code><span><a class="mark" href="#all_diagnostics_channel_tracingchannelsubscribesubscribers" id="all_diagnostics_channel_tracingchannelsubscribesubscribers">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_subscribe_subscribers"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>subscribers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Set of <a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a> subscribers
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_diagnostics_channel_startevent"><code>start</code> event</a> subscriber</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_diagnostics_channel_endevent"><code>end</code> event</a> subscriber</li>
<li><code>asyncStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_diagnostics_channel_asyncstartevent"><code>asyncStart</code> event</a> subscriber</li>
<li><code>asyncEnd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_diagnostics_channel_asyncendevent"><code>asyncEnd</code> event</a> subscriber</li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_diagnostics_channel_errorevent"><code>error</code> event</a> subscriber</li>
</ul>
</li>
</ul>
<p>Helper to subscribe a collection of functions to the corresponding channels.
This is the same as calling <a href="#all_diagnostics_channel_channelsubscribeonmessage"><code>channel.subscribe(onMessage)</code></a> on each channel
individually.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
channels.<span class="hljs-title function_">subscribe</span>({
<span class="hljs-title function_">start</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle start message</span>
},
<span class="hljs-title function_">end</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle end message</span>
},
<span class="hljs-title function_">asyncStart</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle asyncStart message</span>
},
<span class="hljs-title function_">asyncEnd</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle asyncEnd message</span>
},
<span class="hljs-title function_">error</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle error message</span>
},
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
channels.<span class="hljs-title function_">subscribe</span>({
<span class="hljs-title function_">start</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle start message</span>
},
<span class="hljs-title function_">end</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle end message</span>
},
<span class="hljs-title function_">asyncStart</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle asyncStart message</span>
},
<span class="hljs-title function_">asyncEnd</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle asyncEnd message</span>
},
<span class="hljs-title function_">error</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle error message</span>
},
});</code><button class="copy-button">copy</button></pre>
<h5><code>tracingChannel.unsubscribe(subscribers)</code><span><a class="mark" href="#all_diagnostics_channel_tracingchannelunsubscribesubscribers" id="all_diagnostics_channel_tracingchannelunsubscribesubscribers">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_unsubscribe_subscribers"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>subscribers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Set of <a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a> subscribers
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_diagnostics_channel_startevent"><code>start</code> event</a> subscriber</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_diagnostics_channel_endevent"><code>end</code> event</a> subscriber</li>
<li><code>asyncStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_diagnostics_channel_asyncstartevent"><code>asyncStart</code> event</a> subscriber</li>
<li><code>asyncEnd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_diagnostics_channel_asyncendevent"><code>asyncEnd</code> event</a> subscriber</li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_diagnostics_channel_errorevent"><code>error</code> event</a> subscriber</li>
</ul>
</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 all handlers were successfully unsubscribed,
and <code>false</code> otherwise.</li>
</ul>
<p>Helper to unsubscribe a collection of functions from the corresponding channels.
This is the same as calling <a href="#all_diagnostics_channel_channelunsubscribeonmessage"><code>channel.unsubscribe(onMessage)</code></a> on each channel
individually.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
channels.<span class="hljs-title function_">unsubscribe</span>({
<span class="hljs-title function_">start</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle start message</span>
},
<span class="hljs-title function_">end</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle end message</span>
},
<span class="hljs-title function_">asyncStart</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle asyncStart message</span>
},
<span class="hljs-title function_">asyncEnd</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle asyncEnd message</span>
},
<span class="hljs-title function_">error</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle error message</span>
},
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
channels.<span class="hljs-title function_">unsubscribe</span>({
<span class="hljs-title function_">start</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle start message</span>
},
<span class="hljs-title function_">end</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle end message</span>
},
<span class="hljs-title function_">asyncStart</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle asyncStart message</span>
},
<span class="hljs-title function_">asyncEnd</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle asyncEnd message</span>
},
<span class="hljs-title function_">error</span>(<span class="hljs-params">message</span>) {
<span class="hljs-comment">// Handle error message</span>
},
});</code><button class="copy-button">copy</button></pre>
<h5><code>tracingChannel.traceSync(fn[, context[, thisArg[, ...args]]])</code><span><a class="mark" href="#all_diagnostics_channel_tracingchanneltracesyncfn-context-thisarg-args" id="all_diagnostics_channel_tracingchanneltracesyncfn-context-thisarg-args">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_tracesync_fn_context_thisarg_args"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_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> Function to wrap a trace around</li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Shared object to correlate events through</li>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The receiver to be used for the function call</li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional arguments to pass to the function</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The return value of the given function</li>
</ul>
<p>Trace a synchronous function call. This will always produce a <a href="#all_diagnostics_channel_startevent"><code>start</code> event</a>
and <a href="#all_diagnostics_channel_endevent"><code>end</code> event</a> around the execution and may produce an <a href="#all_diagnostics_channel_errorevent"><code>error</code> event</a>
if the given function throws an error. This will run the given function using
<a href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args"><code>channel.runStores(context, ...)</code></a> on the <code>start</code> channel which ensures all
events should have any bound stores set to match this trace context.</p>
<p>To ensure only correct trace graphs are formed, events will only be published
if subscribers are present prior to starting the trace. Subscriptions which are
added after the trace begins will not receive future events from that trace,
only future traces will be seen.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
channels.<span class="hljs-title function_">traceSync</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// Do something</span>
}, {
<span class="hljs-attr">some</span>: <span class="hljs-string">'thing'</span>,
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
channels.<span class="hljs-title function_">traceSync</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// Do something</span>
}, {
<span class="hljs-attr">some</span>: <span class="hljs-string">'thing'</span>,
});</code><button class="copy-button">copy</button></pre>
<h5><code>tracingChannel.tracePromise(fn[, context[, thisArg[, ...args]]])</code><span><a class="mark" href="#all_diagnostics_channel_tracingchanneltracepromisefn-context-thisarg-args" id="all_diagnostics_channel_tracingchanneltracepromisefn-context-thisarg-args">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_tracepromise_fn_context_thisarg_args"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_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> Promise-returning function to wrap a trace around</li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Shared object to correlate trace events through</li>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The receiver to be used for the function call</li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional arguments to pass to the function</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Chained from promise returned by the given function</li>
</ul>
<p>Trace a promise-returning function call. This will always produce a
<a href="#all_diagnostics_channel_startevent"><code>start</code> event</a> and <a href="#all_diagnostics_channel_endevent"><code>end</code> event</a> around the synchronous portion of the
function execution, and will produce an <a href="#all_diagnostics_channel_asyncstartevent"><code>asyncStart</code> event</a> and
<a href="#all_diagnostics_channel_asyncendevent"><code>asyncEnd</code> event</a> when a promise continuation is reached. It may also
produce an <a href="#all_diagnostics_channel_errorevent"><code>error</code> event</a> if the given function throws an error or the
returned promise rejects. This will run the given function using
<a href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args"><code>channel.runStores(context, ...)</code></a> on the <code>start</code> channel which ensures all
events should have any bound stores set to match this trace context.</p>
<p>To ensure only correct trace graphs are formed, events will only be published
if subscribers are present prior to starting the trace. Subscriptions which are
added after the trace begins will not receive future events from that trace,
only future traces will be seen.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
channels.<span class="hljs-title function_">tracePromise</span>(<span class="hljs-title function_">async</span> () => {
<span class="hljs-comment">// Do something</span>
}, {
<span class="hljs-attr">some</span>: <span class="hljs-string">'thing'</span>,
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
channels.<span class="hljs-title function_">tracePromise</span>(<span class="hljs-title function_">async</span> () => {
<span class="hljs-comment">// Do something</span>
}, {
<span class="hljs-attr">some</span>: <span class="hljs-string">'thing'</span>,
});</code><button class="copy-button">copy</button></pre>
<h5><code>tracingChannel.traceCallback(fn[, position[, context[, thisArg[, ...args]]]])</code><span><a class="mark" href="#all_diagnostics_channel_tracingchanneltracecallbackfn-position-context-thisarg-args" id="all_diagnostics_channel_tracingchanneltracecallbackfn-position-context-thisarg-args">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_tracecallback_fn_position_context_thisarg_args"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_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> callback using function to wrap a trace around</li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Zero-indexed argument position of expected callback
(defaults to last argument if <code>undefined</code> is passed)</li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Shared object to correlate trace events through (defaults
to <code>{}</code> if <code>undefined</code> is passed)</li>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The receiver to be used for the function call</li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> arguments to pass to the function (must include the callback)</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The return value of the given function</li>
</ul>
<p>Trace a callback-receiving function call. The callback is expected to follow
the error as first arg convention typically used. This will always produce a
<a href="#all_diagnostics_channel_startevent"><code>start</code> event</a> and <a href="#all_diagnostics_channel_endevent"><code>end</code> event</a> around the synchronous portion of the
function execution, and will produce a <a href="#all_diagnostics_channel_asyncstartevent"><code>asyncStart</code> event</a> and
<a href="#all_diagnostics_channel_asyncendevent"><code>asyncEnd</code> event</a> around the callback execution. It may also produce an
<a href="#all_diagnostics_channel_errorevent"><code>error</code> event</a> if the given function throws or the first argument passed to
the callback is set. This will run the given function using
<a href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args"><code>channel.runStores(context, ...)</code></a> on the <code>start</code> channel which ensures all
events should have any bound stores set to match this trace context.</p>
<p>To ensure only correct trace graphs are formed, events will only be published
if subscribers are present prior to starting the trace. Subscriptions which are
added after the trace begins will not receive future events from that trace,
only future traces will be seen.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
channels.<span class="hljs-title function_">traceCallback</span>(<span class="hljs-function">(<span class="hljs-params">arg1, callback</span>) =></span> {
<span class="hljs-comment">// Do something</span>
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'result'</span>);
}, <span class="hljs-number">1</span>, {
<span class="hljs-attr">some</span>: <span class="hljs-string">'thing'</span>,
}, thisArg, arg1, callback);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
channels.<span class="hljs-title function_">traceCallback</span>(<span class="hljs-function">(<span class="hljs-params">arg1, callback</span>) =></span> {
<span class="hljs-comment">// Do something</span>
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'result'</span>);
}, <span class="hljs-number">1</span>, {
<span class="hljs-attr">some</span>: <span class="hljs-string">'thing'</span>,
}, thisArg, arg1, callback);</code><button class="copy-button">copy</button></pre>
<p>The callback will also be run with <a href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args"><code>channel.runStores(context, ...)</code></a> which
enables context loss recovery in some cases.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-keyword">const</span> myStore = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
<span class="hljs-comment">// The start channel sets the initial store data to something</span>
<span class="hljs-comment">// and stores that store data value on the trace context object</span>
channels.<span class="hljs-property">start</span>.<span class="hljs-title function_">bindStore</span>(myStore, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-keyword">const</span> span = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Span</span>(data);
data.<span class="hljs-property">span</span> = span;
<span class="hljs-keyword">return</span> span;
});
<span class="hljs-comment">// Then asyncStart can restore from that data it stored previously</span>
channels.<span class="hljs-property">asyncStart</span>.<span class="hljs-title function_">bindStore</span>(myStore, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-keyword">return</span> data.<span class="hljs-property">span</span>;
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-keyword">const</span> myStore = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
<span class="hljs-comment">// The start channel sets the initial store data to something</span>
<span class="hljs-comment">// and stores that store data value on the trace context object</span>
channels.<span class="hljs-property">start</span>.<span class="hljs-title function_">bindStore</span>(myStore, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-keyword">const</span> span = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Span</span>(data);
data.<span class="hljs-property">span</span> = span;
<span class="hljs-keyword">return</span> span;
});
<span class="hljs-comment">// Then asyncStart can restore from that data it stored previously</span>
channels.<span class="hljs-property">asyncStart</span>.<span class="hljs-title function_">bindStore</span>(myStore, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-keyword">return</span> data.<span class="hljs-property">span</span>;
});</code><button class="copy-button">copy</button></pre>
<h5><code>tracingChannel.hasSubscribers</code><span><a class="mark" href="#all_diagnostics_channel_tracingchannelhassubscribers" id="all_diagnostics_channel_tracingchannelhassubscribers">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_hassubscribers"></a></h5>
<div class="api_metadata">
<span>Added in: v22.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<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 any of the individual channels has a subscriber,
<code>false</code> if not.</li>
</ul>
<p>This is a helper method available on a <a href="#all_diagnostics_channel_class-tracingchannel"><code>TracingChannel</code></a> instance to check if
any of the <a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a> have subscribers. A <code>true</code> is returned if
any of them have at least one subscriber, a <code>false</code> is returned otherwise.</p>
<pre class="with-64-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> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-keyword">if</span> (channels.<span class="hljs-property">hasSubscribers</span>) {
<span class="hljs-comment">// Do something</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-keyword">if</span> (channels.<span class="hljs-property">hasSubscribers</span>) {
<span class="hljs-comment">// Do something</span>
}</code><button class="copy-button">copy</button></pre>
<h4>TracingChannel Channels<span><a class="mark" href="#all_diagnostics_channel_tracingchannel-channels" id="all_diagnostics_channel_tracingchannel-channels">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_channels"></a></h4>
<p>A TracingChannel is a collection of several diagnostics_channels representing
specific points in the execution lifecycle of a single traceable action. The
behavior is split into five diagnostics_channels consisting of <code>start</code>,
<code>end</code>, <code>asyncStart</code>, <code>asyncEnd</code>, and <code>error</code>. A single traceable action will
share the same event object between all events, this can be helpful for
managing correlation through a weakmap.</p>
<p>These event objects will be extended with <code>result</code> or <code>error</code> values when
the task "completes". In the case of a synchronous task the <code>result</code> will be
the return value and the <code>error</code> will be anything thrown from the function.
With callback-based async functions the <code>result</code> will be the second argument
of the callback while the <code>error</code> will either be a thrown error visible in the
<code>end</code> event or the first callback argument in either of the <code>asyncStart</code> or
<code>asyncEnd</code> events.</p>
<p>To ensure only correct trace graphs are formed, events should only be published
if subscribers are present prior to starting the trace. Subscriptions which are
added after the trace begins should not receive future events from that trace,
only future traces will be seen.</p>
<p>Tracing channels should follow a naming pattern of:</p>
<ul>
<li><code>tracing:module.class.method:start</code> or <code>tracing:module.function:start</code></li>
<li><code>tracing:module.class.method:end</code> or <code>tracing:module.function:end</code></li>
<li><code>tracing:module.class.method:asyncStart</code> or <code>tracing:module.function:asyncStart</code></li>
<li><code>tracing:module.class.method:asyncEnd</code> or <code>tracing:module.function:asyncEnd</code></li>
<li><code>tracing:module.class.method:error</code> or <code>tracing:module.function:error</code></li>
</ul>
<h5><code>start(event)</code><span><a class="mark" href="#all_diagnostics_channel_startevent" id="all_diagnostics_channel_startevent">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_start_event"></a></h5>
<ul>
<li>Name: <code>tracing:${name}:start</code></li>
</ul>
<p>The <code>start</code> event represents the point at which a function is called. At this
point the event data may contain function arguments or anything else available
at the very start of the execution of the function.</p>
<h5><code>end(event)</code><span><a class="mark" href="#all_diagnostics_channel_endevent" id="all_diagnostics_channel_endevent">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_end_event"></a></h5>
<ul>
<li>Name: <code>tracing:${name}:end</code></li>
</ul>
<p>The <code>end</code> event represents the point at which a function call returns a value.
In the case of an async function this is when the promise returned not when the
function itself makes a return statement internally. At this point, if the
traced function was synchronous the <code>result</code> field will be set to the return
value of the function. Alternatively, the <code>error</code> field may be present to
represent any thrown errors.</p>
<p>It is recommended to listen specifically to the <code>error</code> event to track errors
as it may be possible for a traceable action to produce multiple errors. For
example, an async task which fails may be started internally before the sync
part of the task then throws an error.</p>
<h5><code>asyncStart(event)</code><span><a class="mark" href="#all_diagnostics_channel_asyncstartevent" id="all_diagnostics_channel_asyncstartevent">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_asyncstart_event"></a></h5>
<ul>
<li>Name: <code>tracing:${name}:asyncStart</code></li>
</ul>
<p>The <code>asyncStart</code> event represents the callback or continuation of a traceable
function being reached. At this point things like callback arguments may be
available, or anything else expressing the "result" of the action.</p>
<p>For callbacks-based functions, the first argument of the callback will be
assigned to the <code>error</code> field, if not <code>undefined</code> or <code>null</code>, and the second
argument will be assigned to the <code>result</code> field.</p>
<p>For promises, the argument to the <code>resolve</code> path will be assigned to <code>result</code>
or the argument to the <code>reject</code> path will be assign to <code>error</code>.</p>
<p>It is recommended to listen specifically to the <code>error</code> event to track errors
as it may be possible for a traceable action to produce multiple errors. For
example, an async task which fails may be started internally before the sync
part of the task then throws an error.</p>
<h5><code>asyncEnd(event)</code><span><a class="mark" href="#all_diagnostics_channel_asyncendevent" id="all_diagnostics_channel_asyncendevent">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_asyncend_event"></a></h5>
<ul>
<li>Name: <code>tracing:${name}:asyncEnd</code></li>
</ul>
<p>The <code>asyncEnd</code> event represents the callback of an asynchronous function
returning. It's not likely event data will change after the <code>asyncStart</code> event,
however it may be useful to see the point where the callback completes.</p>
<h5><code>error(event)</code><span><a class="mark" href="#all_diagnostics_channel_errorevent" id="all_diagnostics_channel_errorevent">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_error_event"></a></h5>
<ul>
<li>Name: <code>tracing:${name}:error</code></li>
</ul>
<p>The <code>error</code> event represents any error produced by the traceable function
either synchronously or asynchronously. If an error is thrown in the
synchronous portion of the traced function the error will be assigned to the
<code>error</code> field of the event and the <code>error</code> event will be triggered. If an error
is received asynchronously through a callback or promise rejection it will also
be assigned to the <code>error</code> field of the event and trigger the <code>error</code> event.</p>
<p>It is possible for a single traceable function call to produce errors multiple
times so this should be considered when consuming this event. For example, if
another async task is triggered internally which fails and then the sync part
of the function then throws and error two <code>error</code> events will be emitted, one
for the sync error and one for the async error.</p>
<h4>Built-in Channels<span><a class="mark" href="#all_diagnostics_channel_built-in-channels" id="all_diagnostics_channel_built-in-channels">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_built_in_channels"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>While the diagnostics_channel API is now considered stable, the built-in
channels currently available are not. Each channel must be declared stable
independently.</p>
<h5>HTTP<span><a class="mark" href="#all_diagnostics_channel_http" id="all_diagnostics_channel_http">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_http"></a></h5>
<p><code>http.client.request.start</code></p>
<ul>
<li><code>request</code> <a href="#all_http_class-httpclientrequest" class="type"><http.ClientRequest></a></li>
</ul>
<p>Emitted when client starts a request.</p>
<p><code>http.client.request.error</code></p>
<ul>
<li><code>request</code> <a href="#all_http_class-httpclientrequest" class="type"><http.ClientRequest></a></li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>Emitted when an error occurs during a client request.</p>
<p><code>http.client.response.finish</code></p>
<ul>
<li><code>request</code> <a href="#all_http_class-httpclientrequest" class="type"><http.ClientRequest></a></li>
<li><code>response</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a></li>
</ul>
<p>Emitted when client receives a response.</p>
<p><code>http.server.request.start</code></p>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a></li>
<li><code>response</code> <a href="#all_http_class-httpserverresponse" class="type"><http.ServerResponse></a></li>
<li><code>socket</code> <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
<li><code>server</code> <a href="#all_http_class-httpserver" class="type"><http.Server></a></li>
</ul>
<p>Emitted when server receives a request.</p>
<p><code>http.server.response.finish</code></p>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a></li>
<li><code>response</code> <a href="#all_http_class-httpserverresponse" class="type"><http.ServerResponse></a></li>
<li><code>socket</code> <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
<li><code>server</code> <a href="#all_http_class-httpserver" class="type"><http.Server></a></li>
</ul>
<p>Emitted when server sends a response.</p>
<h5>NET<span><a class="mark" href="#all_diagnostics_channel_net" id="all_diagnostics_channel_net">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_net"></a></h5>
<p><code>net.client.socket</code></p>
<ul>
<li><code>socket</code> <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
</ul>
<p>Emitted when a new TCP or pipe client socket is created.</p>
<p><code>net.server.socket</code></p>
<ul>
<li><code>socket</code> <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
</ul>
<p>Emitted when a new TCP or pipe connection is received.</p>
<p><code>tracing:net.server.listen:asyncStart</code></p>
<ul>
<li><code>server</code> <a href="#all_net_class-netserver" class="type"><net.Server></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></li>
</ul>
<p>Emitted when <a href="#all_net_serverlisten"><code>net.Server.listen()</code></a> is invoked, before the port or pipe is actually setup.</p>
<p><code>tracing:net.server.listen:asyncEnd</code></p>
<ul>
<li><code>server</code> <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<p>Emitted when <a href="#all_net_serverlisten"><code>net.Server.listen()</code></a> has completed and thus the server is ready to accept connection.</p>
<p><code>tracing:net.server.listen:error</code></p>
<ul>
<li><code>server</code> <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>Emitted when <a href="#all_net_serverlisten"><code>net.Server.listen()</code></a> is returning an error.</p>
<h5>UDP<span><a class="mark" href="#all_diagnostics_channel_udp" id="all_diagnostics_channel_udp">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_udp"></a></h5>
<p><code>udp.socket</code></p>
<ul>
<li><code>socket</code> <a href="#all_dgram_class-dgramsocket" class="type"><dgram.Socket></a></li>
</ul>
<p>Emitted when a new UDP socket is created.</p>
<h5>Process<span><a class="mark" href="#all_diagnostics_channel_process" id="all_diagnostics_channel_process">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_process"></a></h5>
<div class="api_metadata">
<span>Added in: v16.18.0</span>
</div>
<p><code>child_process</code></p>
<ul>
<li><code>process</code> <a href="#all_child_process_class-childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>Emitted when a new process is created.</p>
<h5>Worker Thread<span><a class="mark" href="#all_diagnostics_channel_worker-thread" id="all_diagnostics_channel_worker-thread">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_worker_thread"></a></h5>
<div class="api_metadata">
<span>Added in: v16.18.0</span>
</div>
<p><code>worker_threads</code></p>
<ul>
<li><code>worker</code> <a href="#all_worker_threads_class-worker"><code>Worker</code></a></li>
</ul>
<p>Emitted when a new thread is created.</p></section>
</section>
<section><h2>DNS<span><a class="mark" href="#all_dns_dns" id="all_dns_dns">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/dns.js">lib/dns.js</a></p>
<p>The <code>node:dns</code> module enables name resolution. For example, use it to look up IP
addresses of host names.</p>
<p>Although named for the <a href="https://en.wikipedia.org/wiki/Domain_Name_System">Domain Name System (DNS)</a>, it does not always use the
DNS protocol for lookups. <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> uses the operating system
facilities to perform name resolution. It may not need to perform any network
communication. To perform name resolution the way other applications on the same
system do, use <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</p>
<pre class="with-32-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> dns <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns'</span>;
dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, <span class="hljs-function">(<span class="hljs-params">err, address, family</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'address: %j family: IPv%s'</span>, address, family);
});
<span class="hljs-comment">// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);
dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, <span class="hljs-function">(<span class="hljs-params">err, address, family</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'address: %j family: IPv%s'</span>, address, family);
});
<span class="hljs-comment">// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6</span></code><button class="copy-button">copy</button></pre>
<p>All other functions in the <code>node:dns</code> module connect to an actual DNS server to
perform name resolution. They will always use the network to perform DNS
queries. These functions do not use the same set of configuration files used by
<a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> (e.g. <code>/etc/hosts</code>). Use these functions to always perform
DNS queries, bypassing other name-resolution facilities.</p>
<pre class="with-32-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> dns <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns'</span>;
dns.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'archive.org'</span>, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`addresses: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(addresses)}</span>`</span>);
addresses.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">a</span>) =></span> {
dns.<span class="hljs-title function_">reverse</span>(a, <span class="hljs-function">(<span class="hljs-params">err, hostnames</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-keyword">throw</span> err;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`reverse for <span class="hljs-subst">${a}</span>: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(hostnames)}</span>`</span>);
});
});
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);
dns.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'archive.org'</span>, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`addresses: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(addresses)}</span>`</span>);
addresses.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">a</span>) =></span> {
dns.<span class="hljs-title function_">reverse</span>(a, <span class="hljs-function">(<span class="hljs-params">err, hostnames</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-keyword">throw</span> err;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`reverse for <span class="hljs-subst">${a}</span>: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(hostnames)}</span>`</span>);
});
});
});</code><button class="copy-button">copy</button></pre>
<p>See the <a href="#all_dns_implementation-considerations">Implementation considerations section</a> for more information.</p>
<section><h3>Class: <code>dns.Resolver</code><span><a class="mark" href="#all_dns_class-dnsresolver" id="all_dns_class-dnsresolver">#</a></span><a aria-hidden="true" class="legacy" id="dns_class_dns_resolver"></a></h3>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
</div>
<p>An independent resolver for DNS requests.</p>
<p>Creating a new resolver uses the default server settings. Setting
the servers used for a resolver using
<a href="#all_dns_dnssetserversservers"><code>resolver.setServers()</code></a> does not affect
other resolvers:</p>
<pre class="with-41-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_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns'</span>;
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
resolver.<span class="hljs-title function_">setServers</span>([<span class="hljs-string">'4.4.4.4'</span>]);
<span class="hljs-comment">// This request will use the server at 4.4.4.4, independent of global settings.</span>
resolver.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'example.org'</span>, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =></span> {
<span class="hljs-comment">// ...</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Resolver</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
resolver.<span class="hljs-title function_">setServers</span>([<span class="hljs-string">'4.4.4.4'</span>]);
<span class="hljs-comment">// This request will use the server at 4.4.4.4, independent of global settings.</span>
resolver.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'example.org'</span>, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =></span> {
<span class="hljs-comment">// ...</span>
});</code><button class="copy-button">copy</button></pre>
<p>The following methods from the <code>node:dns</code> module are available:</p>
<ul>
<li><a href="#all_dns_dnsgetservers"><code>resolver.getServers()</code></a></li>
<li><a href="#all_dns_dnsresolvehostname-rrtype-callback"><code>resolver.resolve()</code></a></li>
<li><a href="#all_dns_dnsresolve4hostname-options-callback"><code>resolver.resolve4()</code></a></li>
<li><a href="#all_dns_dnsresolve6hostname-options-callback"><code>resolver.resolve6()</code></a></li>
<li><a href="#all_dns_dnsresolveanyhostname-callback"><code>resolver.resolveAny()</code></a></li>
<li><a href="#all_dns_dnsresolvecaahostname-callback"><code>resolver.resolveCaa()</code></a></li>
<li><a href="#all_dns_dnsresolvecnamehostname-callback"><code>resolver.resolveCname()</code></a></li>
<li><a href="#all_dns_dnsresolvemxhostname-callback"><code>resolver.resolveMx()</code></a></li>
<li><a href="#all_dns_dnsresolvenaptrhostname-callback"><code>resolver.resolveNaptr()</code></a></li>
<li><a href="#all_dns_dnsresolvenshostname-callback"><code>resolver.resolveNs()</code></a></li>
<li><a href="#all_dns_dnsresolveptrhostname-callback"><code>resolver.resolvePtr()</code></a></li>
<li><a href="#all_dns_dnsresolvesoahostname-callback"><code>resolver.resolveSoa()</code></a></li>
<li><a href="#all_dns_dnsresolvesrvhostname-callback"><code>resolver.resolveSrv()</code></a></li>
<li><a href="#all_dns_dnsresolvetxthostname-callback"><code>resolver.resolveTxt()</code></a></li>
<li><a href="#all_dns_dnsreverseip-callback"><code>resolver.reverse()</code></a></li>
<li><a href="#all_dns_dnssetserversservers"><code>resolver.setServers()</code></a></li>
</ul>
<h4><code>Resolver([options])</code><span><a class="mark" href="#all_dns_resolveroptions" id="all_dns_resolveroptions">#</a></span><a aria-hidden="true" class="legacy" id="dns_resolver_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>v16.7.0, v14.18.0</td>
<td><p>The <code>options</code> object now accepts a <code>tries</code> option.</p></td></tr>
<tr><td>v12.18.3</td>
<td><p>The constructor now accepts an <code>options</code> object. The single supported option is <code>timeout</code>.</p></td></tr>
<tr><td>v8.3.0</td>
<td><p><span>Added in: v8.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Create a new resolver.</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>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Query timeout in milliseconds, or <code>-1</code> to use the
default timeout.</li>
<li><code>tries</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of tries the resolver will try contacting
each name server before giving up. <strong>Default:</strong> <code>4</code></li>
</ul>
</li>
</ul>
<h4><code>resolver.cancel()</code><span><a class="mark" href="#all_dns_resolvercancel" id="all_dns_resolvercancel">#</a></span><a aria-hidden="true" class="legacy" id="dns_resolver_cancel"></a></h4>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
</div>
<p>Cancel all outstanding DNS queries made by this resolver. The corresponding
callbacks will be called with an error with code <code>ECANCELLED</code>.</p>
<h4><code>resolver.setLocalAddress([ipv4][, ipv6])</code><span><a class="mark" href="#all_dns_resolversetlocaladdressipv4-ipv6" id="all_dns_resolversetlocaladdressipv4-ipv6">#</a></span><a aria-hidden="true" class="legacy" id="dns_resolver_setlocaladdress_ipv4_ipv6"></a></h4>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<ul>
<li><code>ipv4</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string representation of an IPv4 address.
<strong>Default:</strong> <code>'0.0.0.0'</code></li>
<li><code>ipv6</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string representation of an IPv6 address.
<strong>Default:</strong> <code>'::0'</code></li>
</ul>
<p>The resolver instance will send its requests from the specified IP address.
This allows programs to specify outbound interfaces when used on multi-homed
systems.</p>
<p>If a v4 or v6 address is not specified, it is set to the default and the
operating system will choose a local address automatically.</p>
<p>The resolver will use the v4 local address when making requests to IPv4 DNS
servers, and the v6 local address when making requests to IPv6 DNS servers.
The <code>rrtype</code> of resolution requests has no impact on the local address used.</p>
</section><section><h3><code>dns.getServers()</code><span><a class="mark" href="#all_dns_dnsgetservers" id="all_dns_dnsgetservers">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_getservers"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>Returns an array of IP address strings, formatted according to <a href="https://tools.ietf.org/html/rfc5952#section-6">RFC 5952</a>,
that are currently configured for DNS resolution. A string will include a port
section if a custom port is used.</p>
<!-- eslint-disable @stylistic/js/semi-->
<pre><code class="language-js">[
<span class="hljs-string">'8.8.8.8'</span>,
<span class="hljs-string">'2001:4860:4860::8888'</span>,
<span class="hljs-string">'8.8.8.8:1053'</span>,
<span class="hljs-string">'[2001:4860:4860::8888]:1053'</span>,
]</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>dns.lookup(hostname[, options], callback)</code><span><a class="mark" href="#all_dns_dnslookuphostname-options-callback" id="all_dns_dnslookuphostname-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_lookup_hostname_options_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>verbatim</code> option is now deprecated in favor of the new <code>order</code> option.</p></td></tr>
<tr><td>v18.4.0</td>
<td><p>For compatibility with <code>node:net</code>, when passing an option object the <code>family</code> option can be the string <code>'IPv4'</code> or the string <code>'IPv6'</code>.</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>v17.0.0</td>
<td><p>The <code>verbatim</code> options defaults to <code>true</code> now.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p>The <code>verbatim</code> option is supported now.</p></td></tr>
<tr><td>v1.2.0</td>
<td><p>The <code>all</code> option is supported now.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The record family. Must be <code>4</code>, <code>6</code>, or <code>0</code>. For
backward compatibility reasons,<code>'IPv4'</code> and <code>'IPv6'</code> are interpreted as <code>4</code>
and <code>6</code> respectively. The value <code>0</code> indicates that either an IPv4 or IPv6
address is returned. If the value <code>0</code> is used with <code>{ all: true }</code> (see
below), either one of or both IPv4 and IPv6 addresses are returned,
depending on the system's DNS resolver. <strong>Default:</strong> <code>0</code>.</li>
<li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> One or more <a href="#all_dns_supported-getaddrinfo-flags">supported <code>getaddrinfo</code> flags</a>. Multiple
flags may be passed by bitwise <code>OR</code>ing their values.</li>
<li><code>all</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the callback returns all resolved addresses in
an array. Otherwise, returns a single address. <strong>Default:</strong> <code>false</code>.</li>
<li><code>order</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> When <code>verbatim</code>, the resolved addresses are return
unsorted. When <code>ipv4first</code>, the resolved addresses are sorted by placing
IPv4 addresses before IPv6 addresses. When <code>ipv6first</code>, the resolved
addresses are sorted by placing IPv6 addresses before IPv4 addresses.
<strong>Default:</strong> <code>verbatim</code> (addresses are not reordered).
Default value is configurable using <a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> or
<a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order</code></a>.</li>
<li><code>verbatim</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the callback receives IPv4 and IPv6
addresses in the order the DNS resolver returned them. When <code>false</code>,
IPv4 addresses are placed before IPv6 addresses.
This option will be deprecated in favor of <code>order</code>. When both are specified,
<code>order</code> has higher precedence. New code should only use <code>order</code>.
<strong>Default:</strong> <code>true</code> (addresses are not reordered). Default value is
configurable using <a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> or
<a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order</code></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>
<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>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string representation of an IPv4 or IPv6 address.</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>4</code> or <code>6</code>, denoting the family of <code>address</code>, or <code>0</code> if
the address is not an IPv4 or IPv6 address. <code>0</code> is a likely indicator of a
bug in the name resolution service used by the operating system.</li>
</ul>
</li>
</ul>
<p>Resolves a host name (e.g. <code>'nodejs.org'</code>) into the first found A (IPv4) or
AAAA (IPv6) record. All <code>option</code> properties are optional. If <code>options</code> is an
integer, then it must be <code>4</code> or <code>6</code> – if <code>options</code> is not provided, then
either IPv4 or IPv6 addresses, or both, are returned if found.</p>
<p>With the <code>all</code> option set to <code>true</code>, the arguments for <code>callback</code> change to
<code>(err, addresses)</code>, with <code>addresses</code> being an array of objects with the
properties <code>address</code> and <code>family</code>.</p>
<p>On error, <code>err</code> is an <a href="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code> is the error code.
Keep in mind that <code>err.code</code> will be set to <code>'ENOTFOUND'</code> not only when
the host name does not exist but also when the lookup fails in other ways
such as no available file descriptors.</p>
<p><code>dns.lookup()</code> does not necessarily have anything to do with the DNS protocol.
The implementation uses an operating system facility that can associate names
with addresses and vice versa. This implementation can have subtle but
important consequences on the behavior of any Node.js program. Please take some
time to consult the <a href="#all_dns_implementation-considerations">Implementation considerations section</a> before using
<code>dns.lookup()</code>.</p>
<p>Example usage:</p>
<pre class="with-32-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> dns <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns'</span>;
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">family</span>: <span class="hljs-number">6</span>,
<span class="hljs-attr">hints</span>: dns.<span class="hljs-property">ADDRCONFIG</span> | dns.<span class="hljs-property">V4MAPPED</span>,
};
dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options, <span class="hljs-function">(<span class="hljs-params">err, address, family</span>) =></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'address: %j family: IPv%s'</span>, address, family));
<span class="hljs-comment">// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6</span>
<span class="hljs-comment">// When options.all is true, the result will be an Array.</span>
options.<span class="hljs-property">all</span> = <span class="hljs-literal">true</span>;
dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'addresses: %j'</span>, addresses));
<span class="hljs-comment">// addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">family</span>: <span class="hljs-number">6</span>,
<span class="hljs-attr">hints</span>: dns.<span class="hljs-property">ADDRCONFIG</span> | dns.<span class="hljs-property">V4MAPPED</span>,
};
dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options, <span class="hljs-function">(<span class="hljs-params">err, address, family</span>) =></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'address: %j family: IPv%s'</span>, address, family));
<span class="hljs-comment">// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6</span>
<span class="hljs-comment">// When options.all is true, the result will be an Array.</span>
options.<span class="hljs-property">all</span> = <span class="hljs-literal">true</span>;
dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'addresses: %j'</span>, addresses));
<span class="hljs-comment">// addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]</span></code><button class="copy-button">copy</button></pre>
<p>If this method is invoked as its <a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed version, and <code>all</code>
is not set to <code>true</code>, it returns a <code>Promise</code> for an <code>Object</code> with <code>address</code> and
<code>family</code> properties.</p>
<h4>Supported getaddrinfo flags<span><a class="mark" href="#all_dns_supported-getaddrinfo-flags" id="all_dns_supported-getaddrinfo-flags">#</a></span><a aria-hidden="true" class="legacy" id="dns_supported_getaddrinfo_flags"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.13.0, v12.17.0</td>
<td><p>Added support for the <code>dns.ALL</code> flag.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The following flags can be passed as hints to <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</p>
<ul>
<li><code>dns.ADDRCONFIG</code>: Limits returned address types to the types of non-loopback
addresses configured on the system. For example, IPv4 addresses are only
returned if the current system has at least one IPv4 address configured.</li>
<li><code>dns.V4MAPPED</code>: If the IPv6 family was specified, but no IPv6 addresses were
found, then return IPv4 mapped IPv6 addresses. It is not supported
on some operating systems (e.g. FreeBSD 10.1).</li>
<li><code>dns.ALL</code>: If <code>dns.V4MAPPED</code> is specified, return resolved IPv6 addresses as
well as IPv4 mapped IPv6 addresses.</li>
</ul>
</section><section><h3><code>dns.lookupService(address, port, callback)</code><span><a class="mark" href="#all_dns_dnslookupserviceaddress-port-callback" id="all_dns_dnslookupserviceaddress-port-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_lookupservice_address_port_callback"></a></h3>
<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</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>v0.11.14</td>
<td><p><span>Added in: v0.11.14</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> e.g. <code>example.com</code></li>
<li><code>service</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> e.g. <code>http</code></li>
</ul>
</li>
</ul>
<p>Resolves the given <code>address</code> and <code>port</code> into a host name and service using
the operating system's underlying <code>getnameinfo</code> implementation.</p>
<p>If <code>address</code> is not a valid IP address, a <code>TypeError</code> will be thrown.
The <code>port</code> will be coerced to a number. If it is not a legal port, a <code>TypeError</code>
will be thrown.</p>
<p>On an error, <code>err</code> is an <a href="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code> is the error code.</p>
<pre class="with-64-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> dns <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns'</span>;
dns.<span class="hljs-title function_">lookupService</span>(<span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-number">22</span>, <span class="hljs-function">(<span class="hljs-params">err, hostname, service</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hostname, service);
<span class="hljs-comment">// Prints: localhost ssh</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);
dns.<span class="hljs-title function_">lookupService</span>(<span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-number">22</span>, <span class="hljs-function">(<span class="hljs-params">err, hostname, service</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hostname, service);
<span class="hljs-comment">// Prints: localhost ssh</span>
});</code><button class="copy-button">copy</button></pre>
<p>If this method is invoked as its <a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed version, it returns a
<code>Promise</code> for an <code>Object</code> with <code>hostname</code> and <code>service</code> properties.</p>
</section><section><h3><code>dns.resolve(hostname[, rrtype], callback)</code><span><a class="mark" href="#all_dns_dnsresolvehostname-rrtype-callback" id="all_dns_dnsresolvehostname-rrtype-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolve_hostname_rrtype_callback"></a></h3>
<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</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>v0.1.27</td>
<td><p><span>Added in: v0.1.27</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host name to resolve.</li>
<li><code>rrtype</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Resource record type. <strong>Default:</strong> <code>'A'</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>
<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>records</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/Reference/Global_Objects/Object" class="type"><Object[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve a host name (e.g. <code>'nodejs.org'</code>) into an array
of the resource records. The <code>callback</code> function has arguments
<code>(err, records)</code>. When successful, <code>records</code> will be an array of resource
records. The type and structure of individual results varies based on <code>rrtype</code>:</p>
<table><thead><tr><th><code>rrtype</code></th><th><code>records</code> contains</th><th>Result type</th><th>Shorthand method</th></tr></thead><tbody><tr><td><code>'A'</code></td><td>IPv4 addresses (default)</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#all_dns_dnsresolve4hostname-options-callback"><code>dns.resolve4()</code></a></td></tr><tr><td><code>'AAAA'</code></td><td>IPv6 addresses</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#all_dns_dnsresolve6hostname-options-callback"><code>dns.resolve6()</code></a></td></tr><tr><td><code>'ANY'</code></td><td>any records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#all_dns_dnsresolveanyhostname-callback"><code>dns.resolveAny()</code></a></td></tr><tr><td><code>'CAA'</code></td><td>CA authorization records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#all_dns_dnsresolvecaahostname-callback"><code>dns.resolveCaa()</code></a></td></tr><tr><td><code>'CNAME'</code></td><td>canonical name records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#all_dns_dnsresolvecnamehostname-callback"><code>dns.resolveCname()</code></a></td></tr><tr><td><code>'MX'</code></td><td>mail exchange records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#all_dns_dnsresolvemxhostname-callback"><code>dns.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>name authority pointer records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#all_dns_dnsresolvenaptrhostname-callback"><code>dns.resolveNaptr()</code></a></td></tr><tr><td><code>'NS'</code></td><td>name server records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#all_dns_dnsresolvenshostname-callback"><code>dns.resolveNs()</code></a></td></tr><tr><td><code>'PTR'</code></td><td>pointer records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#all_dns_dnsresolveptrhostname-callback"><code>dns.resolvePtr()</code></a></td></tr><tr><td><code>'SOA'</code></td><td>start of authority records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#all_dns_dnsresolvesoahostname-callback"><code>dns.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>service records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#all_dns_dnsresolvesrvhostname-callback"><code>dns.resolveSrv()</code></a></td></tr><tr><td><code>'TXT'</code></td><td>text records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></td><td><a href="#all_dns_dnsresolvetxthostname-callback"><code>dns.resolveTxt()</code></a></td></tr></tbody></table>
<p>On error, <code>err</code> is an <a href="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code> is one of the
<a href="#all_dns_error-codes">DNS error codes</a>.</p>
</section><section><h3><code>dns.resolve4(hostname[, options], callback)</code><span><a class="mark" href="#all_dns_dnsresolve4hostname-options-callback" id="all_dns_dnsresolve4hostname-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolve4_hostname_options_callback"></a></h3>
<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</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>v7.2.0</td>
<td><p>This method now supports passing <code>options</code>, specifically <code>options.ttl</code>.</p></td></tr>
<tr><td>v0.1.16</td>
<td><p><span>Added in: v0.1.16</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host name to resolve.</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>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Retrieves the Time-To-Live value (TTL) of each record.
When <code>true</code>, the callback receives an array of
<code>{ address: '1.2.3.4', ttl: 60 }</code> objects rather than an array of strings,
with the TTL expressed in seconds.</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>
<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>addresses</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/Reference/Global_Objects/Object" class="type"><Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve a IPv4 addresses (<code>A</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function
will contain an array of IPv4 addresses (e.g.
<code>['74.125.79.104', '74.125.79.105', '74.125.79.106']</code>).</p>
</section><section><h3><code>dns.resolve6(hostname[, options], callback)</code><span><a class="mark" href="#all_dns_dnsresolve6hostname-options-callback" id="all_dns_dnsresolve6hostname-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolve6_hostname_options_callback"></a></h3>
<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</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>v7.2.0</td>
<td><p>This method now supports passing <code>options</code>, specifically <code>options.ttl</code>.</p></td></tr>
<tr><td>v0.1.16</td>
<td><p><span>Added in: v0.1.16</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host name to resolve.</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>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Retrieve the Time-To-Live value (TTL) of each record.
When <code>true</code>, the callback receives an array of
<code>{ address: '0:1:2:3:4:5:6:7', ttl: 60 }</code> objects rather than an array of
strings, with the TTL expressed in seconds.</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>
<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>addresses</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/Reference/Global_Objects/Object" class="type"><Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve IPv6 addresses (<code>AAAA</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function
will contain an array of IPv6 addresses.</p>
</section><section><h3><code>dns.resolveAny(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolveanyhostname-callback" id="all_dns_dnsresolveanyhostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolveany_hostname_callback"></a></h3>
<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</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>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>ret</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve all records (also known as <code>ANY</code> or <code>*</code> query).
The <code>ret</code> argument passed to the <code>callback</code> function will be an array containing
various types of records. Each object has a property <code>type</code> that indicates the
type of the current record. And depending on the <code>type</code>, additional properties
will be present on the object:</p>
<table><thead><tr><th>Type</th><th>Properties</th></tr></thead><tbody><tr><td><code>'A'</code></td><td><code>address</code>/<code>ttl</code></td></tr><tr><td><code>'AAAA'</code></td><td><code>address</code>/<code>ttl</code></td></tr><tr><td><code>'CNAME'</code></td><td><code>value</code></td></tr><tr><td><code>'MX'</code></td><td>Refer to <a href="#all_dns_dnsresolvemxhostname-callback"><code>dns.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>Refer to <a href="#all_dns_dnsresolvenaptrhostname-callback"><code>dns.resolveNaptr()</code></a></td></tr><tr><td><code>'NS'</code></td><td><code>value</code></td></tr><tr><td><code>'PTR'</code></td><td><code>value</code></td></tr><tr><td><code>'SOA'</code></td><td>Refer to <a href="#all_dns_dnsresolvesoahostname-callback"><code>dns.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>Refer to <a href="#all_dns_dnsresolvesrvhostname-callback"><code>dns.resolveSrv()</code></a></td></tr><tr><td><code>'TXT'</code></td><td>This type of record contains an array property called <code>entries</code> which refers to <a href="#all_dns_dnsresolvetxthostname-callback"><code>dns.resolveTxt()</code></a>, e.g. <code>{ entries: ['...'], type: 'TXT' }</code></td></tr></tbody></table>
<p>Here is an example of the <code>ret</code> object passed to the callback:</p>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js">[ { <span class="hljs-attr">type</span>: <span class="hljs-string">'A'</span>, <span class="hljs-attr">address</span>: <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-attr">ttl</span>: <span class="hljs-number">299</span> },
{ <span class="hljs-attr">type</span>: <span class="hljs-string">'CNAME'</span>, <span class="hljs-attr">value</span>: <span class="hljs-string">'example.com'</span> },
{ <span class="hljs-attr">type</span>: <span class="hljs-string">'MX'</span>, <span class="hljs-attr">exchange</span>: <span class="hljs-string">'alt4.aspmx.l.example.com'</span>, <span class="hljs-attr">priority</span>: <span class="hljs-number">50</span> },
{ <span class="hljs-attr">type</span>: <span class="hljs-string">'NS'</span>, <span class="hljs-attr">value</span>: <span class="hljs-string">'ns1.example.com'</span> },
{ <span class="hljs-attr">type</span>: <span class="hljs-string">'TXT'</span>, <span class="hljs-attr">entries</span>: [ <span class="hljs-string">'v=spf1 include:_spf.example.com ~all'</span> ] },
{ <span class="hljs-attr">type</span>: <span class="hljs-string">'SOA'</span>,
<span class="hljs-attr">nsname</span>: <span class="hljs-string">'ns1.example.com'</span>,
<span class="hljs-attr">hostmaster</span>: <span class="hljs-string">'admin.example.com'</span>,
<span class="hljs-attr">serial</span>: <span class="hljs-number">156696742</span>,
<span class="hljs-attr">refresh</span>: <span class="hljs-number">900</span>,
<span class="hljs-attr">retry</span>: <span class="hljs-number">900</span>,
<span class="hljs-attr">expire</span>: <span class="hljs-number">1800</span>,
<span class="hljs-attr">minttl</span>: <span class="hljs-number">60</span> } ]</code> <button class="copy-button">copy</button></pre>
<p>DNS server operators may choose not to respond to <code>ANY</code>
queries. It may be better to call individual methods like <a href="#all_dns_dnsresolve4hostname-options-callback"><code>dns.resolve4()</code></a>,
<a href="#all_dns_dnsresolvemxhostname-callback"><code>dns.resolveMx()</code></a>, and so on. For more details, see <a href="https://tools.ietf.org/html/rfc8482">RFC 8482</a>.</p>
</section><section><h3><code>dns.resolveCname(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvecnamehostname-callback" id="all_dns_dnsresolvecnamehostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvecname_hostname_callback"></a></h3>
<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</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>v0.3.2</td>
<td><p><span>Added in: v0.3.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve <code>CNAME</code> records for the <code>hostname</code>. The
<code>addresses</code> argument passed to the <code>callback</code> function
will contain an array of canonical name records available for the <code>hostname</code>
(e.g. <code>['bar.example.com']</code>).</p>
</section><section><h3><code>dns.resolveCaa(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvecaahostname-callback" id="all_dns_dnsresolvecaahostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvecaa_hostname_callback"></a></h3>
<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</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>v15.0.0, v14.17.0</td>
<td><p><span>Added in: v15.0.0, v14.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>records</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve <code>CAA</code> records for the <code>hostname</code>. The
<code>addresses</code> argument passed to the <code>callback</code> function
will contain an array of certification authority authorization records
available for the <code>hostname</code> (e.g. <code>[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]</code>).</p>
</section><section><h3><code>dns.resolveMx(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvemxhostname-callback" id="all_dns_dnsresolvemxhostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvemx_hostname_callback"></a></h3>
<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</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>v0.1.27</td>
<td><p><span>Added in: v0.1.27</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve mail exchange records (<code>MX</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will
contain an array of objects containing both a <code>priority</code> and <code>exchange</code>
property (e.g. <code>[{priority: 10, exchange: 'mx.example.com'}, ...]</code>).</p>
</section><section><h3><code>dns.resolveNaptr(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvenaptrhostname-callback" id="all_dns_dnsresolvenaptrhostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvenaptr_hostname_callback"></a></h3>
<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</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>v0.9.12</td>
<td><p><span>Added in: v0.9.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve regular expression-based records (<code>NAPTR</code>
records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code>
function will contain an array of objects with the following properties:</p>
<ul>
<li><code>flags</code></li>
<li><code>service</code></li>
<li><code>regexp</code></li>
<li><code>replacement</code></li>
<li><code>order</code></li>
<li><code>preference</code></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
<span class="hljs-attr">flags</span>: <span class="hljs-string">'s'</span>,
<span class="hljs-attr">service</span>: <span class="hljs-string">'SIP+D2U'</span>,
<span class="hljs-attr">regexp</span>: <span class="hljs-string">''</span>,
<span class="hljs-attr">replacement</span>: <span class="hljs-string">'_sip._udp.example.com'</span>,
<span class="hljs-attr">order</span>: <span class="hljs-number">30</span>,
<span class="hljs-attr">preference</span>: <span class="hljs-number">100</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>dns.resolveNs(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvenshostname-callback" id="all_dns_dnsresolvenshostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvens_hostname_callback"></a></h3>
<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</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>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve name server records (<code>NS</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will
contain an array of name server records available for <code>hostname</code>
(e.g. <code>['ns1.example.com', 'ns2.example.com']</code>).</p>
</section><section><h3><code>dns.resolvePtr(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolveptrhostname-callback" id="all_dns_dnsresolveptrhostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolveptr_hostname_callback"></a></h3>
<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</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>v6.0.0</td>
<td><p><span>Added in: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve pointer records (<code>PTR</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will
be an array of strings containing the reply records.</p>
</section><section><h3><code>dns.resolveSoa(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvesoahostname-callback" id="all_dns_dnsresolvesoahostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvesoa_hostname_callback"></a></h3>
<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</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>v0.11.10</td>
<td><p><span>Added in: v0.11.10</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve a start of authority record (<code>SOA</code> record) for
the <code>hostname</code>. The <code>address</code> argument passed to the <code>callback</code> function will
be an object with the following properties:</p>
<ul>
<li><code>nsname</code></li>
<li><code>hostmaster</code></li>
<li><code>serial</code></li>
<li><code>refresh</code></li>
<li><code>retry</code></li>
<li><code>expire</code></li>
<li><code>minttl</code></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
<span class="hljs-attr">nsname</span>: <span class="hljs-string">'ns.example.com'</span>,
<span class="hljs-attr">hostmaster</span>: <span class="hljs-string">'root.example.com'</span>,
<span class="hljs-attr">serial</span>: <span class="hljs-number">2013101809</span>,
<span class="hljs-attr">refresh</span>: <span class="hljs-number">10000</span>,
<span class="hljs-attr">retry</span>: <span class="hljs-number">2400</span>,
<span class="hljs-attr">expire</span>: <span class="hljs-number">604800</span>,
<span class="hljs-attr">minttl</span>: <span class="hljs-number">3600</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>dns.resolveSrv(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvesrvhostname-callback" id="all_dns_dnsresolvesrvhostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvesrv_hostname_callback"></a></h3>
<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</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>v0.1.27</td>
<td><p><span>Added in: v0.1.27</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve service records (<code>SRV</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will
be an array of objects with the following properties:</p>
<ul>
<li><code>priority</code></li>
<li><code>weight</code></li>
<li><code>port</code></li>
<li><code>name</code></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
<span class="hljs-attr">priority</span>: <span class="hljs-number">10</span>,
<span class="hljs-attr">weight</span>: <span class="hljs-number">5</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">21223</span>,
<span class="hljs-attr">name</span>: <span class="hljs-string">'service.example.com'</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>dns.resolveTxt(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvetxthostname-callback" id="all_dns_dnsresolvetxthostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvetxt_hostname_callback"></a></h3>
<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</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>v0.1.27</td>
<td><p><span>Added in: v0.1.27</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable no-undefined-references list-item-bullet-indent-->
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>records</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[][]></a></li>
</ul>
</li>
</ul>
<!--lint enable no-undefined-references list-item-bullet-indent-->
<p>Uses the DNS protocol to resolve text queries (<code>TXT</code> records) for the
<code>hostname</code>. The <code>records</code> argument passed to the <code>callback</code> function is a
two-dimensional array of the text records available for <code>hostname</code> (e.g.
<code>[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]</code>). Each sub-array contains TXT chunks of
one record. Depending on the use case, these could be either joined together or
treated separately.</p>
</section><section><h3><code>dns.reverse(ip, callback)</code><span><a class="mark" href="#all_dns_dnsreverseip-callback" id="all_dns_dnsreverseip-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_reverse_ip_callback"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><code>ip</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>hostnames</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
</li>
</ul>
<p>Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
array of host names.</p>
<p>On error, <code>err</code> is an <a href="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code> is
one of the <a href="#all_dns_error-codes">DNS error codes</a>.</p>
</section><section><h3><code>dns.setDefaultResultOrder(order)</code><span><a class="mark" href="#all_dns_dnssetdefaultresultorderorder" id="all_dns_dnssetdefaultresultorderorder">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_setdefaultresultorder_order"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>ipv6first</code> value is supported now.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p>Changed default value to <code>verbatim</code>.</p></td></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p><span>Added in: v16.4.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>order</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> must be <code>'ipv4first'</code>, <code>'ipv6first'</code> or <code>'verbatim'</code>.</li>
</ul>
<p>Set the default value of <code>order</code> in <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> and
<a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup()</code></a>. The value could be:</p>
<ul>
<li><code>ipv4first</code>: sets default <code>order</code> to <code>ipv4first</code>.</li>
<li><code>ipv6first</code>: sets default <code>order</code> to <code>ipv6first</code>.</li>
<li><code>verbatim</code>: sets default <code>order</code> to <code>verbatim</code>.</li>
</ul>
<p>The default is <code>verbatim</code> and <a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> have higher
priority than <a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order</code></a>. When using <a href="worker_threads.html">worker threads</a>,
<a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> from the main thread won't affect the default
dns orders in workers.</p>
</section><section><h3><code>dns.getDefaultResultOrder()</code><span><a class="mark" href="#all_dns_dnsgetdefaultresultorder" id="all_dns_dnsgetdefaultresultorder">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_getdefaultresultorder"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>ipv6first</code> value is supported now.</p></td></tr>
<tr><td>v20.1.0, v18.17.0</td>
<td><p><span>Added in: v20.1.0, v18.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Get the default value for <code>order</code> in <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> and
<a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup()</code></a>. The value could be:</p>
<ul>
<li><code>ipv4first</code>: for <code>order</code> defaulting to <code>ipv4first</code>.</li>
<li><code>ipv6first</code>: for <code>order</code> defaulting to <code>ipv6first</code>.</li>
<li><code>verbatim</code>: for <code>order</code> defaulting to <code>verbatim</code>.</li>
</ul>
</section><section><h3><code>dns.setServers(servers)</code><span><a class="mark" href="#all_dns_dnssetserversservers" id="all_dns_dnssetserversservers">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_setservers_servers"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.3</span>
</div>
<ul>
<li><code>servers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> array of <a href="https://tools.ietf.org/html/rfc5952#section-6">RFC 5952</a> formatted addresses</li>
</ul>
<p>Sets the IP address and port of servers to be used when performing DNS
resolution. The <code>servers</code> argument is an array of <a href="https://tools.ietf.org/html/rfc5952#section-6">RFC 5952</a> formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.</p>
<pre><code class="language-js">dns.<span class="hljs-title function_">setServers</span>([
<span class="hljs-string">'8.8.8.8'</span>,
<span class="hljs-string">'[2001:4860:4860::8888]'</span>,
<span class="hljs-string">'8.8.8.8:1053'</span>,
<span class="hljs-string">'[2001:4860:4860::8888]:1053'</span>,
]);</code> <button class="copy-button">copy</button></pre>
<p>An error will be thrown if an invalid address is provided.</p>
<p>The <code>dns.setServers()</code> method must not be called while a DNS query is in
progress.</p>
<p>The <a href="#all_dns_dnssetserversservers"><code>dns.setServers()</code></a> method affects only <a href="#all_dns_dnsresolvehostname-rrtype-callback"><code>dns.resolve()</code></a>,
<code>dns.resolve*()</code> and <a href="#all_dns_dnsreverseip-callback"><code>dns.reverse()</code></a> (and specifically <em>not</em>
<a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>).</p>
<p>This method works much like
<a href="https://man7.org/linux/man-pages/man5/resolv.conf.5.html">resolve.conf</a>.
That is, if attempting to resolve with the first server provided results in a
<code>NOTFOUND</code> error, the <code>resolve()</code> method will <em>not</em> attempt to resolve with
subsequent servers provided. Fallback DNS servers will only be used if the
earlier ones time out or result in some other error.</p>
</section><section><h3>DNS promises API<span><a class="mark" href="#all_dns_dns-promises-api" id="all_dns_dns-promises-api">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_promises_api"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Exposed as <code>require('dns/promises')</code>.</p></td></tr>
<tr><td>v11.14.0, v10.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v10.6.0</td>
<td><p><span>Added in: v10.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>dns.promises</code> API provides an alternative set of asynchronous DNS methods
that return <code>Promise</code> objects rather than using callbacks. The API is accessible
via <code>require('node:dns').promises</code> or <code>require('node:dns/promises')</code>.</p>
<h4>Class: <code>dnsPromises.Resolver</code><span><a class="mark" href="#all_dns_class-dnspromisesresolver" id="all_dns_class-dnspromisesresolver">#</a></span><a aria-hidden="true" class="legacy" id="dns_class_dnspromises_resolver"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<p>An independent resolver for DNS requests.</p>
<p>Creating a new resolver uses the default server settings. Setting
the servers used for a resolver using
<a href="#all_dns_dnspromisessetserversservers"><code>resolver.setServers()</code></a> does not affect
other resolvers:</p>
<pre class="with-50-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_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>;
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
resolver.<span class="hljs-title function_">setServers</span>([<span class="hljs-string">'4.4.4.4'</span>]);
<span class="hljs-comment">// This request will use the server at 4.4.4.4, independent of global settings.</span>
<span class="hljs-keyword">const</span> addresses = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'example.org'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Resolver</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>).<span class="hljs-property">promises</span>;
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
resolver.<span class="hljs-title function_">setServers</span>([<span class="hljs-string">'4.4.4.4'</span>]);
<span class="hljs-comment">// This request will use the server at 4.4.4.4, independent of global settings.</span>
resolver.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'example.org'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">addresses</span>) =></span> {
<span class="hljs-comment">// ...</span>
});
<span class="hljs-comment">// Alternatively, the same code can be written using async-await style.</span>
(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> addresses = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'example.org'</span>);
})();</code><button class="copy-button">copy</button></pre>
<p>The following methods from the <code>dnsPromises</code> API are available:</p>
<ul>
<li><a href="#all_dns_dnspromisesgetservers"><code>resolver.getServers()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvehostname-rrtype"><code>resolver.resolve()</code></a></li>
<li><a href="#all_dns_dnspromisesresolve4hostname-options"><code>resolver.resolve4()</code></a></li>
<li><a href="#all_dns_dnspromisesresolve6hostname-options"><code>resolver.resolve6()</code></a></li>
<li><a href="#all_dns_dnspromisesresolveanyhostname"><code>resolver.resolveAny()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvecaahostname"><code>resolver.resolveCaa()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvecnamehostname"><code>resolver.resolveCname()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvemxhostname"><code>resolver.resolveMx()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvenaptrhostname"><code>resolver.resolveNaptr()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvenshostname"><code>resolver.resolveNs()</code></a></li>
<li><a href="#all_dns_dnspromisesresolveptrhostname"><code>resolver.resolvePtr()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvesoahostname"><code>resolver.resolveSoa()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvesrvhostname"><code>resolver.resolveSrv()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvetxthostname"><code>resolver.resolveTxt()</code></a></li>
<li><a href="#all_dns_dnspromisesreverseip"><code>resolver.reverse()</code></a></li>
<li><a href="#all_dns_dnspromisessetserversservers"><code>resolver.setServers()</code></a></li>
</ul>
<h4><code>resolver.cancel()</code><span><a class="mark" href="#all_dns_resolvercancel_1" id="all_dns_resolvercancel_1">#</a></span><a aria-hidden="true" class="legacy" id="dns_resolver_cancel_1"></a></h4>
<div class="api_metadata">
<span>Added in: v15.3.0, v14.17.0</span>
</div>
<p>Cancel all outstanding DNS queries made by this resolver. The corresponding
promises will be rejected with an error with the code <code>ECANCELLED</code>.</p>
<h4><code>dnsPromises.getServers()</code><span><a class="mark" href="#all_dns_dnspromisesgetservers" id="all_dns_dnspromisesgetservers">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_getservers"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>Returns an array of IP address strings, formatted according to <a href="https://tools.ietf.org/html/rfc5952#section-6">RFC 5952</a>,
that are currently configured for DNS resolution. A string will include a port
section if a custom port is used.</p>
<!-- eslint-disable @stylistic/js/semi-->
<pre><code class="language-js">[
<span class="hljs-string">'8.8.8.8'</span>,
<span class="hljs-string">'2001:4860:4860::8888'</span>,
<span class="hljs-string">'8.8.8.8:1053'</span>,
<span class="hljs-string">'[2001:4860:4860::8888]:1053'</span>,
]</code> <button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.lookup(hostname[, options])</code><span><a class="mark" href="#all_dns_dnspromiseslookuphostname-options" id="all_dns_dnspromiseslookuphostname-options">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_lookup_hostname_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>v20.13.0</td>
<td><p>The <code>verbatim</code> option is now deprecated in favor of the new <code>order</code> option.</p></td></tr>
<tr><td>v10.6.0</td>
<td><p><span>Added in: v10.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The record family. Must be <code>4</code>, <code>6</code>, or <code>0</code>. The value
<code>0</code> indicates that either an IPv4 or IPv6 address is returned. If the
value <code>0</code> is used with <code>{ all: true }</code> (see below), either one of or both
IPv4 and IPv6 addresses are returned, depending on the system's DNS
resolver. <strong>Default:</strong> <code>0</code>.</li>
<li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> One or more <a href="#all_dns_supported-getaddrinfo-flags">supported <code>getaddrinfo</code> flags</a>. Multiple
flags may be passed by bitwise <code>OR</code>ing their values.</li>
<li><code>all</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Promise</code> is resolved with all addresses in
an array. Otherwise, returns a single address. <strong>Default:</strong> <code>false</code>.</li>
<li><code>order</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> When <code>verbatim</code>, the <code>Promise</code> is resolved with IPv4 and
IPv6 addresses in the order the DNS resolver returned them. When <code>ipv4first</code>,
IPv4 addresses are placed before IPv6 addresses. When <code>ipv6first</code>,
IPv6 addresses are placed before IPv4 addresses.
<strong>Default:</strong> <code>verbatim</code> (addresses are not reordered).
Default value is configurable using <a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> or
<a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order</code></a>. New code should use <code>{ order: 'verbatim' }</code>.</li>
<li><code>verbatim</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Promise</code> is resolved with IPv4 and
IPv6 addresses in the order the DNS resolver returned them. When <code>false</code>,
IPv4 addresses are placed before IPv6 addresses.
This option will be deprecated in favor of <code>order</code>. When both are specified,
<code>order</code> has higher precedence. New code should only use <code>order</code>.
<strong>Default:</strong> currently <code>false</code> (addresses are reordered) but this is
expected to change in the not too distant future. Default value is
configurable using <a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> or
<a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order</code></a>.</li>
</ul>
</li>
</ul>
<p>Resolves a host name (e.g. <code>'nodejs.org'</code>) into the first found A (IPv4) or
AAAA (IPv6) record. All <code>option</code> properties are optional. If <code>options</code> is an
integer, then it must be <code>4</code> or <code>6</code> – if <code>options</code> is not provided, then
either IPv4 or IPv6 addresses, or both, are returned if found.</p>
<p>With the <code>all</code> option set to <code>true</code>, the <code>Promise</code> is resolved with <code>addresses</code>
being an array of objects with the properties <code>address</code> and <code>family</code>.</p>
<p>On error, the <code>Promise</code> is rejected with an <a href="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code>
is the error code.
Keep in mind that <code>err.code</code> will be set to <code>'ENOTFOUND'</code> not only when
the host name does not exist but also when the lookup fails in other ways
such as no available file descriptors.</p>
<p><a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup()</code></a> does not necessarily have anything to do with the DNS
protocol. The implementation uses an operating system facility that can
associate names with addresses and vice versa. This implementation can have
subtle but important consequences on the behavior of any Node.js program. Please
take some time to consult the <a href="#all_dns_implementation-considerations">Implementation considerations section</a> before
using <code>dnsPromises.lookup()</code>.</p>
<p>Example usage:</p>
<pre class="with-33-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> dns <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns'</span>;
<span class="hljs-keyword">const</span> dnsPromises = dns.<span class="hljs-property">promises</span>;
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">family</span>: <span class="hljs-number">6</span>,
<span class="hljs-attr">hints</span>: dns.<span class="hljs-property">ADDRCONFIG</span> | dns.<span class="hljs-property">V4MAPPED</span>,
};
<span class="hljs-keyword">await</span> dnsPromises.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options).<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">'address: %j family: IPv%s'</span>, result.<span class="hljs-property">address</span>, result.<span class="hljs-property">family</span>);
<span class="hljs-comment">// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6</span>
});
<span class="hljs-comment">// When options.all is true, the result will be an Array.</span>
options.<span class="hljs-property">all</span> = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">await</span> dnsPromises.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options).<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">'addresses: %j'</span>, result);
<span class="hljs-comment">// addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);
<span class="hljs-keyword">const</span> dnsPromises = dns.<span class="hljs-property">promises</span>;
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">family</span>: <span class="hljs-number">6</span>,
<span class="hljs-attr">hints</span>: dns.<span class="hljs-property">ADDRCONFIG</span> | dns.<span class="hljs-property">V4MAPPED</span>,
};
dnsPromises.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options).<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">'address: %j family: IPv%s'</span>, result.<span class="hljs-property">address</span>, result.<span class="hljs-property">family</span>);
<span class="hljs-comment">// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6</span>
});
<span class="hljs-comment">// When options.all is true, the result will be an Array.</span>
options.<span class="hljs-property">all</span> = <span class="hljs-literal">true</span>;
dnsPromises.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options).<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">'addresses: %j'</span>, result);
<span class="hljs-comment">// addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.lookupService(address, port)</code><span><a class="mark" href="#all_dns_dnspromiseslookupserviceaddress-port" id="all_dns_dnspromiseslookupserviceaddress-port">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_lookupservice_address_port"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Resolves the given <code>address</code> and <code>port</code> into a host name and service using
the operating system's underlying <code>getnameinfo</code> implementation.</p>
<p>If <code>address</code> is not a valid IP address, a <code>TypeError</code> will be thrown.
The <code>port</code> will be coerced to a number. If it is not a legal port, a <code>TypeError</code>
will be thrown.</p>
<p>On error, the <code>Promise</code> is rejected with an <a href="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code>
is the error code.</p>
<pre class="with-64-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> dnsPromises <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>;
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> dnsPromises.<span class="hljs-title function_">lookupService</span>(<span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-number">22</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result.<span class="hljs-property">hostname</span>, result.<span class="hljs-property">service</span>); <span class="hljs-comment">// Prints: localhost ssh</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> dnsPromises = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>).<span class="hljs-property">promises</span>;
dnsPromises.<span class="hljs-title function_">lookupService</span>(<span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-number">22</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>(result.<span class="hljs-property">hostname</span>, result.<span class="hljs-property">service</span>);
<span class="hljs-comment">// Prints: localhost ssh</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.resolve(hostname[, rrtype])</code><span><a class="mark" href="#all_dns_dnspromisesresolvehostname-rrtype" id="all_dns_dnspromisesresolvehostname-rrtype">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolve_hostname_rrtype"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host name to resolve.</li>
<li><code>rrtype</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Resource record type. <strong>Default:</strong> <code>'A'</code>.</li>
</ul>
<p>Uses the DNS protocol to resolve a host name (e.g. <code>'nodejs.org'</code>) into an array
of the resource records. When successful, the <code>Promise</code> is resolved with an
array of resource records. The type and structure of individual results vary
based on <code>rrtype</code>:</p>
<table><thead><tr><th><code>rrtype</code></th><th><code>records</code> contains</th><th>Result type</th><th>Shorthand method</th></tr></thead><tbody><tr><td><code>'A'</code></td><td>IPv4 addresses (default)</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#all_dns_dnspromisesresolve4hostname-options"><code>dnsPromises.resolve4()</code></a></td></tr><tr><td><code>'AAAA'</code></td><td>IPv6 addresses</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#all_dns_dnspromisesresolve6hostname-options"><code>dnsPromises.resolve6()</code></a></td></tr><tr><td><code>'ANY'</code></td><td>any records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#all_dns_dnspromisesresolveanyhostname"><code>dnsPromises.resolveAny()</code></a></td></tr><tr><td><code>'CAA'</code></td><td>CA authorization records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#all_dns_dnspromisesresolvecaahostname"><code>dnsPromises.resolveCaa()</code></a></td></tr><tr><td><code>'CNAME'</code></td><td>canonical name records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#all_dns_dnspromisesresolvecnamehostname"><code>dnsPromises.resolveCname()</code></a></td></tr><tr><td><code>'MX'</code></td><td>mail exchange records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#all_dns_dnspromisesresolvemxhostname"><code>dnsPromises.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>name authority pointer records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#all_dns_dnspromisesresolvenaptrhostname"><code>dnsPromises.resolveNaptr()</code></a></td></tr><tr><td><code>'NS'</code></td><td>name server records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#all_dns_dnspromisesresolvenshostname"><code>dnsPromises.resolveNs()</code></a></td></tr><tr><td><code>'PTR'</code></td><td>pointer records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#all_dns_dnspromisesresolveptrhostname"><code>dnsPromises.resolvePtr()</code></a></td></tr><tr><td><code>'SOA'</code></td><td>start of authority records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#all_dns_dnspromisesresolvesoahostname"><code>dnsPromises.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>service records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#all_dns_dnspromisesresolvesrvhostname"><code>dnsPromises.resolveSrv()</code></a></td></tr><tr><td><code>'TXT'</code></td><td>text records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></td><td><a href="#all_dns_dnspromisesresolvetxthostname"><code>dnsPromises.resolveTxt()</code></a></td></tr></tbody></table>
<p>On error, the <code>Promise</code> is rejected with an <a href="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code>
is one of the <a href="#all_dns_error-codes">DNS error codes</a>.</p>
<h4><code>dnsPromises.resolve4(hostname[, options])</code><span><a class="mark" href="#all_dns_dnspromisesresolve4hostname-options" id="all_dns_dnspromisesresolve4hostname-options">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolve4_hostname_options"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host name to resolve.</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>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Retrieve the Time-To-Live value (TTL) of each record.
When <code>true</code>, the <code>Promise</code> is resolved with an array of
<code>{ address: '1.2.3.4', ttl: 60 }</code> objects rather than an array of strings,
with the TTL expressed in seconds.</li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve IPv4 addresses (<code>A</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of IPv4
addresses (e.g. <code>['74.125.79.104', '74.125.79.105', '74.125.79.106']</code>).</p>
<h4><code>dnsPromises.resolve6(hostname[, options])</code><span><a class="mark" href="#all_dns_dnspromisesresolve6hostname-options" id="all_dns_dnspromisesresolve6hostname-options">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolve6_hostname_options"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host name to resolve.</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>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Retrieve the Time-To-Live value (TTL) of each record.
When <code>true</code>, the <code>Promise</code> is resolved with an array of
<code>{ address: '0:1:2:3:4:5:6:7', ttl: 60 }</code> objects rather than an array of
strings, with the TTL expressed in seconds.</li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve IPv6 addresses (<code>AAAA</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of IPv6
addresses.</p>
<h4><code>dnsPromises.resolveAny(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolveanyhostname" id="all_dns_dnspromisesresolveanyhostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolveany_hostname"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Uses the DNS protocol to resolve all records (also known as <code>ANY</code> or <code>*</code> query).
On success, the <code>Promise</code> is resolved with an array containing various types of
records. Each object has a property <code>type</code> that indicates the type of the
current record. And depending on the <code>type</code>, additional properties will be
present on the object:</p>
<table><thead><tr><th>Type</th><th>Properties</th></tr></thead><tbody><tr><td><code>'A'</code></td><td><code>address</code>/<code>ttl</code></td></tr><tr><td><code>'AAAA'</code></td><td><code>address</code>/<code>ttl</code></td></tr><tr><td><code>'CNAME'</code></td><td><code>value</code></td></tr><tr><td><code>'MX'</code></td><td>Refer to <a href="#all_dns_dnspromisesresolvemxhostname"><code>dnsPromises.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>Refer to <a href="#all_dns_dnspromisesresolvenaptrhostname"><code>dnsPromises.resolveNaptr()</code></a></td></tr><tr><td><code>'NS'</code></td><td><code>value</code></td></tr><tr><td><code>'PTR'</code></td><td><code>value</code></td></tr><tr><td><code>'SOA'</code></td><td>Refer to <a href="#all_dns_dnspromisesresolvesoahostname"><code>dnsPromises.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>Refer to <a href="#all_dns_dnspromisesresolvesrvhostname"><code>dnsPromises.resolveSrv()</code></a></td></tr><tr><td><code>'TXT'</code></td><td>This type of record contains an array property called <code>entries</code> which refers to <a href="#all_dns_dnspromisesresolvetxthostname"><code>dnsPromises.resolveTxt()</code></a>, e.g. <code>{ entries: ['...'], type: 'TXT' }</code></td></tr></tbody></table>
<p>Here is an example of the result object:</p>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js">[ { <span class="hljs-attr">type</span>: <span class="hljs-string">'A'</span>, <span class="hljs-attr">address</span>: <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-attr">ttl</span>: <span class="hljs-number">299</span> },
{ <span class="hljs-attr">type</span>: <span class="hljs-string">'CNAME'</span>, <span class="hljs-attr">value</span>: <span class="hljs-string">'example.com'</span> },
{ <span class="hljs-attr">type</span>: <span class="hljs-string">'MX'</span>, <span class="hljs-attr">exchange</span>: <span class="hljs-string">'alt4.aspmx.l.example.com'</span>, <span class="hljs-attr">priority</span>: <span class="hljs-number">50</span> },
{ <span class="hljs-attr">type</span>: <span class="hljs-string">'NS'</span>, <span class="hljs-attr">value</span>: <span class="hljs-string">'ns1.example.com'</span> },
{ <span class="hljs-attr">type</span>: <span class="hljs-string">'TXT'</span>, <span class="hljs-attr">entries</span>: [ <span class="hljs-string">'v=spf1 include:_spf.example.com ~all'</span> ] },
{ <span class="hljs-attr">type</span>: <span class="hljs-string">'SOA'</span>,
<span class="hljs-attr">nsname</span>: <span class="hljs-string">'ns1.example.com'</span>,
<span class="hljs-attr">hostmaster</span>: <span class="hljs-string">'admin.example.com'</span>,
<span class="hljs-attr">serial</span>: <span class="hljs-number">156696742</span>,
<span class="hljs-attr">refresh</span>: <span class="hljs-number">900</span>,
<span class="hljs-attr">retry</span>: <span class="hljs-number">900</span>,
<span class="hljs-attr">expire</span>: <span class="hljs-number">1800</span>,
<span class="hljs-attr">minttl</span>: <span class="hljs-number">60</span> } ]</code> <button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.resolveCaa(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvecaahostname" id="all_dns_dnspromisesresolvecaahostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvecaa_hostname"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.17.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Uses the DNS protocol to resolve <code>CAA</code> records for the <code>hostname</code>. On success,
the <code>Promise</code> is resolved with an array of objects containing available
certification authority authorization records available for the <code>hostname</code>
(e.g. <code>[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]</code>).</p>
<h4><code>dnsPromises.resolveCname(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvecnamehostname" id="all_dns_dnspromisesresolvecnamehostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvecname_hostname"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Uses the DNS protocol to resolve <code>CNAME</code> records for the <code>hostname</code>. On success,
the <code>Promise</code> is resolved with an array of canonical name records available for
the <code>hostname</code> (e.g. <code>['bar.example.com']</code>).</p>
<h4><code>dnsPromises.resolveMx(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvemxhostname" id="all_dns_dnspromisesresolvemxhostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvemx_hostname"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Uses the DNS protocol to resolve mail exchange records (<code>MX</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of objects
containing both a <code>priority</code> and <code>exchange</code> property (e.g.
<code>[{priority: 10, exchange: 'mx.example.com'}, ...]</code>).</p>
<h4><code>dnsPromises.resolveNaptr(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvenaptrhostname" id="all_dns_dnspromisesresolvenaptrhostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvenaptr_hostname"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Uses the DNS protocol to resolve regular expression-based records (<code>NAPTR</code>
records) for the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an array
of objects with the following properties:</p>
<ul>
<li><code>flags</code></li>
<li><code>service</code></li>
<li><code>regexp</code></li>
<li><code>replacement</code></li>
<li><code>order</code></li>
<li><code>preference</code></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
<span class="hljs-attr">flags</span>: <span class="hljs-string">'s'</span>,
<span class="hljs-attr">service</span>: <span class="hljs-string">'SIP+D2U'</span>,
<span class="hljs-attr">regexp</span>: <span class="hljs-string">''</span>,
<span class="hljs-attr">replacement</span>: <span class="hljs-string">'_sip._udp.example.com'</span>,
<span class="hljs-attr">order</span>: <span class="hljs-number">30</span>,
<span class="hljs-attr">preference</span>: <span class="hljs-number">100</span>
}</code> <button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.resolveNs(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvenshostname" id="all_dns_dnspromisesresolvenshostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvens_hostname"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Uses the DNS protocol to resolve name server records (<code>NS</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of name server
records available for <code>hostname</code> (e.g.
<code>['ns1.example.com', 'ns2.example.com']</code>).</p>
<h4><code>dnsPromises.resolvePtr(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolveptrhostname" id="all_dns_dnspromisesresolveptrhostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolveptr_hostname"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Uses the DNS protocol to resolve pointer records (<code>PTR</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of strings
containing the reply records.</p>
<h4><code>dnsPromises.resolveSoa(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvesoahostname" id="all_dns_dnspromisesresolvesoahostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvesoa_hostname"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Uses the DNS protocol to resolve a start of authority record (<code>SOA</code> record) for
the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an object with the
following properties:</p>
<ul>
<li><code>nsname</code></li>
<li><code>hostmaster</code></li>
<li><code>serial</code></li>
<li><code>refresh</code></li>
<li><code>retry</code></li>
<li><code>expire</code></li>
<li><code>minttl</code></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
<span class="hljs-attr">nsname</span>: <span class="hljs-string">'ns.example.com'</span>,
<span class="hljs-attr">hostmaster</span>: <span class="hljs-string">'root.example.com'</span>,
<span class="hljs-attr">serial</span>: <span class="hljs-number">2013101809</span>,
<span class="hljs-attr">refresh</span>: <span class="hljs-number">10000</span>,
<span class="hljs-attr">retry</span>: <span class="hljs-number">2400</span>,
<span class="hljs-attr">expire</span>: <span class="hljs-number">604800</span>,
<span class="hljs-attr">minttl</span>: <span class="hljs-number">3600</span>
}</code> <button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.resolveSrv(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvesrvhostname" id="all_dns_dnspromisesresolvesrvhostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvesrv_hostname"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Uses the DNS protocol to resolve service records (<code>SRV</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of objects with
the following properties:</p>
<ul>
<li><code>priority</code></li>
<li><code>weight</code></li>
<li><code>port</code></li>
<li><code>name</code></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
<span class="hljs-attr">priority</span>: <span class="hljs-number">10</span>,
<span class="hljs-attr">weight</span>: <span class="hljs-number">5</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">21223</span>,
<span class="hljs-attr">name</span>: <span class="hljs-string">'service.example.com'</span>
}</code> <button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.resolveTxt(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvetxthostname" id="all_dns_dnspromisesresolvetxthostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvetxt_hostname"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Uses the DNS protocol to resolve text queries (<code>TXT</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with a two-dimensional array
of the text records available for <code>hostname</code> (e.g.
<code>[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]</code>). Each sub-array contains TXT chunks of
one record. Depending on the use case, these could be either joined together or
treated separately.</p>
<h4><code>dnsPromises.reverse(ip)</code><span><a class="mark" href="#all_dns_dnspromisesreverseip" id="all_dns_dnspromisesreverseip">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_reverse_ip"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>ip</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
array of host names.</p>
<p>On error, the <code>Promise</code> is rejected with an <a href="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code>
is one of the <a href="#all_dns_error-codes">DNS error codes</a>.</p>
<h4><code>dnsPromises.setDefaultResultOrder(order)</code><span><a class="mark" href="#all_dns_dnspromisessetdefaultresultorderorder" id="all_dns_dnspromisessetdefaultresultorderorder">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_setdefaultresultorder_order"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>ipv6first</code> value is supported now.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p>Changed default value to <code>verbatim</code>.</p></td></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p><span>Added in: v16.4.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>order</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> must be <code>'ipv4first'</code>, <code>'ipv6first'</code> or <code>'verbatim'</code>.</li>
</ul>
<p>Set the default value of <code>order</code> in <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> and
<a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup()</code></a>. The value could be:</p>
<ul>
<li><code>ipv4first</code>: sets default <code>order</code> to <code>ipv4first</code>.</li>
<li><code>ipv6first</code>: sets default <code>order</code> to <code>ipv6first</code>.</li>
<li><code>verbatim</code>: sets default <code>order</code> to <code>verbatim</code>.</li>
</ul>
<p>The default is <code>verbatim</code> and <a href="#all_dns_dnspromisessetdefaultresultorderorder"><code>dnsPromises.setDefaultResultOrder()</code></a> have
higher priority than <a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order</code></a>. When using <a href="worker_threads.html">worker threads</a>,
<a href="#all_dns_dnspromisessetdefaultresultorderorder"><code>dnsPromises.setDefaultResultOrder()</code></a> from the main thread won't affect the
default dns orders in workers.</p>
<h4><code>dnsPromises.getDefaultResultOrder()</code><span><a class="mark" href="#all_dns_dnspromisesgetdefaultresultorder" id="all_dns_dnspromisesgetdefaultresultorder">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_getdefaultresultorder"></a></h4>
<div class="api_metadata">
<span>Added in: v20.1.0</span>
</div>
<p>Get the value of <code>dnsOrder</code>.</p>
<h4><code>dnsPromises.setServers(servers)</code><span><a class="mark" href="#all_dns_dnspromisessetserversservers" id="all_dns_dnspromisessetserversservers">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_setservers_servers"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>servers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> array of <a href="https://tools.ietf.org/html/rfc5952#section-6">RFC 5952</a> formatted addresses</li>
</ul>
<p>Sets the IP address and port of servers to be used when performing DNS
resolution. The <code>servers</code> argument is an array of <a href="https://tools.ietf.org/html/rfc5952#section-6">RFC 5952</a> formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.</p>
<pre><code class="language-js">dnsPromises.<span class="hljs-title function_">setServers</span>([
<span class="hljs-string">'8.8.8.8'</span>,
<span class="hljs-string">'[2001:4860:4860::8888]'</span>,
<span class="hljs-string">'8.8.8.8:1053'</span>,
<span class="hljs-string">'[2001:4860:4860::8888]:1053'</span>,
]);</code> <button class="copy-button">copy</button></pre>
<p>An error will be thrown if an invalid address is provided.</p>
<p>The <code>dnsPromises.setServers()</code> method must not be called while a DNS query is in
progress.</p>
<p>This method works much like
<a href="https://man7.org/linux/man-pages/man5/resolv.conf.5.html">resolve.conf</a>.
That is, if attempting to resolve with the first server provided results in a
<code>NOTFOUND</code> error, the <code>resolve()</code> method will <em>not</em> attempt to resolve with
subsequent servers provided. Fallback DNS servers will only be used if the
earlier ones time out or result in some other error.</p>
</section><section><h3>Error codes<span><a class="mark" href="#all_dns_error-codes" id="all_dns_error-codes">#</a></span><a aria-hidden="true" class="legacy" id="dns_error_codes"></a></h3>
<p>Each DNS query can return one of the following error codes:</p>
<ul>
<li><code>dns.NODATA</code>: DNS server returned an answer with no data.</li>
<li><code>dns.FORMERR</code>: DNS server claims query was misformatted.</li>
<li><code>dns.SERVFAIL</code>: DNS server returned general failure.</li>
<li><code>dns.NOTFOUND</code>: Domain name not found.</li>
<li><code>dns.NOTIMP</code>: DNS server does not implement the requested operation.</li>
<li><code>dns.REFUSED</code>: DNS server refused query.</li>
<li><code>dns.BADQUERY</code>: Misformatted DNS query.</li>
<li><code>dns.BADNAME</code>: Misformatted host name.</li>
<li><code>dns.BADFAMILY</code>: Unsupported address family.</li>
<li><code>dns.BADRESP</code>: Misformatted DNS reply.</li>
<li><code>dns.CONNREFUSED</code>: Could not contact DNS servers.</li>
<li><code>dns.TIMEOUT</code>: Timeout while contacting DNS servers.</li>
<li><code>dns.EOF</code>: End of file.</li>
<li><code>dns.FILE</code>: Error reading file.</li>
<li><code>dns.NOMEM</code>: Out of memory.</li>
<li><code>dns.DESTRUCTION</code>: Channel is being destroyed.</li>
<li><code>dns.BADSTR</code>: Misformatted string.</li>
<li><code>dns.BADFLAGS</code>: Illegal flags specified.</li>
<li><code>dns.NONAME</code>: Given host name is not numeric.</li>
<li><code>dns.BADHINTS</code>: Illegal hints flags specified.</li>
<li><code>dns.NOTINITIALIZED</code>: c-ares library initialization not yet performed.</li>
<li><code>dns.LOADIPHLPAPI</code>: Error loading <code>iphlpapi.dll</code>.</li>
<li><code>dns.ADDRGETNETWORKPARAMS</code>: Could not find <code>GetNetworkParams</code> function.</li>
<li><code>dns.CANCELLED</code>: DNS query cancelled.</li>
</ul>
<p>The <code>dnsPromises</code> API also exports the above error codes, e.g., <code>dnsPromises.NODATA</code>.</p>
</section><section><h3>Implementation considerations<span><a class="mark" href="#all_dns_implementation-considerations" id="all_dns_implementation-considerations">#</a></span><a aria-hidden="true" class="legacy" id="dns_implementation_considerations"></a></h3>
<p>Although <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> and the various <code>dns.resolve*()/dns.reverse()</code>
functions have the same goal of associating a network name with a network
address (or vice versa), their behavior is quite different. These differences
can have subtle but significant consequences on the behavior of Node.js
programs.</p>
<h4><code>dns.lookup()</code><span><a class="mark" href="#all_dns_dnslookup" id="all_dns_dnslookup">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_lookup"></a></h4>
<p>Under the hood, <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> uses the same operating system facilities
as most other programs. For instance, <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> will almost always
resolve a given name the same way as the <code>ping</code> command. On most POSIX-like
operating systems, the behavior of the <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> function can be
modified by changing settings in <a href="http://man7.org/linux/man-pages/man5/nsswitch.conf.5.html"><code>nsswitch.conf(5)</code></a> and/or <a href="http://man7.org/linux/man-pages/man5/resolv.conf.5.html"><code>resolv.conf(5)</code></a>,
but changing these files will change the behavior of all other
programs running on the same operating system.</p>
<p>Though the call to <code>dns.lookup()</code> will be asynchronous from JavaScript's
perspective, it is implemented as a synchronous call to <a href="http://man7.org/linux/man-pages/man3/getaddrinfo.3.html"><code>getaddrinfo(3)</code></a> that runs
on libuv's threadpool. This can have surprising negative performance
implications for some applications, see the <a href="#all_cli_uv_threadpool_sizesize"><code>UV_THREADPOOL_SIZE</code></a>
documentation for more information.</p>
<p>Various networking APIs will call <code>dns.lookup()</code> internally to resolve
host names. If that is an issue, consider resolving the host name to an address
using <code>dns.resolve()</code> and using the address instead of a host name. Also, some
networking APIs (such as <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect()</code></a> and <a href="#all_dgram_dgramcreatesocketoptions-callback"><code>dgram.createSocket()</code></a>)
allow the default resolver, <code>dns.lookup()</code>, to be replaced.</p>
<h4><code>dns.resolve()</code>, <code>dns.resolve*()</code>, and <code>dns.reverse()</code><span><a class="mark" href="#all_dns_dnsresolve-dnsresolve-and-dnsreverse" id="all_dns_dnsresolve-dnsresolve-and-dnsreverse">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolve_dns_resolve_and_dns_reverse"></a></h4>
<p>These functions are implemented quite differently than <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>. They
do not use <a href="http://man7.org/linux/man-pages/man3/getaddrinfo.3.html"><code>getaddrinfo(3)</code></a> and they <em>always</em> perform a DNS query on the
network. This network communication is always done asynchronously and does not
use libuv's threadpool.</p>
<p>As a result, these functions cannot have the same negative impact on other
processing that happens on libuv's threadpool that <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> can have.</p>
<p>They do not use the same set of configuration files that <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>
uses. For instance, they do not use the configuration from <code>/etc/hosts</code>.</p></section>
</section>
<section><h2>Domain<span><a class="mark" href="#all_domain_domain" id="all_domain_domain">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain"></a></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.8.0</td>
<td><p>Any <code>Promise</code>s created in VM contexts no longer have a <code>.domain</code> property. Their handlers are still executed in the proper domain, however, and <code>Promise</code>s created in the main context still possess a <code>.domain</code> property.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Handlers for <code>Promise</code>s are now invoked in the domain in which the first promise of a chain was created.</p></td></tr>
<tr><td>v1.4.2</td>
<td><p><span>Deprecated since: v1.4.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/domain.js">lib/domain.js</a></p>
<p><strong>This module is pending deprecation.</strong> Once a replacement API has been
finalized, this module will be fully deprecated. Most developers should
<strong>not</strong> have cause to use this module. Users who absolutely must have
the functionality that domains provide may rely on it for the time being
but should expect to have to migrate to a different solution
in the future.</p>
<p>Domains provide a way to handle multiple different IO operations as a
single group. If any of the event emitters or callbacks registered to a
domain emit an <code>'error'</code> event, or throw an error, then the domain object
will be notified, rather than losing the context of the error in the
<code>process.on('uncaughtException')</code> handler, or causing the program to
exit immediately with an error code.</p>
<section><h3>Warning: Don't ignore errors!<span><a class="mark" href="#all_domain_warning-dont-ignore-errors" id="all_domain_warning-dont-ignore-errors">#</a></span><a aria-hidden="true" class="legacy" id="domain_warning_don_t_ignore_errors"></a></h3>
<p>Domain error handlers are not a substitute for closing down a
process when an error occurs.</p>
<p>By the very nature of how <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw"><code>throw</code></a> works in JavaScript, there is almost
never any way to safely "pick up where it left off", without leaking
references, or creating some other sort of undefined brittle state.</p>
<p>The safest way to respond to a thrown error is to shut down the
process. Of course, in a normal web server, there may be many
open connections, and it is not reasonable to abruptly shut those down
because an error was triggered by someone else.</p>
<p>The better approach is to send an error response to the request that
triggered the error, while letting the others finish in their normal
time, and stop listening for new requests in that worker.</p>
<p>In this way, <code>domain</code> usage goes hand-in-hand with the cluster module,
since the primary process can fork a new worker when a worker
encounters an error. For Node.js programs that scale to multiple
machines, the terminating proxy or service registry can take note of
the failure, and react accordingly.</p>
<p>For example, this is not a good idea:</p>
<pre><code class="language-js"><span class="hljs-comment">// XXX WARNING! BAD IDEA!</span>
<span class="hljs-keyword">const</span> d = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:domain'</span>).<span class="hljs-title function_">create</span>();
d.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> {
<span class="hljs-comment">// The error won't crash the process, but what it does is worse!</span>
<span class="hljs-comment">// Though we've prevented abrupt process restarting, we are leaking</span>
<span class="hljs-comment">// a lot of resources if this ever happens.</span>
<span class="hljs-comment">// This is no better than process.on('uncaughtException')!</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`error, but oh well <span class="hljs-subst">${er.message}</span>`</span>);
});
d.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
<span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>).<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
<span class="hljs-title function_">handleRequest</span>(req, res);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-variable constant_">PORT</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>By using the context of a domain, and the resilience of separating our
program into multiple worker processes, we can react more
appropriately, and handle errors with much greater safety.</p>
<pre><code class="language-js"><span class="hljs-comment">// Much better!</span>
<span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">PORT</span> = +process.<span class="hljs-property">env</span>.<span class="hljs-property">PORT</span> || <span class="hljs-number">1337</span>;
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
<span class="hljs-comment">// A more realistic scenario would have more than 2 workers,</span>
<span class="hljs-comment">// and perhaps not put the primary and worker in the same file.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// It is also possible to get a bit fancier about logging, and</span>
<span class="hljs-comment">// implement whatever custom logic is needed to prevent DoS</span>
<span class="hljs-comment">// attacks and other bad behavior.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// See the options in the cluster documentation.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The important thing is that the primary does very little,</span>
<span class="hljs-comment">// increasing our resilience to unexpected errors.</span>
cluster.<span class="hljs-title function_">fork</span>();
cluster.<span class="hljs-title function_">fork</span>();
cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'disconnect!'</span>);
cluster.<span class="hljs-title function_">fork</span>();
});
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// the worker</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// This is where we put our bugs!</span>
<span class="hljs-keyword">const</span> domain = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:domain'</span>);
<span class="hljs-comment">// See the cluster documentation for more details about using</span>
<span class="hljs-comment">// worker processes to serve requests. How it works, caveats, etc.</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>).<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> d = domain.<span class="hljs-title function_">create</span>();
d.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`error <span class="hljs-subst">${er.stack}</span>`</span>);
<span class="hljs-comment">// We're in dangerous territory!</span>
<span class="hljs-comment">// By definition, something unexpected occurred,</span>
<span class="hljs-comment">// which we probably didn't want.</span>
<span class="hljs-comment">// Anything can happen now! Be very careful!</span>
<span class="hljs-keyword">try</span> {
<span class="hljs-comment">// Make sure we close down within 30 seconds</span>
<span class="hljs-keyword">const</span> killtimer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>);
}, <span class="hljs-number">30000</span>);
<span class="hljs-comment">// But don't keep the process open just for that!</span>
killtimer.<span class="hljs-title function_">unref</span>();
<span class="hljs-comment">// Stop taking new requests.</span>
server.<span class="hljs-title function_">close</span>();
<span class="hljs-comment">// Let the primary know we're dead. This will trigger a</span>
<span class="hljs-comment">// 'disconnect' in the cluster primary, and then it will fork</span>
<span class="hljs-comment">// a new worker.</span>
cluster.<span class="hljs-property">worker</span>.<span class="hljs-title function_">disconnect</span>();
<span class="hljs-comment">// Try to send an error to the request that triggered the problem</span>
res.<span class="hljs-property">statusCode</span> = <span class="hljs-number">500</span>;
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'content-type'</span>, <span class="hljs-string">'text/plain'</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Oops, there was a problem!\n'</span>);
} <span class="hljs-keyword">catch</span> (er2) {
<span class="hljs-comment">// Oh well, not much we can do at this point.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Error sending 500! <span class="hljs-subst">${er2.stack}</span>`</span>);
}
});
<span class="hljs-comment">// Because req and res were created before this domain existed,</span>
<span class="hljs-comment">// we need to explicitly add them.</span>
<span class="hljs-comment">// See the explanation of implicit vs explicit binding below.</span>
d.<span class="hljs-title function_">add</span>(req);
d.<span class="hljs-title function_">add</span>(res);
<span class="hljs-comment">// Now run the handler function in the domain.</span>
d.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
<span class="hljs-title function_">handleRequest</span>(req, res);
});
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-variable constant_">PORT</span>);
}
<span class="hljs-comment">// This part is not important. Just an example routing thing.</span>
<span class="hljs-comment">// Put fancy application logic here.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">handleRequest</span>(<span class="hljs-params">req, res</span>) {
<span class="hljs-keyword">switch</span> (req.<span class="hljs-property">url</span>) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'/error'</span>:
<span class="hljs-comment">// We do some async stuff, and then...</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// Whoops!</span>
flerb.<span class="hljs-title function_">bark</span>();
}, timeout);
<span class="hljs-keyword">break</span>;
<span class="hljs-attr">default</span>:
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
}
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Additions to <code>Error</code> objects<span><a class="mark" href="#all_domain_additions-to-error-objects" id="all_domain_additions-to-error-objects">#</a></span><a aria-hidden="true" class="legacy" id="domain_additions_to_error_objects"></a></h3>
<p>Any time an <code>Error</code> object is routed through a domain, a few extra fields
are added to it.</p>
<ul>
<li><code>error.domain</code> The domain that first handled the error.</li>
<li><code>error.domainEmitter</code> The event emitter that emitted an <code>'error'</code> event
with the error object.</li>
<li><code>error.domainBound</code> The callback function which was bound to the
domain, and passed an error as its first argument.</li>
<li><code>error.domainThrown</code> A boolean indicating whether the error was
thrown, emitted, or passed to a bound callback function.</li>
</ul>
</section><section><h3>Implicit binding<span><a class="mark" href="#all_domain_implicit-binding" id="all_domain_implicit-binding">#</a></span><a aria-hidden="true" class="legacy" id="domain_implicit_binding"></a></h3>
<p>If domains are in use, then all <strong>new</strong> <code>EventEmitter</code> objects (including
Stream objects, requests, responses, etc.) will be implicitly bound to
the active domain at the time of their creation.</p>
<p>Additionally, callbacks passed to low-level event loop requests (such as
to <code>fs.open()</code>, or other callback-taking methods) will automatically be
bound to the active domain. If they throw, then the domain will catch
the error.</p>
<p>In order to prevent excessive memory usage, <code>Domain</code> objects themselves
are not implicitly added as children of the active domain. If they
were, then it would be too easy to prevent request and response objects
from being properly garbage collected.</p>
<p>To nest <code>Domain</code> objects as children of a parent <code>Domain</code> they must be
explicitly added.</p>
<p>Implicit binding routes thrown errors and <code>'error'</code> events to the
<code>Domain</code>'s <code>'error'</code> event, but does not register the <code>EventEmitter</code> on the
<code>Domain</code>.
Implicit binding only takes care of thrown errors and <code>'error'</code> events.</p>
</section><section><h3>Explicit binding<span><a class="mark" href="#all_domain_explicit-binding" id="all_domain_explicit-binding">#</a></span><a aria-hidden="true" class="legacy" id="domain_explicit_binding"></a></h3>
<p>Sometimes, the domain in use is not the one that ought to be used for a
specific event emitter. Or, the event emitter could have been created
in the context of one domain, but ought to instead be bound to some
other domain.</p>
<p>For example, there could be one domain in use for an HTTP server, but
perhaps we would like to have a separate domain to use for each request.</p>
<p>That is possible via explicit binding.</p>
<pre><code class="language-js"><span class="hljs-comment">// Create a top-level domain for the server</span>
<span class="hljs-keyword">const</span> domain = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:domain'</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> serverDomain = domain.<span class="hljs-title function_">create</span>();
serverDomain.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// Server is created in the scope of serverDomain</span>
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 and res are also created in the scope of serverDomain</span>
<span class="hljs-comment">// however, we'd prefer to have a separate domain for each request.</span>
<span class="hljs-comment">// create it first thing, and add req and res to it.</span>
<span class="hljs-keyword">const</span> reqd = domain.<span class="hljs-title function_">create</span>();
reqd.<span class="hljs-title function_">add</span>(req);
reqd.<span class="hljs-title function_">add</span>(res);
reqd.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Error'</span>, er, req.<span class="hljs-property">url</span>);
<span class="hljs-keyword">try</span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">500</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Error occurred, sorry.'</span>);
} <span class="hljs-keyword">catch</span> (er2) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Error sending 500'</span>, er2, req.<span class="hljs-property">url</span>);
}
});
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>domain.create()</code><span><a class="mark" href="#all_domain_domaincreate" id="all_domain_domaincreate">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_create"></a></h3>
<ul>
<li>Returns: <a href="#all_domain_class-domain" class="type"><Domain></a></li>
</ul>
</section><section><h3>Class: <code>Domain</code><span><a class="mark" href="#all_domain_class-domain" id="all_domain_class-domain">#</a></span><a aria-hidden="true" class="legacy" id="domain_class_domain"></a></h3>
<ul>
<li>Extends: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>The <code>Domain</code> class encapsulates the functionality of routing errors and
uncaught exceptions to the active <code>Domain</code> object.</p>
<p>To handle the errors that it catches, listen to its <code>'error'</code> event.</p>
<h4><code>domain.members</code><span><a class="mark" href="#all_domain_domainmembers" id="all_domain_domainmembers">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_members"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>An array of timers and event emitters that have been explicitly added
to the domain.</p>
<h4><code>domain.add(emitter)</code><span><a class="mark" href="#all_domain_domainaddemitter" id="all_domain_domainaddemitter">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_add_emitter"></a></h4>
<ul>
<li><code>emitter</code> <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a> | <a href="#all_timers_timers" class="type"><Timer></a> emitter or timer to be added to the domain</li>
</ul>
<p>Explicitly adds an emitter to the domain. If any event handlers called by
the emitter throw an error, or if the emitter emits an <code>'error'</code> event, it
will be routed to the domain's <code>'error'</code> event, just like with implicit
binding.</p>
<p>This also works with timers that are returned from <a href="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a> and
<a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a>. If their callback function throws, it will be caught by
the domain <code>'error'</code> handler.</p>
<p>If the Timer or <code>EventEmitter</code> was already bound to a domain, it is removed
from that one, and bound to this one instead.</p>
<h4><code>domain.bind(callback)</code><span><a class="mark" href="#all_domain_domainbindcallback" id="all_domain_domainbindcallback">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_bind_callback"></a></h4>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The bound function</li>
</ul>
<p>The returned function will be a wrapper around the supplied callback
function. When the returned function is called, any errors that are
thrown will be routed to the domain's <code>'error'</code> event.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> d = domain.<span class="hljs-title function_">create</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">readSomeFile</span>(<span class="hljs-params">filename, cb</span>) {
fs.<span class="hljs-title function_">readFile</span>(filename, <span class="hljs-string">'utf8'</span>, d.<span class="hljs-title function_">bind</span>(<span class="hljs-function">(<span class="hljs-params">er, data</span>) =></span> {
<span class="hljs-comment">// If this throws, it will also be passed to the domain.</span>
<span class="hljs-keyword">return</span> <span class="hljs-title function_">cb</span>(er, data ? <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(data) : <span class="hljs-literal">null</span>);
}));
}
d.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> {
<span class="hljs-comment">// An error occurred somewhere. If we throw it now, it will crash the program</span>
<span class="hljs-comment">// with the normal line number and stack message.</span>
});</code> <button class="copy-button">copy</button></pre>
<h4><code>domain.enter()</code><span><a class="mark" href="#all_domain_domainenter" id="all_domain_domainenter">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_enter"></a></h4>
<p>The <code>enter()</code> method is plumbing used by the <code>run()</code>, <code>bind()</code>, and
<code>intercept()</code> methods to set the active domain. It sets <code>domain.active</code> and
<code>process.domain</code> to the domain, and implicitly pushes the domain onto the domain
stack managed by the domain module (see <a href="#all_domain_domainexit"><code>domain.exit()</code></a> for details on the
domain stack). The call to <code>enter()</code> delimits the beginning of a chain of
asynchronous calls and I/O operations bound to a domain.</p>
<p>Calling <code>enter()</code> changes only the active domain, and does not alter the domain
itself. <code>enter()</code> and <code>exit()</code> can be called an arbitrary number of times on a
single domain.</p>
<h4><code>domain.exit()</code><span><a class="mark" href="#all_domain_domainexit" id="all_domain_domainexit">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_exit"></a></h4>
<p>The <code>exit()</code> method exits the current domain, popping it off the domain stack.
Any time execution is going to switch to the context of a different chain of
asynchronous calls, it's important to ensure that the current domain is exited.
The call to <code>exit()</code> delimits either the end of or an interruption to the chain
of asynchronous calls and I/O operations bound to a domain.</p>
<p>If there are multiple, nested domains bound to the current execution context,
<code>exit()</code> will exit any domains nested within this domain.</p>
<p>Calling <code>exit()</code> changes only the active domain, and does not alter the domain
itself. <code>enter()</code> and <code>exit()</code> can be called an arbitrary number of times on a
single domain.</p>
<h4><code>domain.intercept(callback)</code><span><a class="mark" href="#all_domain_domaininterceptcallback" id="all_domain_domaininterceptcallback">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_intercept_callback"></a></h4>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The intercepted function</li>
</ul>
<p>This method is almost identical to <a href="#all_domain_domainbindcallback"><code>domain.bind(callback)</code></a>. However, in
addition to catching thrown errors, it will also intercept <a href="#all_errors_class-error"><code>Error</code></a>
objects sent as the first argument to the function.</p>
<p>In this way, the common <code>if (err) return callback(err);</code> pattern can be replaced
with a single error handler in a single place.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> d = domain.<span class="hljs-title function_">create</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">readSomeFile</span>(<span class="hljs-params">filename, cb</span>) {
fs.<span class="hljs-title function_">readFile</span>(filename, <span class="hljs-string">'utf8'</span>, d.<span class="hljs-title function_">intercept</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-comment">// Note, the first argument is never passed to the</span>
<span class="hljs-comment">// callback since it is assumed to be the 'Error' argument</span>
<span class="hljs-comment">// and thus intercepted by the domain.</span>
<span class="hljs-comment">// If this throws, it will also be passed to the domain</span>
<span class="hljs-comment">// so the error-handling logic can be moved to the 'error'</span>
<span class="hljs-comment">// event on the domain instead of being repeated throughout</span>
<span class="hljs-comment">// the program.</span>
<span class="hljs-keyword">return</span> <span class="hljs-title function_">cb</span>(<span class="hljs-literal">null</span>, <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(data));
}));
}
d.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> {
<span class="hljs-comment">// An error occurred somewhere. If we throw it now, it will crash the program</span>
<span class="hljs-comment">// with the normal line number and stack message.</span>
});</code> <button class="copy-button">copy</button></pre>
<h4><code>domain.remove(emitter)</code><span><a class="mark" href="#all_domain_domainremoveemitter" id="all_domain_domainremoveemitter">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_remove_emitter"></a></h4>
<ul>
<li><code>emitter</code> <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a> | <a href="#all_timers_timers" class="type"><Timer></a> emitter or timer to be removed from the domain</li>
</ul>
<p>The opposite of <a href="#all_domain_domainaddemitter"><code>domain.add(emitter)</code></a>. Removes domain handling from the
specified emitter.</p>
<h4><code>domain.run(fn[, ...args])</code><span><a class="mark" href="#all_domain_domainrunfn-args" id="all_domain_domainrunfn-args">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_run_fn_args"></a></h4>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Run the supplied function in the context of the domain, implicitly
binding all event emitters, timers, and low-level requests that are
created in that context. Optionally, arguments can be passed to
the function.</p>
<p>This is the most basic way to use a domain.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> domain = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:domain'</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> d = domain.<span class="hljs-title function_">create</span>();
d.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Caught error!'</span>, er);
});
d.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { <span class="hljs-comment">// Simulating some various async stuff</span>
fs.<span class="hljs-title function_">open</span>(<span class="hljs-string">'non-existent file'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">er, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (er) <span class="hljs-keyword">throw</span> er;
<span class="hljs-comment">// proceed...</span>
});
}, <span class="hljs-number">100</span>);
});
});</code> <button class="copy-button">copy</button></pre>
<p>In this example, the <code>d.on('error')</code> handler will be triggered, rather
than crashing the program.</p>
</section><section><h3>Domains and promises<span><a class="mark" href="#all_domain_domains-and-promises" id="all_domain_domains-and-promises">#</a></span><a aria-hidden="true" class="legacy" id="domain_domains_and_promises"></a></h3>
<p>As of Node.js 8.0.0, the handlers of promises are run inside the domain in
which the call to <code>.then()</code> or <code>.catch()</code> itself was made:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> d1 = domain.<span class="hljs-title function_">create</span>();
<span class="hljs-keyword">const</span> d2 = domain.<span class="hljs-title function_">create</span>();
<span class="hljs-keyword">let</span> p;
d1.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
p = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">42</span>);
});
d2.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
p.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">v</span>) =></span> {
<span class="hljs-comment">// running in d2</span>
});
});</code> <button class="copy-button">copy</button></pre>
<p>A callback may be bound to a specific domain using <a href="#all_domain_domainbindcallback"><code>domain.bind(callback)</code></a>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> d1 = domain.<span class="hljs-title function_">create</span>();
<span class="hljs-keyword">const</span> d2 = domain.<span class="hljs-title function_">create</span>();
<span class="hljs-keyword">let</span> p;
d1.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
p = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">42</span>);
});
d2.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
p.<span class="hljs-title function_">then</span>(p.<span class="hljs-property">domain</span>.<span class="hljs-title function_">bind</span>(<span class="hljs-function">(<span class="hljs-params">v</span>) =></span> {
<span class="hljs-comment">// running in d1</span>
}));
});</code> <button class="copy-button">copy</button></pre>
<p>Domains will not interfere with the error handling mechanisms for
promises. In other words, no <code>'error'</code> event will be emitted for unhandled
<code>Promise</code> rejections.</p></section>
</section>
<section><h2>Errors<span><a class="mark" href="#all_errors_errors" id="all_errors_errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_errors"></a></h2>
<p>Applications running in Node.js will generally experience four categories of
errors:</p>
<ul>
<li>Standard JavaScript errors such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError" class="type"><EvalError></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError" class="type"><SyntaxError></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError" class="type"><RangeError></a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError" class="type"><ReferenceError></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError" class="type"><TypeError></a>, and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError" class="type"><URIError></a>.</li>
<li>System errors triggered by underlying operating system constraints such
as attempting to open a file that does not exist or attempting to send data
over a closed socket.</li>
<li>User-specified errors triggered by application code.</li>
<li><code>AssertionError</code>s are a special class of error that can be triggered when
Node.js detects an exceptional logic violation that should never occur. These
are raised typically by the <code>node:assert</code> module.</li>
</ul>
<p>All JavaScript and system errors raised by Node.js inherit from, or are
instances of, the standard JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> class and are guaranteed
to provide <em>at least</em> the properties available on that class.</p>
<section><h3>Error propagation and interception<span><a class="mark" href="#all_errors_error-propagation-and-interception" id="all_errors_error-propagation-and-interception">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_propagation_and_interception"></a></h3>
<p>Node.js supports several mechanisms for propagating and handling errors that
occur while an application is running. How these errors are reported and
handled depends entirely on the type of <code>Error</code> and the style of the API that is
called.</p>
<p>All JavaScript errors are handled as exceptions that <em>immediately</em> generate
and throw an error using the standard JavaScript <code>throw</code> mechanism. These
are handled using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch"><code>try…catch</code> construct</a> provided by the
JavaScript language.</p>
<pre><code class="language-js"><span class="hljs-comment">// Throws with a ReferenceError because z is not defined.</span>
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> m = <span class="hljs-number">1</span>;
<span class="hljs-keyword">const</span> n = m + z;
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-comment">// Handle the error here.</span>
}</code> <button class="copy-button">copy</button></pre>
<p>Any use of the JavaScript <code>throw</code> mechanism will raise an exception that
<em>must</em> be handled or the Node.js process will exit immediately.</p>
<p>With few exceptions, <em>Synchronous</em> APIs (any blocking method that does not
return a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> nor accept a <code>callback</code> function, such as
<a href="#all_fs_fsreadfilesyncpath-options"><code>fs.readFileSync</code></a>), will use <code>throw</code> to report errors.</p>
<p>Errors that occur within <em>Asynchronous APIs</em> may be reported in multiple ways:</p>
<ul>
<li>
<p>Some asynchronous methods returns a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a>, you should always take into
account that it might be rejected. See <a href="#all_cli_--unhandled-rejectionsmode"><code>--unhandled-rejections</code></a> flag for
how the process will react to an unhandled promise rejection.</p>
<!-- eslint-disable no-useless-return -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs/promises'</span>);
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">let</span> data;
<span class="hljs-keyword">try</span> {
data = <span class="hljs-keyword">await</span> fs.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'a file that does not exist'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'There was an error reading the file!'</span>, err);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-comment">// Otherwise handle the data</span>
})();</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Most asynchronous methods that accept a <code>callback</code> function will accept an
<code>Error</code> object passed as the first argument to that function. If that first
argument is not <code>null</code> and is an instance of <code>Error</code>, then an error occurred
that should be handled.</p>
<!-- eslint-disable no-useless-return -->
<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>);
fs.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'a file that does not exist'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</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">'There was an error reading the file!'</span>, err);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-comment">// Otherwise handle the data</span>
});</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>When an asynchronous method is called on an object that is an
<a href="#all_events_class-eventemitter"><code>EventEmitter</code></a>, errors can be routed to that object's <code>'error'</code> event.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> connection = net.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'localhost'</span>);
<span class="hljs-comment">// Adding an 'error' event handler to a stream:</span>
connection.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-comment">// If the connection is reset by the server, or if it can't</span>
<span class="hljs-comment">// connect at all, or on any sort of error encountered by</span>
<span class="hljs-comment">// the connection, the error will be sent here.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
});
connection.<span class="hljs-title function_">pipe</span>(process.<span class="hljs-property">stdout</span>);</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>A handful of typically asynchronous methods in the Node.js API may still
use the <code>throw</code> mechanism to raise exceptions that must be handled using
<code>try…catch</code>. There is no comprehensive list of such methods; please
refer to the documentation of each method to determine the appropriate
error handling mechanism required.</p>
</li>
</ul>
<p>The use of the <code>'error'</code> event mechanism is most common for <a href="stream.html">stream-based</a>
and <a href="#all_events_class-eventemitter">event emitter-based</a> APIs, which themselves represent a series of
asynchronous operations over time (as opposed to a single operation that may
pass or fail).</p>
<p>For <em>all</em> <a href="#all_events_class-eventemitter"><code>EventEmitter</code></a> objects, if an <code>'error'</code> event handler is not
provided, the error will be thrown, causing the Node.js process to report an
uncaught exception and crash unless either: a handler has been registered for
the <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a> event, or the deprecated <a href="domain.html"><code>node:domain</code></a>
module is used.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// This will crash the process because no 'error' event</span>
<span class="hljs-comment">// handler has been added.</span>
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'This will crash'</span>));
});</code> <button class="copy-button">copy</button></pre>
<p>Errors generated in this way <em>cannot</em> be intercepted using <code>try…catch</code> as
they are thrown <em>after</em> the calling code has already exited.</p>
<p>Developers must refer to the documentation for each method to determine
exactly how errors raised by those methods are propagated.</p>
</section><section><h3>Class: <code>Error</code><span><a class="mark" href="#all_errors_class-error" id="all_errors_class-error">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_error"></a></h3>
<p>A generic JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> object that does not denote any specific
circumstance of why the error occurred. <code>Error</code> objects capture a "stack trace"
detailing the point in the code at which the <code>Error</code> was instantiated, and may
provide a text description of the error.</p>
<p>All errors generated by Node.js, including all system and JavaScript errors,
will either be instances of, or inherit from, the <code>Error</code> class.</p>
<h4><code>new Error(message[, options])</code><span><a class="mark" href="#all_errors_new-errormessage-options" id="all_errors_new-errormessage-options">#</a></span><a aria-hidden="true" class="legacy" id="errors_new_error_message_options"></a></h4>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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>cause</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The error that caused the newly created error.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>Error</code> object and sets the <code>error.message</code> property to the
provided text message. If an object is passed as <code>message</code>, the text message
is generated by calling <code>String(message)</code>. If the <code>cause</code> option is provided,
it is assigned to the <code>error.cause</code> property. The <code>error.stack</code> property will
represent the point in the code at which <code>new Error()</code> was called. Stack traces
are dependent on <a href="https://v8.dev/docs/stack-trace-api">V8's stack trace API</a>. Stack traces extend only to either
(a) the beginning of <em>synchronous code execution</em>, or (b) the number of frames
given by the property <code>Error.stackTraceLimit</code>, whichever is smaller.</p>
<h4><code>Error.captureStackTrace(targetObject[, constructorOpt])</code><span><a class="mark" href="#all_errors_errorcapturestacktracetargetobject-constructoropt" id="all_errors_errorcapturestacktracetargetobject-constructoropt">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_capturestacktrace_targetobject_constructoropt"></a></h4>
<ul>
<li><code>targetObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>constructorOpt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>Creates a <code>.stack</code> property on <code>targetObject</code>, which when accessed returns
a string representing the location in the code at which
<code>Error.captureStackTrace()</code> was called.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myObject = {};
<span class="hljs-title class_">Error</span>.<span class="hljs-title function_">captureStackTrace</span>(myObject);
myObject.<span class="hljs-property">stack</span>; <span class="hljs-comment">// Similar to `new Error().stack`</span></code> <button class="copy-button">copy</button></pre>
<p>The first line of the trace will be prefixed with
<code>${myObject.name}: ${myObject.message}</code>.</p>
<p>The optional <code>constructorOpt</code> argument accepts a function. If given, all frames
above <code>constructorOpt</code>, including <code>constructorOpt</code>, will be omitted from the
generated stack trace.</p>
<p>The <code>constructorOpt</code> argument is useful for hiding implementation
details of error generation from the user. For instance:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">a</span>(<span class="hljs-params"></span>) {
<span class="hljs-title function_">b</span>();
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">b</span>(<span class="hljs-params"></span>) {
<span class="hljs-title function_">c</span>();
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">c</span>(<span class="hljs-params"></span>) {
<span class="hljs-comment">// Create an error without stack trace to avoid calculating the stack trace twice.</span>
<span class="hljs-keyword">const</span> { stackTraceLimit } = <span class="hljs-title class_">Error</span>;
<span class="hljs-title class_">Error</span>.<span class="hljs-property">stackTraceLimit</span> = <span class="hljs-number">0</span>;
<span class="hljs-keyword">const</span> error = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>();
<span class="hljs-title class_">Error</span>.<span class="hljs-property">stackTraceLimit</span> = stackTraceLimit;
<span class="hljs-comment">// Capture the stack trace above function b</span>
<span class="hljs-title class_">Error</span>.<span class="hljs-title function_">captureStackTrace</span>(error, b); <span class="hljs-comment">// Neither function c, nor b is included in the stack trace</span>
<span class="hljs-keyword">throw</span> error;
}
<span class="hljs-title function_">a</span>();</code> <button class="copy-button">copy</button></pre>
<h4><code>Error.stackTraceLimit</code><span><a class="mark" href="#all_errors_errorstacktracelimit" id="all_errors_errorstacktracelimit">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_stacktracelimit"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The <code>Error.stackTraceLimit</code> property specifies the number of stack frames
collected by a stack trace (whether generated by <code>new Error().stack</code> or
<code>Error.captureStackTrace(obj)</code>).</p>
<p>The default value is <code>10</code> but may be set to any valid JavaScript number. Changes
will affect any stack trace captured <em>after</em> the value has been changed.</p>
<p>If set to a non-number value, or set to a negative number, stack traces will
not capture any frames.</p>
<h4><code>error.cause</code><span><a class="mark" href="#all_errors_errorcause" id="all_errors_errorcause">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_cause"></a></h4>
<div class="api_metadata">
<span>Added in: v16.9.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>If present, the <code>error.cause</code> property is the underlying cause of the <code>Error</code>.
It is used when catching an error and throwing a new one with a different
message or code in order to still have access to the original error.</p>
<p>The <code>error.cause</code> property is typically set by calling
<code>new Error(message, { cause })</code>. It is not set by the constructor if the
<code>cause</code> option is not provided.</p>
<p>This property allows errors to be chained. When serializing <code>Error</code> objects,
<a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> recursively serializes <code>error.cause</code> if it is set.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> cause = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'The remote HTTP server responded with a 500 status'</span>);
<span class="hljs-keyword">const</span> symptom = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'The message failed to send'</span>, { cause });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(symptom);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// Error: The message failed to send</span>
<span class="hljs-comment">// at REPL2:1:17</span>
<span class="hljs-comment">// at Script.runInThisContext (node:vm:130:12)</span>
<span class="hljs-comment">// ... 7 lines matching cause stack trace ...</span>
<span class="hljs-comment">// at [_line] [as _line] (node:internal/readline/interface:886:18) {</span>
<span class="hljs-comment">// [cause]: Error: The remote HTTP server responded with a 500 status</span>
<span class="hljs-comment">// at REPL1:1:15</span>
<span class="hljs-comment">// at Script.runInThisContext (node:vm:130:12)</span>
<span class="hljs-comment">// at REPLServer.defaultEval (node:repl:574:29)</span>
<span class="hljs-comment">// at bound (node:domain:426:15)</span>
<span class="hljs-comment">// at REPLServer.runBound [as eval] (node:domain:437:12)</span>
<span class="hljs-comment">// at REPLServer.onLine (node:repl:902:10)</span>
<span class="hljs-comment">// at REPLServer.emit (node:events:549:35)</span>
<span class="hljs-comment">// at REPLServer.emit (node:domain:482:12)</span>
<span class="hljs-comment">// at [_onLine] [as _onLine] (node:internal/readline/interface:425:12)</span>
<span class="hljs-comment">// at [_line] [as _line] (node:internal/readline/interface:886:18)</span></code> <button class="copy-button">copy</button></pre>
<h4><code>error.code</code><span><a class="mark" href="#all_errors_errorcode" id="all_errors_errorcode">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_code"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>error.code</code> property is a string label that identifies the kind of error.
<code>error.code</code> is the most stable way to identify an error. It will only change
between major versions of Node.js. In contrast, <code>error.message</code> strings may
change between any versions of Node.js. See <a href="#all_errors_nodejs-error-codes">Node.js error codes</a> for details
about specific codes.</p>
<h4><code>error.message</code><span><a class="mark" href="#all_errors_errormessage" id="all_errors_errormessage">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_message"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>error.message</code> property is the string description of the error as set by
calling <code>new Error(message)</code>. The <code>message</code> passed to the constructor will also
appear in the first line of the stack trace of the <code>Error</code>, however changing
this property after the <code>Error</code> object is created <em>may not</em> change the first
line of the stack trace (for example, when <code>error.stack</code> is read before this
property is changed).</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'The message'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>);
<span class="hljs-comment">// Prints: The message</span></code> <button class="copy-button">copy</button></pre>
<h4><code>error.stack</code><span><a class="mark" href="#all_errors_errorstack" id="all_errors_errorstack">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_stack"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>error.stack</code> property is a string describing the point in the code at which
the <code>Error</code> was instantiated.</p>
<pre><code class="language-console">Error: Things keep happening!
at /home/gbusey/file.js:525:2
at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)
at Actor.<anonymous> (/home/gbusey/actors.js:400:8)
at increaseSynergy (/home/gbusey/actors.js:701:6)</code> <button class="copy-button">copy</button></pre>
<p>The first line is formatted as <code><error class name>: <error message></code>, and
is followed by a series of stack frames (each line beginning with "at ").
Each frame describes a call site within the code that lead to the error being
generated. V8 attempts to display a name for each function (by variable name,
function name, or object method name), but occasionally it will not be able to
find a suitable name. If V8 cannot determine a name for the function, only
location information will be displayed for that frame. Otherwise, the
determined function name will be displayed with location information appended
in parentheses.</p>
<p>Frames are only generated for JavaScript functions. If, for example, execution
synchronously passes through a C++ addon function called <code>cheetahify</code> which
itself calls a JavaScript function, the frame representing the <code>cheetahify</code> call
will not be present in the stack traces:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> cheetahify = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./native-binding.node'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">makeFaster</span>(<span class="hljs-params"></span>) {
<span class="hljs-comment">// `cheetahify()` *synchronously* calls speedy.</span>
<span class="hljs-title function_">cheetahify</span>(<span class="hljs-keyword">function</span> <span class="hljs-title function_">speedy</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'oh no!'</span>);
});
}
<span class="hljs-title function_">makeFaster</span>();
<span class="hljs-comment">// will throw:</span>
<span class="hljs-comment">// /home/gbusey/file.js:6</span>
<span class="hljs-comment">// throw new Error('oh no!');</span>
<span class="hljs-comment">// ^</span>
<span class="hljs-comment">// Error: oh no!</span>
<span class="hljs-comment">// at speedy (/home/gbusey/file.js:6:11)</span>
<span class="hljs-comment">// at makeFaster (/home/gbusey/file.js:5:3)</span>
<span class="hljs-comment">// at Object.<anonymous> (/home/gbusey/file.js:10:1)</span>
<span class="hljs-comment">// at Module._compile (module.js:456:26)</span>
<span class="hljs-comment">// at Object.Module._extensions..js (module.js:474:10)</span>
<span class="hljs-comment">// at Module.load (module.js:356:32)</span>
<span class="hljs-comment">// at Function.Module._load (module.js:312:12)</span>
<span class="hljs-comment">// at Function.Module.runMain (module.js:497:10)</span>
<span class="hljs-comment">// at startup (node.js:119:16)</span>
<span class="hljs-comment">// at node.js:906:3</span></code> <button class="copy-button">copy</button></pre>
<p>The location information will be one of:</p>
<ul>
<li><code>native</code>, if the frame represents a call internal to V8 (as in <code>[].forEach</code>).</li>
<li><code>plain-filename.js:line:column</code>, if the frame represents a call internal
to Node.js.</li>
<li><code>/absolute/path/to/file.js:line:column</code>, if the frame represents a call in
a user program (using CommonJS module system), or its dependencies.</li>
<li><code><transport-protocol>:///url/to/module/file.mjs:line:column</code>, if the frame
represents a call in a user program (using ES module system), or
its dependencies.</li>
</ul>
<p>The string representing the stack trace is lazily generated when the
<code>error.stack</code> property is <strong>accessed</strong>.</p>
<p>The number of frames captured by the stack trace is bounded by the smaller of
<code>Error.stackTraceLimit</code> or the number of available frames on the current event
loop tick.</p>
</section><section><h3>Class: <code>AssertionError</code><span><a class="mark" href="#all_errors_class-assertionerror" id="all_errors_class-assertionerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_assertionerror"></a></h3>
<ul>
<li>Extends: <a href="#all_errors_class-error" class="type"><errors.Error></a></li>
</ul>
<p>Indicates the failure of an assertion. For details, see
<a href="#all_assert_class-assertassertionerror"><code>Class: assert.AssertionError</code></a>.</p>
</section><section><h3>Class: <code>RangeError</code><span><a class="mark" href="#all_errors_class-rangeerror" id="all_errors_class-rangeerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_rangeerror"></a></h3>
<ul>
<li>Extends: <a href="#all_errors_class-error" class="type"><errors.Error></a></li>
</ul>
<p>Indicates that a provided argument was not within the set or range of
acceptable values for a function; whether that is a numeric range, or
outside the set of options for a given function parameter.</p>
<pre><code class="language-js"><span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>).<span class="hljs-title function_">connect</span>(-<span class="hljs-number">1</span>);
<span class="hljs-comment">// Throws "RangeError: "port" option should be >= 0 and < 65536: -1"</span></code> <button class="copy-button">copy</button></pre>
<p>Node.js will generate and throw <code>RangeError</code> instances <em>immediately</em> as a form
of argument validation.</p>
</section><section><h3>Class: <code>ReferenceError</code><span><a class="mark" href="#all_errors_class-referenceerror" id="all_errors_class-referenceerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_referenceerror"></a></h3>
<ul>
<li>Extends: <a href="#all_errors_class-error" class="type"><errors.Error></a></li>
</ul>
<p>Indicates that an attempt is being made to access a variable that is not
defined. Such errors commonly indicate typos in code, or an otherwise broken
program.</p>
<p>While client code may generate and propagate these errors, in practice, only V8
will do so.</p>
<pre><code class="language-js">doesNotExist;
<span class="hljs-comment">// Throws ReferenceError, doesNotExist is not a variable in this program.</span></code> <button class="copy-button">copy</button></pre>
<p>Unless an application is dynamically generating and running code,
<code>ReferenceError</code> instances indicate a bug in the code or its dependencies.</p>
</section><section><h3>Class: <code>SyntaxError</code><span><a class="mark" href="#all_errors_class-syntaxerror" id="all_errors_class-syntaxerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_syntaxerror"></a></h3>
<ul>
<li>Extends: <a href="#all_errors_class-error" class="type"><errors.Error></a></li>
</ul>
<p>Indicates that a program is not valid JavaScript. These errors may only be
generated and propagated as a result of code evaluation. Code evaluation may
happen as a result of <code>eval</code>, <code>Function</code>, <code>require</code>, or <a href="vm.html">vm</a>. These errors
are almost always indicative of a broken program.</p>
<pre><code class="language-js"><span class="hljs-keyword">try</span> {
<span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>).<span class="hljs-title function_">runInThisContext</span>(<span class="hljs-string">'binary ! isNotOk'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-comment">// 'err' will be a SyntaxError.</span>
}</code> <button class="copy-button">copy</button></pre>
<p><code>SyntaxError</code> instances are unrecoverable in the context that created them –
they may only be caught by other contexts.</p>
</section><section><h3>Class: <code>SystemError</code><span><a class="mark" href="#all_errors_class-systemerror" id="all_errors_class-systemerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_systemerror"></a></h3>
<ul>
<li>Extends: <a href="#all_errors_class-error" class="type"><errors.Error></a></li>
</ul>
<p>Node.js generates system errors when exceptions occur within its runtime
environment. These usually occur when an application violates an operating
system constraint. For example, a system error will occur if an application
attempts to read a file that does not exist.</p>
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If present, the address to which a network connection
failed</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The string error code</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If present, the file path destination when reporting a file
system error</li>
<li><code>errno</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The system-provided error number</li>
<li><code>info</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> If present, extra details about the error condition</li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A system-provided human-readable description of the error</li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If present, the file path when reporting a file system error</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If present, the network connection port that is not available</li>
<li><code>syscall</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the system call that triggered the error</li>
</ul>
<h4><code>error.address</code><span><a class="mark" href="#all_errors_erroraddress" id="all_errors_erroraddress">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_address"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>If present, <code>error.address</code> is a string describing the address to which a
network connection failed.</p>
<h4><code>error.code</code><span><a class="mark" href="#all_errors_errorcode_1" id="all_errors_errorcode_1">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_code_1"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>error.code</code> property is a string representing the error code.</p>
<h4><code>error.dest</code><span><a class="mark" href="#all_errors_errordest" id="all_errors_errordest">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_dest"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>If present, <code>error.dest</code> is the file path destination when reporting a file
system error.</p>
<h4><code>error.errno</code><span><a class="mark" href="#all_errors_errorerrno" id="all_errors_errorerrno">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_errno"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The <code>error.errno</code> property is a negative number which corresponds
to the error code defined in <a href="https://docs.libuv.org/en/v1.x/errors.html"><code>libuv Error handling</code></a>.</p>
<p>On Windows the error number provided by the system will be normalized by libuv.</p>
<p>To get the string representation of the error code, use
<a href="#all_util_utilgetsystemerrornameerr"><code>util.getSystemErrorName(error.errno)</code></a>.</p>
<h4><code>error.info</code><span><a class="mark" href="#all_errors_errorinfo" id="all_errors_errorinfo">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_info"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>If present, <code>error.info</code> is an object with details about the error condition.</p>
<h4><code>error.message</code><span><a class="mark" href="#all_errors_errormessage_1" id="all_errors_errormessage_1">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_message_1"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p><code>error.message</code> is a system-provided human-readable description of the error.</p>
<h4><code>error.path</code><span><a class="mark" href="#all_errors_errorpath" id="all_errors_errorpath">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_path"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>If present, <code>error.path</code> is a string containing a relevant invalid pathname.</p>
<h4><code>error.port</code><span><a class="mark" href="#all_errors_errorport" id="all_errors_errorport">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_port"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>If present, <code>error.port</code> is the network connection port that is not available.</p>
<h4><code>error.syscall</code><span><a class="mark" href="#all_errors_errorsyscall" id="all_errors_errorsyscall">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_syscall"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>error.syscall</code> property is a string describing the <a href="https://man7.org/linux/man-pages/man2/syscalls.2.html">syscall</a> that failed.</p>
<h4>Common system errors<span><a class="mark" href="#all_errors_common-system-errors" id="all_errors_common-system-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_common_system_errors"></a></h4>
<p>This is a list of system errors commonly-encountered when writing a Node.js
program. For a comprehensive list, see the <a href="https://man7.org/linux/man-pages/man3/errno.3.html"><code>errno</code>(3) man page</a>.</p>
<ul>
<li>
<p><code>EACCES</code> (Permission denied): An attempt was made to access a file in a way
forbidden by its file access permissions.</p>
</li>
<li>
<p><code>EADDRINUSE</code> (Address already in use): An attempt to bind a server
(<a href="net.html"><code>net</code></a>, <a href="http.html"><code>http</code></a>, or <a href="https.html"><code>https</code></a>) to a local address failed due to
another server on the local system already occupying that address.</p>
</li>
<li>
<p><code>ECONNREFUSED</code> (Connection refused): No connection could be made because the
target machine actively refused it. This usually results from trying to
connect to a service that is inactive on the foreign host.</p>
</li>
<li>
<p><code>ECONNRESET</code> (Connection reset by peer): A connection was forcibly closed by
a peer. This normally results from a loss of the connection on the remote
socket due to a timeout or reboot. Commonly encountered via the <a href="http.html"><code>http</code></a>
and <a href="net.html"><code>net</code></a> modules.</p>
</li>
<li>
<p><code>EEXIST</code> (File exists): An existing file was the target of an operation that
required that the target not exist.</p>
</li>
<li>
<p><code>EISDIR</code> (Is a directory): An operation expected a file, but the given
pathname was a directory.</p>
</li>
<li>
<p><code>EMFILE</code> (Too many open files in system): Maximum number of
<a href="https://en.wikipedia.org/wiki/File_descriptor">file descriptors</a> allowable on the system has been reached, and
requests for another descriptor cannot be fulfilled until at least one
has been closed. This is encountered when opening many files at once in
parallel, especially on systems (in particular, macOS) where there is a low
file descriptor limit for processes. To remedy a low limit, run
<code>ulimit -n 2048</code> in the same shell that will run the Node.js process.</p>
</li>
<li>
<p><code>ENOENT</code> (No such file or directory): Commonly raised by <a href="fs.html"><code>fs</code></a> operations
to indicate that a component of the specified pathname does not exist. No
entity (file or directory) could be found by the given path.</p>
</li>
<li>
<p><code>ENOTDIR</code> (Not a directory): A component of the given pathname existed, but
was not a directory as expected. Commonly raised by <a href="#all_fs_fsreaddirpath-options-callback"><code>fs.readdir</code></a>.</p>
</li>
<li>
<p><code>ENOTEMPTY</code> (Directory not empty): A directory with entries was the target
of an operation that requires an empty directory, usually <a href="#all_fs_fsunlinkpath-callback"><code>fs.unlink</code></a>.</p>
</li>
<li>
<p><code>ENOTFOUND</code> (DNS lookup failed): Indicates a DNS failure of either
<code>EAI_NODATA</code> or <code>EAI_NONAME</code>. This is not a standard POSIX error.</p>
</li>
<li>
<p><code>EPERM</code> (Operation not permitted): An attempt was made to perform an
operation that requires elevated privileges.</p>
</li>
<li>
<p><code>EPIPE</code> (Broken pipe): A write on a pipe, socket, or FIFO for which there is
no process to read the data. Commonly encountered at the <a href="net.html"><code>net</code></a> and
<a href="http.html"><code>http</code></a> layers, indicative that the remote side of the stream being
written to has been closed.</p>
</li>
<li>
<p><code>ETIMEDOUT</code> (Operation timed out): A connect or send request failed because
the connected party did not properly respond after a period of time. Usually
encountered by <a href="http.html"><code>http</code></a> or <a href="net.html"><code>net</code></a>. Often a sign that a <code>socket.end()</code>
was not properly called.</p>
</li>
</ul>
</section><section><h3>Class: <code>TypeError</code><span><a class="mark" href="#all_errors_class-typeerror" id="all_errors_class-typeerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_typeerror"></a></h3>
<ul>
<li>Extends <a href="#all_errors_class-error" class="type"><errors.Error></a></li>
</ul>
<p>Indicates that a provided argument is not an allowable type. For example,
passing a function to a parameter which expects a string would be a <code>TypeError</code>.</p>
<pre><code class="language-js"><span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>).<span class="hljs-title function_">parse</span>(<span class="hljs-function">() =></span> { });
<span class="hljs-comment">// Throws TypeError, since it expected a string.</span></code> <button class="copy-button">copy</button></pre>
<p>Node.js will generate and throw <code>TypeError</code> instances <em>immediately</em> as a form
of argument validation.</p>
</section><section><h3>Exceptions vs. errors<span><a class="mark" href="#all_errors_exceptions-vs-errors" id="all_errors_exceptions-vs-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_exceptions_vs_errors"></a></h3>
<p>A JavaScript exception is a value that is thrown as a result of an invalid
operation or as the target of a <code>throw</code> statement. While it is not required
that these values are instances of <code>Error</code> or classes which inherit from
<code>Error</code>, all exceptions thrown by Node.js or the JavaScript runtime <em>will</em> be
instances of <code>Error</code>.</p>
<p>Some exceptions are <em>unrecoverable</em> at the JavaScript layer. Such exceptions
will <em>always</em> cause the Node.js process to crash. Examples include <code>assert()</code>
checks or <code>abort()</code> calls in the C++ layer.</p>
</section><section><h3>OpenSSL errors<span><a class="mark" href="#all_errors_openssl-errors" id="all_errors_openssl-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_openssl_errors"></a></h3>
<p>Errors originating in <code>crypto</code> or <code>tls</code> are of class <code>Error</code>, and in addition to
the standard <code>.code</code> and <code>.message</code> properties, may have some additional
OpenSSL-specific properties.</p>
<h4><code>error.opensslErrorStack</code><span><a class="mark" href="#all_errors_erroropensslerrorstack" id="all_errors_erroropensslerrorstack">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_opensslerrorstack"></a></h4>
<p>An array of errors that can give context to where in the OpenSSL library an
error originates from.</p>
<h4><code>error.function</code><span><a class="mark" href="#all_errors_errorfunction" id="all_errors_errorfunction">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_function"></a></h4>
<p>The OpenSSL function the error originates in.</p>
<h4><code>error.library</code><span><a class="mark" href="#all_errors_errorlibrary" id="all_errors_errorlibrary">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_library"></a></h4>
<p>The OpenSSL library the error originates in.</p>
<h4><code>error.reason</code><span><a class="mark" href="#all_errors_errorreason" id="all_errors_errorreason">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_reason"></a></h4>
<p>A human-readable string describing the reason for the error.</p>
<p><a id="nodejs-error-codes"></a></p>
</section><section><h3>Node.js error codes<span><a class="mark" href="#all_errors_nodejs-error-codes" id="all_errors_nodejs-error-codes">#</a></span><a aria-hidden="true" class="legacy" id="errors_node_js_error_codes"></a></h3>
<p><a id="ABORT_ERR"></a></p>
<h4><code>ABORT_ERR</code><span><a class="mark" href="#all_errors_abort_err" id="all_errors_abort_err">#</a></span><a aria-hidden="true" class="legacy" id="errors_abort_err"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>Used when an operation has been aborted (typically using an <code>AbortController</code>).</p>
<p>APIs <em>not</em> using <code>AbortSignal</code>s typically do not raise an error with this code.</p>
<p>This code does not use the regular <code>ERR_*</code> convention Node.js errors use in
order to be compatible with the web platform's <code>AbortError</code>.</p>
<p><a id="ERR_ACCESS_DENIED"></a></p>
<h4><code>ERR_ACCESS_DENIED</code><span><a class="mark" href="#all_errors_err_access_denied" id="all_errors_err_access_denied">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_access_denied"></a></h4>
<p>A special type of error that is triggered whenever Node.js tries to get access
to a resource restricted by the <a href="#all_permissions_permission-model">Permission Model</a>.</p>
<p><a id="ERR_AMBIGUOUS_ARGUMENT"></a></p>
<h4><code>ERR_AMBIGUOUS_ARGUMENT</code><span><a class="mark" href="#all_errors_err_ambiguous_argument" id="all_errors_err_ambiguous_argument">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_ambiguous_argument"></a></h4>
<p>A function argument is being used in a way that suggests that the function
signature may be misunderstood. This is thrown by the <code>node:assert</code> module when
the <code>message</code> parameter in <code>assert.throws(block, message)</code> matches the error
message thrown by <code>block</code> because that usage suggests that the user believes
<code>message</code> is the expected message rather than the message the <code>AssertionError</code>
will display if <code>block</code> does not throw.</p>
<p><a id="ERR_ARG_NOT_ITERABLE"></a></p>
<h4><code>ERR_ARG_NOT_ITERABLE</code><span><a class="mark" href="#all_errors_err_arg_not_iterable" id="all_errors_err_arg_not_iterable">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_arg_not_iterable"></a></h4>
<p>An iterable argument (i.e. a value that works with <code>for...of</code> loops) was
required, but not provided to a Node.js API.</p>
<p><a id="ERR_ASSERTION"></a></p>
<h4><code>ERR_ASSERTION</code><span><a class="mark" href="#all_errors_err_assertion" id="all_errors_err_assertion">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_assertion"></a></h4>
<p>A special type of error that can be triggered whenever Node.js detects an
exceptional logic violation that should never occur. These are raised typically
by the <code>node:assert</code> module.</p>
<p><a id="ERR_ASYNC_CALLBACK"></a></p>
<h4><code>ERR_ASYNC_CALLBACK</code><span><a class="mark" href="#all_errors_err_async_callback" id="all_errors_err_async_callback">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_async_callback"></a></h4>
<p>An attempt was made to register something that is not a function as an
<code>AsyncHooks</code> callback.</p>
<p><a id="ERR_ASYNC_TYPE"></a></p>
<h4><code>ERR_ASYNC_TYPE</code><span><a class="mark" href="#all_errors_err_async_type" id="all_errors_err_async_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_async_type"></a></h4>
<p>The type of an asynchronous resource was invalid. Users are also able
to define their own types if using the public embedder API.</p>
<p><a id="ERR_BROTLI_COMPRESSION_FAILED"></a></p>
<h4><code>ERR_BROTLI_COMPRESSION_FAILED</code><span><a class="mark" href="#all_errors_err_brotli_compression_failed" id="all_errors_err_brotli_compression_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_brotli_compression_failed"></a></h4>
<p>Data passed to a Brotli stream was not successfully compressed.</p>
<p><a id="ERR_BROTLI_INVALID_PARAM"></a></p>
<h4><code>ERR_BROTLI_INVALID_PARAM</code><span><a class="mark" href="#all_errors_err_brotli_invalid_param" id="all_errors_err_brotli_invalid_param">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_brotli_invalid_param"></a></h4>
<p>An invalid parameter key was passed during construction of a Brotli stream.</p>
<p><a id="ERR_BUFFER_CONTEXT_NOT_AVAILABLE"></a></p>
<h4><code>ERR_BUFFER_CONTEXT_NOT_AVAILABLE</code><span><a class="mark" href="#all_errors_err_buffer_context_not_available" id="all_errors_err_buffer_context_not_available">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_buffer_context_not_available"></a></h4>
<p>An attempt was made to create a Node.js <code>Buffer</code> instance from addon or embedder
code, while in a JS engine Context that is not associated with a Node.js
instance. The data passed to the <code>Buffer</code> method will have been released
by the time the method returns.</p>
<p>When encountering this error, a possible alternative to creating a <code>Buffer</code>
instance is to create a normal <code>Uint8Array</code>, which only differs in the
prototype of the resulting object. <code>Uint8Array</code>s are generally accepted in all
Node.js core APIs where <code>Buffer</code>s are; they are available in all Contexts.</p>
<p><a id="ERR_BUFFER_OUT_OF_BOUNDS"></a></p>
<h4><code>ERR_BUFFER_OUT_OF_BOUNDS</code><span><a class="mark" href="#all_errors_err_buffer_out_of_bounds" id="all_errors_err_buffer_out_of_bounds">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_buffer_out_of_bounds"></a></h4>
<p>An operation outside the bounds of a <code>Buffer</code> was attempted.</p>
<p><a id="ERR_BUFFER_TOO_LARGE"></a></p>
<h4><code>ERR_BUFFER_TOO_LARGE</code><span><a class="mark" href="#all_errors_err_buffer_too_large" id="all_errors_err_buffer_too_large">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_buffer_too_large"></a></h4>
<p>An attempt has been made to create a <code>Buffer</code> larger than the maximum allowed
size.</p>
<p><a id="ERR_CANNOT_WATCH_SIGINT"></a></p>
<h4><code>ERR_CANNOT_WATCH_SIGINT</code><span><a class="mark" href="#all_errors_err_cannot_watch_sigint" id="all_errors_err_cannot_watch_sigint">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_cannot_watch_sigint"></a></h4>
<p>Node.js was unable to watch for the <code>SIGINT</code> signal.</p>
<p><a id="ERR_CHILD_CLOSED_BEFORE_REPLY"></a></p>
<h4><code>ERR_CHILD_CLOSED_BEFORE_REPLY</code><span><a class="mark" href="#all_errors_err_child_closed_before_reply" id="all_errors_err_child_closed_before_reply">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_child_closed_before_reply"></a></h4>
<p>A child process was closed before the parent received a reply.</p>
<p><a id="ERR_CHILD_PROCESS_IPC_REQUIRED"></a></p>
<h4><code>ERR_CHILD_PROCESS_IPC_REQUIRED</code><span><a class="mark" href="#all_errors_err_child_process_ipc_required" id="all_errors_err_child_process_ipc_required">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_child_process_ipc_required"></a></h4>
<p>Used when a child process is being forked without specifying an IPC channel.</p>
<p><a id="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"></a></p>
<h4><code>ERR_CHILD_PROCESS_STDIO_MAXBUFFER</code><span><a class="mark" href="#all_errors_err_child_process_stdio_maxbuffer" id="all_errors_err_child_process_stdio_maxbuffer">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_child_process_stdio_maxbuffer"></a></h4>
<p>Used when the main process is trying to read data from the child process's
STDERR/STDOUT, and the data's length is longer than the <code>maxBuffer</code> option.</p>
<p><a id="ERR_CLOSED_MESSAGE_PORT"></a></p>
<h4><code>ERR_CLOSED_MESSAGE_PORT</code><span><a class="mark" href="#all_errors_err_closed_message_port" id="all_errors_err_closed_message_port">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_closed_message_port"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.2.0, v14.17.1</td>
<td><p>The error message was reintroduced.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p>The error message was removed.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>There was an attempt to use a <code>MessagePort</code> instance in a closed
state, usually after <code>.close()</code> has been called.</p>
<p><a id="ERR_CONSOLE_WRITABLE_STREAM"></a></p>
<h4><code>ERR_CONSOLE_WRITABLE_STREAM</code><span><a class="mark" href="#all_errors_err_console_writable_stream" id="all_errors_err_console_writable_stream">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_console_writable_stream"></a></h4>
<p><code>Console</code> was instantiated without <code>stdout</code> stream, or <code>Console</code> has a
non-writable <code>stdout</code> or <code>stderr</code> stream.</p>
<p><a id="ERR_CONSTRUCT_CALL_INVALID"></a></p>
<h4><code>ERR_CONSTRUCT_CALL_INVALID</code><span><a class="mark" href="#all_errors_err_construct_call_invalid" id="all_errors_err_construct_call_invalid">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_construct_call_invalid"></a></h4>
<div class="api_metadata">
<span>Added in: v12.5.0</span>
</div>
<p>A class constructor was called that is not callable.</p>
<p><a id="ERR_CONSTRUCT_CALL_REQUIRED"></a></p>
<h4><code>ERR_CONSTRUCT_CALL_REQUIRED</code><span><a class="mark" href="#all_errors_err_construct_call_required" id="all_errors_err_construct_call_required">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_construct_call_required"></a></h4>
<p>A constructor for a class was called without <code>new</code>.</p>
<p><a id="ERR_CONTEXT_NOT_INITIALIZED"></a></p>
<h4><code>ERR_CONTEXT_NOT_INITIALIZED</code><span><a class="mark" href="#all_errors_err_context_not_initialized" id="all_errors_err_context_not_initialized">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_context_not_initialized"></a></h4>
<p>The vm context passed into the API is not yet initialized. This could happen
when an error occurs (and is caught) during the creation of the
context, for example, when the allocation fails or the maximum call stack
size is reached when the context is created.</p>
<p><a id="ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED"></a></p>
<h4><code>ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED</code><span><a class="mark" href="#all_errors_err_crypto_custom_engine_not_supported" id="all_errors_err_crypto_custom_engine_not_supported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_custom_engine_not_supported"></a></h4>
<p>An OpenSSL engine was requested (for example, through the <code>clientCertEngine</code> or
<code>privateKeyEngine</code> TLS options) that is not supported by the version of OpenSSL
being used, likely due to the compile-time flag <code>OPENSSL_NO_ENGINE</code>.</p>
<p><a id="ERR_CRYPTO_ECDH_INVALID_FORMAT"></a></p>
<h4><code>ERR_CRYPTO_ECDH_INVALID_FORMAT</code><span><a class="mark" href="#all_errors_err_crypto_ecdh_invalid_format" id="all_errors_err_crypto_ecdh_invalid_format">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_ecdh_invalid_format"></a></h4>
<p>An invalid value for the <code>format</code> argument was passed to the <code>crypto.ECDH()</code>
class <code>getPublicKey()</code> method.</p>
<p><a id="ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY"></a></p>
<h4><code>ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY</code><span><a class="mark" href="#all_errors_err_crypto_ecdh_invalid_public_key" id="all_errors_err_crypto_ecdh_invalid_public_key">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_ecdh_invalid_public_key"></a></h4>
<p>An invalid value for the <code>key</code> argument has been passed to the
<code>crypto.ECDH()</code> class <code>computeSecret()</code> method. It means that the public
key lies outside of the elliptic curve.</p>
<p><a id="ERR_CRYPTO_ENGINE_UNKNOWN"></a></p>
<h4><code>ERR_CRYPTO_ENGINE_UNKNOWN</code><span><a class="mark" href="#all_errors_err_crypto_engine_unknown" id="all_errors_err_crypto_engine_unknown">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_engine_unknown"></a></h4>
<p>An invalid crypto engine identifier was passed to
<a href="#all_crypto_cryptosetengineengine-flags"><code>require('node:crypto').setEngine()</code></a>.</p>
<p><a id="ERR_CRYPTO_FIPS_FORCED"></a></p>
<h4><code>ERR_CRYPTO_FIPS_FORCED</code><span><a class="mark" href="#all_errors_err_crypto_fips_forced" id="all_errors_err_crypto_fips_forced">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_fips_forced"></a></h4>
<p>The <a href="#all_cli_--force-fips"><code>--force-fips</code></a> command-line argument was used but there was an attempt
to enable or disable FIPS mode in the <code>node:crypto</code> module.</p>
<p><a id="ERR_CRYPTO_FIPS_UNAVAILABLE"></a></p>
<h4><code>ERR_CRYPTO_FIPS_UNAVAILABLE</code><span><a class="mark" href="#all_errors_err_crypto_fips_unavailable" id="all_errors_err_crypto_fips_unavailable">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_fips_unavailable"></a></h4>
<p>An attempt was made to enable or disable FIPS mode, but FIPS mode was not
available.</p>
<p><a id="ERR_CRYPTO_HASH_FINALIZED"></a></p>
<h4><code>ERR_CRYPTO_HASH_FINALIZED</code><span><a class="mark" href="#all_errors_err_crypto_hash_finalized" id="all_errors_err_crypto_hash_finalized">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_hash_finalized"></a></h4>
<p><a href="#all_crypto_hashdigestencoding"><code>hash.digest()</code></a> was called multiple times. The <code>hash.digest()</code> method must
be called no more than one time per instance of a <code>Hash</code> object.</p>
<p><a id="ERR_CRYPTO_HASH_UPDATE_FAILED"></a></p>
<h4><code>ERR_CRYPTO_HASH_UPDATE_FAILED</code><span><a class="mark" href="#all_errors_err_crypto_hash_update_failed" id="all_errors_err_crypto_hash_update_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_hash_update_failed"></a></h4>
<p><a href="#all_crypto_hashupdatedata-inputencoding"><code>hash.update()</code></a> failed for any reason. This should rarely, if ever, happen.</p>
<p><a id="ERR_CRYPTO_INCOMPATIBLE_KEY"></a></p>
<h4><code>ERR_CRYPTO_INCOMPATIBLE_KEY</code><span><a class="mark" href="#all_errors_err_crypto_incompatible_key" id="all_errors_err_crypto_incompatible_key">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_incompatible_key"></a></h4>
<p>The given crypto keys are incompatible with the attempted operation.</p>
<p><a id="ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS"></a></p>
<h4><code>ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS</code><span><a class="mark" href="#all_errors_err_crypto_incompatible_key_options" id="all_errors_err_crypto_incompatible_key_options">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_incompatible_key_options"></a></h4>
<p>The selected public or private key encoding is incompatible with other options.</p>
<p><a id="ERR_CRYPTO_INITIALIZATION_FAILED"></a></p>
<h4><code>ERR_CRYPTO_INITIALIZATION_FAILED</code><span><a class="mark" href="#all_errors_err_crypto_initialization_failed" id="all_errors_err_crypto_initialization_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_initialization_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>Initialization of the crypto subsystem failed.</p>
<p><a id="ERR_CRYPTO_INVALID_AUTH_TAG"></a></p>
<h4><code>ERR_CRYPTO_INVALID_AUTH_TAG</code><span><a class="mark" href="#all_errors_err_crypto_invalid_auth_tag" id="all_errors_err_crypto_invalid_auth_tag">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_auth_tag"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid authentication tag was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_COUNTER"></a></p>
<h4><code>ERR_CRYPTO_INVALID_COUNTER</code><span><a class="mark" href="#all_errors_err_crypto_invalid_counter" id="all_errors_err_crypto_invalid_counter">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_counter"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid counter was provided for a counter-mode cipher.</p>
<p><a id="ERR_CRYPTO_INVALID_CURVE"></a></p>
<h4><code>ERR_CRYPTO_INVALID_CURVE</code><span><a class="mark" href="#all_errors_err_crypto_invalid_curve" id="all_errors_err_crypto_invalid_curve">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_curve"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid elliptic-curve was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_DIGEST"></a></p>
<h4><code>ERR_CRYPTO_INVALID_DIGEST</code><span><a class="mark" href="#all_errors_err_crypto_invalid_digest" id="all_errors_err_crypto_invalid_digest">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_digest"></a></h4>
<p>An invalid <a href="#all_crypto_cryptogethashes">crypto digest algorithm</a> was specified.</p>
<p><a id="ERR_CRYPTO_INVALID_IV"></a></p>
<h4><code>ERR_CRYPTO_INVALID_IV</code><span><a class="mark" href="#all_errors_err_crypto_invalid_iv" id="all_errors_err_crypto_invalid_iv">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_iv"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid initialization vector was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_JWK"></a></p>
<h4><code>ERR_CRYPTO_INVALID_JWK</code><span><a class="mark" href="#all_errors_err_crypto_invalid_jwk" id="all_errors_err_crypto_invalid_jwk">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_jwk"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid JSON Web Key was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE"></a></p>
<h4><code>ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE</code><span><a class="mark" href="#all_errors_err_crypto_invalid_key_object_type" id="all_errors_err_crypto_invalid_key_object_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_key_object_type"></a></h4>
<p>The given crypto key object's type is invalid for the attempted operation.</p>
<p><a id="ERR_CRYPTO_INVALID_KEYLEN"></a></p>
<h4><code>ERR_CRYPTO_INVALID_KEYLEN</code><span><a class="mark" href="#all_errors_err_crypto_invalid_keylen" id="all_errors_err_crypto_invalid_keylen">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_keylen"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid key length was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_KEYPAIR"></a></p>
<h4><code>ERR_CRYPTO_INVALID_KEYPAIR</code><span><a class="mark" href="#all_errors_err_crypto_invalid_keypair" id="all_errors_err_crypto_invalid_keypair">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_keypair"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid key pair was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_KEYTYPE"></a></p>
<h4><code>ERR_CRYPTO_INVALID_KEYTYPE</code><span><a class="mark" href="#all_errors_err_crypto_invalid_keytype" id="all_errors_err_crypto_invalid_keytype">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_keytype"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid key type was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_MESSAGELEN"></a></p>
<h4><code>ERR_CRYPTO_INVALID_MESSAGELEN</code><span><a class="mark" href="#all_errors_err_crypto_invalid_messagelen" id="all_errors_err_crypto_invalid_messagelen">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_messagelen"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid message length was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_SCRYPT_PARAMS"></a></p>
<h4><code>ERR_CRYPTO_INVALID_SCRYPT_PARAMS</code><span><a class="mark" href="#all_errors_err_crypto_invalid_scrypt_params" id="all_errors_err_crypto_invalid_scrypt_params">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_scrypt_params"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>Invalid scrypt algorithm parameters were provided.</p>
<p><a id="ERR_CRYPTO_INVALID_STATE"></a></p>
<h4><code>ERR_CRYPTO_INVALID_STATE</code><span><a class="mark" href="#all_errors_err_crypto_invalid_state" id="all_errors_err_crypto_invalid_state">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_state"></a></h4>
<p>A crypto method was used on an object that was in an invalid state. For
instance, calling <a href="#all_crypto_ciphergetauthtag"><code>cipher.getAuthTag()</code></a> before calling <code>cipher.final()</code>.</p>
<p><a id="ERR_CRYPTO_INVALID_TAG_LENGTH"></a></p>
<h4><code>ERR_CRYPTO_INVALID_TAG_LENGTH</code><span><a class="mark" href="#all_errors_err_crypto_invalid_tag_length" id="all_errors_err_crypto_invalid_tag_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_tag_length"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid authentication tag length was provided.</p>
<p><a id="ERR_CRYPTO_JOB_INIT_FAILED"></a></p>
<h4><code>ERR_CRYPTO_JOB_INIT_FAILED</code><span><a class="mark" href="#all_errors_err_crypto_job_init_failed" id="all_errors_err_crypto_job_init_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_job_init_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>Initialization of an asynchronous crypto operation failed.</p>
<p><a id="ERR_CRYPTO_JWK_UNSUPPORTED_CURVE"></a></p>
<h4><code>ERR_CRYPTO_JWK_UNSUPPORTED_CURVE</code><span><a class="mark" href="#all_errors_err_crypto_jwk_unsupported_curve" id="all_errors_err_crypto_jwk_unsupported_curve">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_jwk_unsupported_curve"></a></h4>
<p>Key's Elliptic Curve is not registered for use in the
<a href="https://www.iana.org/assignments/jose/jose.xhtml#web-key-elliptic-curve">JSON Web Key Elliptic Curve Registry</a>.</p>
<p><a id="ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE"></a></p>
<h4><code>ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE</code><span><a class="mark" href="#all_errors_err_crypto_jwk_unsupported_key_type" id="all_errors_err_crypto_jwk_unsupported_key_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_jwk_unsupported_key_type"></a></h4>
<p>Key's Asymmetric Key Type is not registered for use in the
<a href="https://www.iana.org/assignments/jose/jose.xhtml#web-key-types">JSON Web Key Types Registry</a>.</p>
<p><a id="ERR_CRYPTO_OPERATION_FAILED"></a></p>
<h4><code>ERR_CRYPTO_OPERATION_FAILED</code><span><a class="mark" href="#all_errors_err_crypto_operation_failed" id="all_errors_err_crypto_operation_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_operation_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>A crypto operation failed for an otherwise unspecified reason.</p>
<p><a id="ERR_CRYPTO_PBKDF2_ERROR"></a></p>
<h4><code>ERR_CRYPTO_PBKDF2_ERROR</code><span><a class="mark" href="#all_errors_err_crypto_pbkdf2_error" id="all_errors_err_crypto_pbkdf2_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_pbkdf2_error"></a></h4>
<p>The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide
more details and therefore neither does Node.js.</p>
<p><a id="ERR_CRYPTO_SCRYPT_INVALID_PARAMETER"></a></p>
<h4><code>ERR_CRYPTO_SCRYPT_INVALID_PARAMETER</code><span><a class="mark" href="#all_errors_err_crypto_scrypt_invalid_parameter" id="all_errors_err_crypto_scrypt_invalid_parameter">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_scrypt_invalid_parameter"></a></h4>
<p>One or more <a href="#all_crypto_cryptoscryptpassword-salt-keylen-options-callback"><code>crypto.scrypt()</code></a> or <a href="#all_crypto_cryptoscryptsyncpassword-salt-keylen-options"><code>crypto.scryptSync()</code></a> parameters are
outside their legal range.</p>
<p><a id="ERR_CRYPTO_SCRYPT_NOT_SUPPORTED"></a></p>
<h4><code>ERR_CRYPTO_SCRYPT_NOT_SUPPORTED</code><span><a class="mark" href="#all_errors_err_crypto_scrypt_not_supported" id="all_errors_err_crypto_scrypt_not_supported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_scrypt_not_supported"></a></h4>
<p>Node.js was compiled without <code>scrypt</code> support. Not possible with the official
release binaries but can happen with custom builds, including distro builds.</p>
<p><a id="ERR_CRYPTO_SIGN_KEY_REQUIRED"></a></p>
<h4><code>ERR_CRYPTO_SIGN_KEY_REQUIRED</code><span><a class="mark" href="#all_errors_err_crypto_sign_key_required" id="all_errors_err_crypto_sign_key_required">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_sign_key_required"></a></h4>
<p>A signing <code>key</code> was not provided to the <a href="#all_crypto_signsignprivatekey-outputencoding"><code>sign.sign()</code></a> method.</p>
<p><a id="ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH"></a></p>
<h4><code>ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH</code><span><a class="mark" href="#all_errors_err_crypto_timing_safe_equal_length" id="all_errors_err_crypto_timing_safe_equal_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_timing_safe_equal_length"></a></h4>
<p><a href="#all_crypto_cryptotimingsafeequala-b"><code>crypto.timingSafeEqual()</code></a> was called with <code>Buffer</code>, <code>TypedArray</code>, or
<code>DataView</code> arguments of different lengths.</p>
<p><a id="ERR_CRYPTO_UNKNOWN_CIPHER"></a></p>
<h4><code>ERR_CRYPTO_UNKNOWN_CIPHER</code><span><a class="mark" href="#all_errors_err_crypto_unknown_cipher" id="all_errors_err_crypto_unknown_cipher">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_unknown_cipher"></a></h4>
<p>An unknown cipher was specified.</p>
<p><a id="ERR_CRYPTO_UNKNOWN_DH_GROUP"></a></p>
<h4><code>ERR_CRYPTO_UNKNOWN_DH_GROUP</code><span><a class="mark" href="#all_errors_err_crypto_unknown_dh_group" id="all_errors_err_crypto_unknown_dh_group">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_unknown_dh_group"></a></h4>
<p>An unknown Diffie-Hellman group name was given. See
<a href="#all_crypto_cryptogetdiffiehellmangroupname"><code>crypto.getDiffieHellman()</code></a> for a list of valid group names.</p>
<p><a id="ERR_CRYPTO_UNSUPPORTED_OPERATION"></a></p>
<h4><code>ERR_CRYPTO_UNSUPPORTED_OPERATION</code><span><a class="mark" href="#all_errors_err_crypto_unsupported_operation" id="all_errors_err_crypto_unsupported_operation">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_unsupported_operation"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<p>An attempt to invoke an unsupported crypto operation was made.</p>
<p><a id="ERR_DEBUGGER_ERROR"></a></p>
<h4><code>ERR_DEBUGGER_ERROR</code><span><a class="mark" href="#all_errors_err_debugger_error" id="all_errors_err_debugger_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_debugger_error"></a></h4>
<div class="api_metadata">
<span>Added in: v16.4.0, v14.17.4</span>
</div>
<p>An error occurred with the <a href="debugger.html">debugger</a>.</p>
<p><a id="ERR_DEBUGGER_STARTUP_ERROR"></a></p>
<h4><code>ERR_DEBUGGER_STARTUP_ERROR</code><span><a class="mark" href="#all_errors_err_debugger_startup_error" id="all_errors_err_debugger_startup_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_debugger_startup_error"></a></h4>
<div class="api_metadata">
<span>Added in: v16.4.0, v14.17.4</span>
</div>
<p>The <a href="debugger.html">debugger</a> timed out waiting for the required host/port to be free.</p>
<p><a id="ERR_DLOPEN_DISABLED"></a></p>
<h4><code>ERR_DLOPEN_DISABLED</code><span><a class="mark" href="#all_errors_err_dlopen_disabled" id="all_errors_err_dlopen_disabled">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_dlopen_disabled"></a></h4>
<div class="api_metadata">
<span>Added in: v16.10.0, v14.19.0</span>
</div>
<p>Loading native addons has been disabled using <a href="#all_cli_--no-addons"><code>--no-addons</code></a>.</p>
<p><a id="ERR_DLOPEN_FAILED"></a></p>
<h4><code>ERR_DLOPEN_FAILED</code><span><a class="mark" href="#all_errors_err_dlopen_failed" id="all_errors_err_dlopen_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_dlopen_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>A call to <code>process.dlopen()</code> failed.</p>
<p><a id="ERR_DIR_CLOSED"></a></p>
<h4><code>ERR_DIR_CLOSED</code><span><a class="mark" href="#all_errors_err_dir_closed" id="all_errors_err_dir_closed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_dir_closed"></a></h4>
<p>The <a href="#all_fs_class-fsdir"><code>fs.Dir</code></a> was previously closed.</p>
<p><a id="ERR_DIR_CONCURRENT_OPERATION"></a></p>
<h4><code>ERR_DIR_CONCURRENT_OPERATION</code><span><a class="mark" href="#all_errors_err_dir_concurrent_operation" id="all_errors_err_dir_concurrent_operation">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_dir_concurrent_operation"></a></h4>
<div class="api_metadata">
<span>Added in: v14.3.0</span>
</div>
<p>A synchronous read or close call was attempted on an <a href="#all_fs_class-fsdir"><code>fs.Dir</code></a> which has
ongoing asynchronous operations.</p>
<p><a id="ERR_DNS_SET_SERVERS_FAILED"></a></p>
<h4><code>ERR_DNS_SET_SERVERS_FAILED</code><span><a class="mark" href="#all_errors_err_dns_set_servers_failed" id="all_errors_err_dns_set_servers_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_dns_set_servers_failed"></a></h4>
<p><code>c-ares</code> failed to set the DNS server.</p>
<p><a id="ERR_DOMAIN_CALLBACK_NOT_AVAILABLE"></a></p>
<h4><code>ERR_DOMAIN_CALLBACK_NOT_AVAILABLE</code><span><a class="mark" href="#all_errors_err_domain_callback_not_available" id="all_errors_err_domain_callback_not_available">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_domain_callback_not_available"></a></h4>
<p>The <code>node:domain</code> module was not usable since it could not establish the
required error handling hooks, because
<a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> had been called at an
earlier point in time.</p>
<p><a id="ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE"></a></p>
<h4><code>ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE</code><span><a class="mark" href="#all_errors_err_domain_cannot_set_uncaught_exception_capture" id="all_errors_err_domain_cannot_set_uncaught_exception_capture">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_domain_cannot_set_uncaught_exception_capture"></a></h4>
<p><a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> could not be called
because the <code>node:domain</code> module has been loaded at an earlier point in time.</p>
<p>The stack trace is extended to include the point in time at which the
<code>node:domain</code> module had been loaded.</p>
<p><a id="ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION"></a></p>
<h4><code>ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION</code><span><a class="mark" href="#all_errors_err_duplicate_startup_snapshot_main_function" id="all_errors_err_duplicate_startup_snapshot_main_function">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_duplicate_startup_snapshot_main_function"></a></h4>
<p><a href="#all_v8_v8startupsnapshotsetdeserializemainfunctioncallback-data"><code>v8.startupSnapshot.setDeserializeMainFunction()</code></a> could not be called
because it had already been called before.</p>
<p><a id="ERR_ENCODING_INVALID_ENCODED_DATA"></a></p>
<h4><code>ERR_ENCODING_INVALID_ENCODED_DATA</code><span><a class="mark" href="#all_errors_err_encoding_invalid_encoded_data" id="all_errors_err_encoding_invalid_encoded_data">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_encoding_invalid_encoded_data"></a></h4>
<p>Data provided to <code>TextDecoder()</code> API was invalid according to the encoding
provided.</p>
<p><a id="ERR_ENCODING_NOT_SUPPORTED"></a></p>
<h4><code>ERR_ENCODING_NOT_SUPPORTED</code><span><a class="mark" href="#all_errors_err_encoding_not_supported" id="all_errors_err_encoding_not_supported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_encoding_not_supported"></a></h4>
<p>Encoding provided to <code>TextDecoder()</code> API was not one of the
<a href="#all_util_whatwg-supported-encodings">WHATWG Supported Encodings</a>.</p>
<p><a id="ERR_EVAL_ESM_CANNOT_PRINT"></a></p>
<h4><code>ERR_EVAL_ESM_CANNOT_PRINT</code><span><a class="mark" href="#all_errors_err_eval_esm_cannot_print" id="all_errors_err_eval_esm_cannot_print">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_eval_esm_cannot_print"></a></h4>
<p><code>--print</code> cannot be used with ESM input.</p>
<p><a id="ERR_EVENT_RECURSION"></a></p>
<h4><code>ERR_EVENT_RECURSION</code><span><a class="mark" href="#all_errors_err_event_recursion" id="all_errors_err_event_recursion">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_event_recursion"></a></h4>
<p>Thrown when an attempt is made to recursively dispatch an event on <code>EventTarget</code>.</p>
<p><a id="ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE"></a></p>
<h4><code>ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE</code><span><a class="mark" href="#all_errors_err_execution_environment_not_available" id="all_errors_err_execution_environment_not_available">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_execution_environment_not_available"></a></h4>
<p>The JS execution context is not associated with a Node.js environment.
This may occur when Node.js is used as an embedded library and some hooks
for the JS engine are not set up properly.</p>
<p><a id="ERR_FALSY_VALUE_REJECTION"></a></p>
<h4><code>ERR_FALSY_VALUE_REJECTION</code><span><a class="mark" href="#all_errors_err_falsy_value_rejection" id="all_errors_err_falsy_value_rejection">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_falsy_value_rejection"></a></h4>
<p>A <code>Promise</code> that was callbackified via <code>util.callbackify()</code> was rejected with a
falsy value.</p>
<p><a id="ERR_FEATURE_UNAVAILABLE_ON_PLATFORM"></a></p>
<h4><code>ERR_FEATURE_UNAVAILABLE_ON_PLATFORM</code><span><a class="mark" href="#all_errors_err_feature_unavailable_on_platform" id="all_errors_err_feature_unavailable_on_platform">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_feature_unavailable_on_platform"></a></h4>
<div class="api_metadata">
<span>Added in: v14.0.0</span>
</div>
<p>Used when a feature that is not available
to the current platform which is running Node.js is used.</p>
<p><a id="ERR_FS_CP_DIR_TO_NON_DIR"></a></p>
<h4><code>ERR_FS_CP_DIR_TO_NON_DIR</code><span><a class="mark" href="#all_errors_err_fs_cp_dir_to_non_dir" id="all_errors_err_fs_cp_dir_to_non_dir">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_dir_to_non_dir"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>An attempt was made to copy a directory to a non-directory (file, symlink,
etc.) using <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>.</p>
<p><a id="ERR_FS_CP_EEXIST"></a></p>
<h4><code>ERR_FS_CP_EEXIST</code><span><a class="mark" href="#all_errors_err_fs_cp_eexist" id="all_errors_err_fs_cp_eexist">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_eexist"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>An attempt was made to copy over a file that already existed with
<a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>, with the <code>force</code> and <code>errorOnExist</code> set to <code>true</code>.</p>
<p><a id="ERR_FS_CP_EINVAL"></a></p>
<h4><code>ERR_FS_CP_EINVAL</code><span><a class="mark" href="#all_errors_err_fs_cp_einval" id="all_errors_err_fs_cp_einval">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_einval"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>When using <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>, <code>src</code> or <code>dest</code> pointed to an invalid path.</p>
<p><a id="ERR_HTTP_BODY_NOT_ALLOWED"></a></p>
<h4><code>ERR_HTTP_BODY_NOT_ALLOWED</code><span><a class="mark" href="#all_errors_err_http_body_not_allowed" id="all_errors_err_http_body_not_allowed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_body_not_allowed"></a></h4>
<p>An error is thrown when writing to an HTTP response which does not allow
contents.</p>
<p><a id="ERR_HTTP_CONTENT_LENGTH_MISMATCH"></a></p>
<h4><code>ERR_HTTP_CONTENT_LENGTH_MISMATCH</code><span><a class="mark" href="#all_errors_err_http_content_length_mismatch" id="all_errors_err_http_content_length_mismatch">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_content_length_mismatch"></a></h4>
<p>Response body size doesn't match with the specified content-length header value.</p>
<p><a id="ERR_FS_CP_FIFO_PIPE"></a></p>
<h4><code>ERR_FS_CP_FIFO_PIPE</code><span><a class="mark" href="#all_errors_err_fs_cp_fifo_pipe" id="all_errors_err_fs_cp_fifo_pipe">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_fifo_pipe"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>An attempt was made to copy a named pipe with <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>.</p>
<p><a id="ERR_FS_CP_NON_DIR_TO_DIR"></a></p>
<h4><code>ERR_FS_CP_NON_DIR_TO_DIR</code><span><a class="mark" href="#all_errors_err_fs_cp_non_dir_to_dir" id="all_errors_err_fs_cp_non_dir_to_dir">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_non_dir_to_dir"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>An attempt was made to copy a non-directory (file, symlink, etc.) to a directory
using <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>.</p>
<p><a id="ERR_FS_CP_SOCKET"></a></p>
<h4><code>ERR_FS_CP_SOCKET</code><span><a class="mark" href="#all_errors_err_fs_cp_socket" id="all_errors_err_fs_cp_socket">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>An attempt was made to copy to a socket with <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>.</p>
<p><a id="ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY"></a></p>
<h4><code>ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY</code><span><a class="mark" href="#all_errors_err_fs_cp_symlink_to_subdirectory" id="all_errors_err_fs_cp_symlink_to_subdirectory">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_symlink_to_subdirectory"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>When using <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>, a symlink in <code>dest</code> pointed to a subdirectory
of <code>src</code>.</p>
<p><a id="ERR_FS_CP_UNKNOWN"></a></p>
<h4><code>ERR_FS_CP_UNKNOWN</code><span><a class="mark" href="#all_errors_err_fs_cp_unknown" id="all_errors_err_fs_cp_unknown">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_unknown"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>An attempt was made to copy to an unknown file type with <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>.</p>
<p><a id="ERR_FS_EISDIR"></a></p>
<h4><code>ERR_FS_EISDIR</code><span><a class="mark" href="#all_errors_err_fs_eisdir" id="all_errors_err_fs_eisdir">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_eisdir"></a></h4>
<p>Path is a directory.</p>
<p><a id="ERR_FS_FILE_TOO_LARGE"></a></p>
<h4><code>ERR_FS_FILE_TOO_LARGE</code><span><a class="mark" href="#all_errors_err_fs_file_too_large" id="all_errors_err_fs_file_too_large">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_file_too_large"></a></h4>
<p>An attempt has been made to read a file whose size is larger than the maximum
allowed size for a <code>Buffer</code>.</p>
<p><a id="ERR_FS_INVALID_SYMLINK_TYPE"></a></p>
<h4><code>ERR_FS_INVALID_SYMLINK_TYPE</code><span><a class="mark" href="#all_errors_err_fs_invalid_symlink_type" id="all_errors_err_fs_invalid_symlink_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_invalid_symlink_type"></a></h4>
<p>An invalid symlink type was passed to the <a href="#all_fs_fssymlinktarget-path-type-callback"><code>fs.symlink()</code></a> or
<a href="#all_fs_fssymlinksynctarget-path-type"><code>fs.symlinkSync()</code></a> methods.</p>
<p><a id="ERR_HTTP_HEADERS_SENT"></a></p>
<h4><code>ERR_HTTP_HEADERS_SENT</code><span><a class="mark" href="#all_errors_err_http_headers_sent" id="all_errors_err_http_headers_sent">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_headers_sent"></a></h4>
<p>An attempt was made to add more headers after the headers had already been sent.</p>
<p><a id="ERR_HTTP_INVALID_HEADER_VALUE"></a></p>
<h4><code>ERR_HTTP_INVALID_HEADER_VALUE</code><span><a class="mark" href="#all_errors_err_http_invalid_header_value" id="all_errors_err_http_invalid_header_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_invalid_header_value"></a></h4>
<p>An invalid HTTP header value was specified.</p>
<p><a id="ERR_HTTP_INVALID_STATUS_CODE"></a></p>
<h4><code>ERR_HTTP_INVALID_STATUS_CODE</code><span><a class="mark" href="#all_errors_err_http_invalid_status_code" id="all_errors_err_http_invalid_status_code">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_invalid_status_code"></a></h4>
<p>Status code was outside the regular status code range (100-999).</p>
<p><a id="ERR_HTTP_REQUEST_TIMEOUT"></a></p>
<h4><code>ERR_HTTP_REQUEST_TIMEOUT</code><span><a class="mark" href="#all_errors_err_http_request_timeout" id="all_errors_err_http_request_timeout">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_request_timeout"></a></h4>
<p>The client has not sent the entire request within the allowed time.</p>
<p><a id="ERR_HTTP_SOCKET_ASSIGNED"></a></p>
<h4><code>ERR_HTTP_SOCKET_ASSIGNED</code><span><a class="mark" href="#all_errors_err_http_socket_assigned" id="all_errors_err_http_socket_assigned">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_socket_assigned"></a></h4>
<p>The given <a href="#all_http_class-httpserverresponse"><code>ServerResponse</code></a> was already assigned a socket.</p>
<p><a id="ERR_HTTP_SOCKET_ENCODING"></a></p>
<h4><code>ERR_HTTP_SOCKET_ENCODING</code><span><a class="mark" href="#all_errors_err_http_socket_encoding" id="all_errors_err_http_socket_encoding">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_socket_encoding"></a></h4>
<p>Changing the socket encoding is not allowed per <a href="https://tools.ietf.org/html/rfc7230#section-3">RFC 7230 Section 3</a>.</p>
<p><a id="ERR_HTTP_TRAILER_INVALID"></a></p>
<h4><code>ERR_HTTP_TRAILER_INVALID</code><span><a class="mark" href="#all_errors_err_http_trailer_invalid" id="all_errors_err_http_trailer_invalid">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_trailer_invalid"></a></h4>
<p>The <code>Trailer</code> header was set even though the transfer encoding does not support
that.</p>
<p><a id="ERR_HTTP2_ALTSVC_INVALID_ORIGIN"></a></p>
<h4><code>ERR_HTTP2_ALTSVC_INVALID_ORIGIN</code><span><a class="mark" href="#all_errors_err_http2_altsvc_invalid_origin" id="all_errors_err_http2_altsvc_invalid_origin">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_altsvc_invalid_origin"></a></h4>
<p>HTTP/2 ALTSVC frames require a valid origin.</p>
<p><a id="ERR_HTTP2_ALTSVC_LENGTH"></a></p>
<h4><code>ERR_HTTP2_ALTSVC_LENGTH</code><span><a class="mark" href="#all_errors_err_http2_altsvc_length" id="all_errors_err_http2_altsvc_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_altsvc_length"></a></h4>
<p>HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes.</p>
<p><a id="ERR_HTTP2_CONNECT_AUTHORITY"></a></p>
<h4><code>ERR_HTTP2_CONNECT_AUTHORITY</code><span><a class="mark" href="#all_errors_err_http2_connect_authority" id="all_errors_err_http2_connect_authority">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_connect_authority"></a></h4>
<p>For HTTP/2 requests using the <code>CONNECT</code> method, the <code>:authority</code> pseudo-header
is required.</p>
<p><a id="ERR_HTTP2_CONNECT_PATH"></a></p>
<h4><code>ERR_HTTP2_CONNECT_PATH</code><span><a class="mark" href="#all_errors_err_http2_connect_path" id="all_errors_err_http2_connect_path">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_connect_path"></a></h4>
<p>For HTTP/2 requests using the <code>CONNECT</code> method, the <code>:path</code> pseudo-header is
forbidden.</p>
<p><a id="ERR_HTTP2_CONNECT_SCHEME"></a></p>
<h4><code>ERR_HTTP2_CONNECT_SCHEME</code><span><a class="mark" href="#all_errors_err_http2_connect_scheme" id="all_errors_err_http2_connect_scheme">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_connect_scheme"></a></h4>
<p>For HTTP/2 requests using the <code>CONNECT</code> method, the <code>:scheme</code> pseudo-header is
forbidden.</p>
<p><a id="ERR_HTTP2_ERROR"></a></p>
<h4><code>ERR_HTTP2_ERROR</code><span><a class="mark" href="#all_errors_err_http2_error" id="all_errors_err_http2_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_error"></a></h4>
<p>A non-specific HTTP/2 error has occurred.</p>
<p><a id="ERR_HTTP2_GOAWAY_SESSION"></a></p>
<h4><code>ERR_HTTP2_GOAWAY_SESSION</code><span><a class="mark" href="#all_errors_err_http2_goaway_session" id="all_errors_err_http2_goaway_session">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_goaway_session"></a></h4>
<p>New HTTP/2 Streams may not be opened after the <code>Http2Session</code> has received a
<code>GOAWAY</code> frame from the connected peer.</p>
<p><a id="ERR_HTTP2_HEADER_SINGLE_VALUE"></a></p>
<h4><code>ERR_HTTP2_HEADER_SINGLE_VALUE</code><span><a class="mark" href="#all_errors_err_http2_header_single_value" id="all_errors_err_http2_header_single_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_header_single_value"></a></h4>
<p>Multiple values were provided for an HTTP/2 header field that was required to
have only a single value.</p>
<p><a id="ERR_HTTP2_HEADERS_AFTER_RESPOND"></a></p>
<h4><code>ERR_HTTP2_HEADERS_AFTER_RESPOND</code><span><a class="mark" href="#all_errors_err_http2_headers_after_respond" id="all_errors_err_http2_headers_after_respond">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_headers_after_respond"></a></h4>
<p>An additional headers was specified after an HTTP/2 response was initiated.</p>
<p><a id="ERR_HTTP2_HEADERS_SENT"></a></p>
<h4><code>ERR_HTTP2_HEADERS_SENT</code><span><a class="mark" href="#all_errors_err_http2_headers_sent" id="all_errors_err_http2_headers_sent">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_headers_sent"></a></h4>
<p>An attempt was made to send multiple response headers.</p>
<p><a id="ERR_HTTP2_INFO_STATUS_NOT_ALLOWED"></a></p>
<h4><code>ERR_HTTP2_INFO_STATUS_NOT_ALLOWED</code><span><a class="mark" href="#all_errors_err_http2_info_status_not_allowed" id="all_errors_err_http2_info_status_not_allowed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_info_status_not_allowed"></a></h4>
<p>Informational HTTP status codes (<code>1xx</code>) may not be set as the response status
code on HTTP/2 responses.</p>
<p><a id="ERR_HTTP2_INVALID_CONNECTION_HEADERS"></a></p>
<h4><code>ERR_HTTP2_INVALID_CONNECTION_HEADERS</code><span><a class="mark" href="#all_errors_err_http2_invalid_connection_headers" id="all_errors_err_http2_invalid_connection_headers">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_connection_headers"></a></h4>
<p>HTTP/1 connection specific headers are forbidden to be used in HTTP/2
requests and responses.</p>
<p><a id="ERR_HTTP2_INVALID_HEADER_VALUE"></a></p>
<h4><code>ERR_HTTP2_INVALID_HEADER_VALUE</code><span><a class="mark" href="#all_errors_err_http2_invalid_header_value" id="all_errors_err_http2_invalid_header_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_header_value"></a></h4>
<p>An invalid HTTP/2 header value was specified.</p>
<p><a id="ERR_HTTP2_INVALID_INFO_STATUS"></a></p>
<h4><code>ERR_HTTP2_INVALID_INFO_STATUS</code><span><a class="mark" href="#all_errors_err_http2_invalid_info_status" id="all_errors_err_http2_invalid_info_status">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_info_status"></a></h4>
<p>An invalid HTTP informational status code has been specified. Informational
status codes must be an integer between <code>100</code> and <code>199</code> (inclusive).</p>
<p><a id="ERR_HTTP2_INVALID_ORIGIN"></a></p>
<h4><code>ERR_HTTP2_INVALID_ORIGIN</code><span><a class="mark" href="#all_errors_err_http2_invalid_origin" id="all_errors_err_http2_invalid_origin">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_origin"></a></h4>
<p>HTTP/2 <code>ORIGIN</code> frames require a valid origin.</p>
<p><a id="ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH"></a></p>
<h4><code>ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH</code><span><a class="mark" href="#all_errors_err_http2_invalid_packed_settings_length" id="all_errors_err_http2_invalid_packed_settings_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_packed_settings_length"></a></h4>
<p>Input <code>Buffer</code> and <code>Uint8Array</code> instances passed to the
<code>http2.getUnpackedSettings()</code> API must have a length that is a multiple of
six.</p>
<p><a id="ERR_HTTP2_INVALID_PSEUDOHEADER"></a></p>
<h4><code>ERR_HTTP2_INVALID_PSEUDOHEADER</code><span><a class="mark" href="#all_errors_err_http2_invalid_pseudoheader" id="all_errors_err_http2_invalid_pseudoheader">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_pseudoheader"></a></h4>
<p>Only valid HTTP/2 pseudoheaders (<code>:status</code>, <code>:path</code>, <code>:authority</code>, <code>:scheme</code>,
and <code>:method</code>) may be used.</p>
<p><a id="ERR_HTTP2_INVALID_SESSION"></a></p>
<h4><code>ERR_HTTP2_INVALID_SESSION</code><span><a class="mark" href="#all_errors_err_http2_invalid_session" id="all_errors_err_http2_invalid_session">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_session"></a></h4>
<p>An action was performed on an <code>Http2Session</code> object that had already been
destroyed.</p>
<p><a id="ERR_HTTP2_INVALID_SETTING_VALUE"></a></p>
<h4><code>ERR_HTTP2_INVALID_SETTING_VALUE</code><span><a class="mark" href="#all_errors_err_http2_invalid_setting_value" id="all_errors_err_http2_invalid_setting_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_setting_value"></a></h4>
<p>An invalid value has been specified for an HTTP/2 setting.</p>
<p><a id="ERR_HTTP2_INVALID_STREAM"></a></p>
<h4><code>ERR_HTTP2_INVALID_STREAM</code><span><a class="mark" href="#all_errors_err_http2_invalid_stream" id="all_errors_err_http2_invalid_stream">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_stream"></a></h4>
<p>An operation was performed on a stream that had already been destroyed.</p>
<p><a id="ERR_HTTP2_MAX_PENDING_SETTINGS_ACK"></a></p>
<h4><code>ERR_HTTP2_MAX_PENDING_SETTINGS_ACK</code><span><a class="mark" href="#all_errors_err_http2_max_pending_settings_ack" id="all_errors_err_http2_max_pending_settings_ack">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_max_pending_settings_ack"></a></h4>
<p>Whenever an HTTP/2 <code>SETTINGS</code> frame is sent to a connected peer, the peer is
required to send an acknowledgment that it has received and applied the new
<code>SETTINGS</code>. By default, a maximum number of unacknowledged <code>SETTINGS</code> frames may
be sent at any given time. This error code is used when that limit has been
reached.</p>
<p><a id="ERR_HTTP2_NESTED_PUSH"></a></p>
<h4><code>ERR_HTTP2_NESTED_PUSH</code><span><a class="mark" href="#all_errors_err_http2_nested_push" id="all_errors_err_http2_nested_push">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_nested_push"></a></h4>
<p>An attempt was made to initiate a new push stream from within a push stream.
Nested push streams are not permitted.</p>
<p><a id="ERR_HTTP2_NO_MEM"></a></p>
<h4><code>ERR_HTTP2_NO_MEM</code><span><a class="mark" href="#all_errors_err_http2_no_mem" id="all_errors_err_http2_no_mem">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_no_mem"></a></h4>
<p>Out of memory when using the <code>http2session.setLocalWindowSize(windowSize)</code> API.</p>
<p><a id="ERR_HTTP2_NO_SOCKET_MANIPULATION"></a></p>
<h4><code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code><span><a class="mark" href="#all_errors_err_http2_no_socket_manipulation" id="all_errors_err_http2_no_socket_manipulation">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_no_socket_manipulation"></a></h4>
<p>An attempt was made to directly manipulate (read, write, pause, resume, etc.) a
socket attached to an <code>Http2Session</code>.</p>
<p><a id="ERR_HTTP2_ORIGIN_LENGTH"></a></p>
<h4><code>ERR_HTTP2_ORIGIN_LENGTH</code><span><a class="mark" href="#all_errors_err_http2_origin_length" id="all_errors_err_http2_origin_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_origin_length"></a></h4>
<p>HTTP/2 <code>ORIGIN</code> frames are limited to a length of 16382 bytes.</p>
<p><a id="ERR_HTTP2_OUT_OF_STREAMS"></a></p>
<h4><code>ERR_HTTP2_OUT_OF_STREAMS</code><span><a class="mark" href="#all_errors_err_http2_out_of_streams" id="all_errors_err_http2_out_of_streams">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_out_of_streams"></a></h4>
<p>The number of streams created on a single HTTP/2 session reached the maximum
limit.</p>
<p><a id="ERR_HTTP2_PAYLOAD_FORBIDDEN"></a></p>
<h4><code>ERR_HTTP2_PAYLOAD_FORBIDDEN</code><span><a class="mark" href="#all_errors_err_http2_payload_forbidden" id="all_errors_err_http2_payload_forbidden">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_payload_forbidden"></a></h4>
<p>A message payload was specified for an HTTP response code for which a payload is
forbidden.</p>
<p><a id="ERR_HTTP2_PING_CANCEL"></a></p>
<h4><code>ERR_HTTP2_PING_CANCEL</code><span><a class="mark" href="#all_errors_err_http2_ping_cancel" id="all_errors_err_http2_ping_cancel">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_ping_cancel"></a></h4>
<p>An HTTP/2 ping was canceled.</p>
<p><a id="ERR_HTTP2_PING_LENGTH"></a></p>
<h4><code>ERR_HTTP2_PING_LENGTH</code><span><a class="mark" href="#all_errors_err_http2_ping_length" id="all_errors_err_http2_ping_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_ping_length"></a></h4>
<p>HTTP/2 ping payloads must be exactly 8 bytes in length.</p>
<p><a id="ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED"></a></p>
<h4><code>ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED</code><span><a class="mark" href="#all_errors_err_http2_pseudoheader_not_allowed" id="all_errors_err_http2_pseudoheader_not_allowed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_pseudoheader_not_allowed"></a></h4>
<p>An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header
key names that begin with the <code>:</code> prefix.</p>
<p><a id="ERR_HTTP2_PUSH_DISABLED"></a></p>
<h4><code>ERR_HTTP2_PUSH_DISABLED</code><span><a class="mark" href="#all_errors_err_http2_push_disabled" id="all_errors_err_http2_push_disabled">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_push_disabled"></a></h4>
<p>An attempt was made to create a push stream, which had been disabled by the
client.</p>
<p><a id="ERR_HTTP2_SEND_FILE"></a></p>
<h4><code>ERR_HTTP2_SEND_FILE</code><span><a class="mark" href="#all_errors_err_http2_send_file" id="all_errors_err_http2_send_file">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_send_file"></a></h4>
<p>An attempt was made to use the <code>Http2Stream.prototype.responseWithFile()</code> API to
send a directory.</p>
<p><a id="ERR_HTTP2_SEND_FILE_NOSEEK"></a></p>
<h4><code>ERR_HTTP2_SEND_FILE_NOSEEK</code><span><a class="mark" href="#all_errors_err_http2_send_file_noseek" id="all_errors_err_http2_send_file_noseek">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_send_file_noseek"></a></h4>
<p>An attempt was made to use the <code>Http2Stream.prototype.responseWithFile()</code> API to
send something other than a regular file, but <code>offset</code> or <code>length</code> options were
provided.</p>
<p><a id="ERR_HTTP2_SESSION_ERROR"></a></p>
<h4><code>ERR_HTTP2_SESSION_ERROR</code><span><a class="mark" href="#all_errors_err_http2_session_error" id="all_errors_err_http2_session_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_session_error"></a></h4>
<p>The <code>Http2Session</code> closed with a non-zero error code.</p>
<p><a id="ERR_HTTP2_SETTINGS_CANCEL"></a></p>
<h4><code>ERR_HTTP2_SETTINGS_CANCEL</code><span><a class="mark" href="#all_errors_err_http2_settings_cancel" id="all_errors_err_http2_settings_cancel">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_settings_cancel"></a></h4>
<p>The <code>Http2Session</code> settings canceled.</p>
<p><a id="ERR_HTTP2_SOCKET_BOUND"></a></p>
<h4><code>ERR_HTTP2_SOCKET_BOUND</code><span><a class="mark" href="#all_errors_err_http2_socket_bound" id="all_errors_err_http2_socket_bound">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_socket_bound"></a></h4>
<p>An attempt was made to connect a <code>Http2Session</code> object to a <code>net.Socket</code> or
<code>tls.TLSSocket</code> that had already been bound to another <code>Http2Session</code> object.</p>
<p><a id="ERR_HTTP2_SOCKET_UNBOUND"></a></p>
<h4><code>ERR_HTTP2_SOCKET_UNBOUND</code><span><a class="mark" href="#all_errors_err_http2_socket_unbound" id="all_errors_err_http2_socket_unbound">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_socket_unbound"></a></h4>
<p>An attempt was made to use the <code>socket</code> property of an <code>Http2Session</code> that
has already been closed.</p>
<p><a id="ERR_HTTP2_STATUS_101"></a></p>
<h4><code>ERR_HTTP2_STATUS_101</code><span><a class="mark" href="#all_errors_err_http2_status_101" id="all_errors_err_http2_status_101">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_status_101"></a></h4>
<p>Use of the <code>101</code> Informational status code is forbidden in HTTP/2.</p>
<p><a id="ERR_HTTP2_STATUS_INVALID"></a></p>
<h4><code>ERR_HTTP2_STATUS_INVALID</code><span><a class="mark" href="#all_errors_err_http2_status_invalid" id="all_errors_err_http2_status_invalid">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_status_invalid"></a></h4>
<p>An invalid HTTP status code has been specified. Status codes must be an integer
between <code>100</code> and <code>599</code> (inclusive).</p>
<p><a id="ERR_HTTP2_STREAM_CANCEL"></a></p>
<h4><code>ERR_HTTP2_STREAM_CANCEL</code><span><a class="mark" href="#all_errors_err_http2_stream_cancel" id="all_errors_err_http2_stream_cancel">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_stream_cancel"></a></h4>
<p>An <code>Http2Stream</code> was destroyed before any data was transmitted to the connected
peer.</p>
<p><a id="ERR_HTTP2_STREAM_ERROR"></a></p>
<h4><code>ERR_HTTP2_STREAM_ERROR</code><span><a class="mark" href="#all_errors_err_http2_stream_error" id="all_errors_err_http2_stream_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_stream_error"></a></h4>
<p>A non-zero error code was been specified in an <code>RST_STREAM</code> frame.</p>
<p><a id="ERR_HTTP2_STREAM_SELF_DEPENDENCY"></a></p>
<h4><code>ERR_HTTP2_STREAM_SELF_DEPENDENCY</code><span><a class="mark" href="#all_errors_err_http2_stream_self_dependency" id="all_errors_err_http2_stream_self_dependency">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_stream_self_dependency"></a></h4>
<p>When setting the priority for an HTTP/2 stream, the stream may be marked as
a dependency for a parent stream. This error code is used when an attempt is
made to mark a stream and dependent of itself.</p>
<p><a id="ERR_HTTP2_TOO_MANY_CUSTOM_SETTINGS"></a></p>
<h4><code>ERR_HTTP2_TOO_MANY_CUSTOM_SETTINGS</code><span><a class="mark" href="#all_errors_err_http2_too_many_custom_settings" id="all_errors_err_http2_too_many_custom_settings">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_too_many_custom_settings"></a></h4>
<p>The number of supported custom settings (10) has been exceeded.</p>
<p><a id="ERR_HTTP2_TOO_MANY_INVALID_FRAMES"></a></p>
<h4><code>ERR_HTTP2_TOO_MANY_INVALID_FRAMES</code><span><a class="mark" href="#all_errors_err_http2_too_many_invalid_frames" id="all_errors_err_http2_too_many_invalid_frames">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_too_many_invalid_frames"></a></h4>
<div class="api_metadata">
<span>Added in: v15.14.0</span>
</div>
<p>The limit of acceptable invalid HTTP/2 protocol frames sent by the peer,
as specified through the <code>maxSessionInvalidFrames</code> option, has been exceeded.</p>
<p><a id="ERR_HTTP2_TRAILERS_ALREADY_SENT"></a></p>
<h4><code>ERR_HTTP2_TRAILERS_ALREADY_SENT</code><span><a class="mark" href="#all_errors_err_http2_trailers_already_sent" id="all_errors_err_http2_trailers_already_sent">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_trailers_already_sent"></a></h4>
<p>Trailing headers have already been sent on the <code>Http2Stream</code>.</p>
<p><a id="ERR_HTTP2_TRAILERS_NOT_READY"></a></p>
<h4><code>ERR_HTTP2_TRAILERS_NOT_READY</code><span><a class="mark" href="#all_errors_err_http2_trailers_not_ready" id="all_errors_err_http2_trailers_not_ready">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_trailers_not_ready"></a></h4>
<p>The <code>http2stream.sendTrailers()</code> method cannot be called until after the
<code>'wantTrailers'</code> event is emitted on an <code>Http2Stream</code> object. The
<code>'wantTrailers'</code> event will only be emitted if the <code>waitForTrailers</code> option
is set for the <code>Http2Stream</code>.</p>
<p><a id="ERR_HTTP2_UNSUPPORTED_PROTOCOL"></a></p>
<h4><code>ERR_HTTP2_UNSUPPORTED_PROTOCOL</code><span><a class="mark" href="#all_errors_err_http2_unsupported_protocol" id="all_errors_err_http2_unsupported_protocol">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_unsupported_protocol"></a></h4>
<p><code>http2.connect()</code> was passed a URL that uses any protocol other than <code>http:</code> or
<code>https:</code>.</p>
<p><a id="ERR_ILLEGAL_CONSTRUCTOR"></a></p>
<h4><code>ERR_ILLEGAL_CONSTRUCTOR</code><span><a class="mark" href="#all_errors_err_illegal_constructor" id="all_errors_err_illegal_constructor">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_illegal_constructor"></a></h4>
<p>An attempt was made to construct an object using a non-public constructor.</p>
<p><a id="ERR_IMPORT_ASSERTION_TYPE_FAILED"></a></p>
<h4><code>ERR_IMPORT_ASSERTION_TYPE_FAILED</code><span><a class="mark" href="#all_errors_err_import_assertion_type_failed" id="all_errors_err_import_assertion_type_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_import_assertion_type_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<p>An import <code>type</code> attribute was provided, but the specified module is of a
different type.</p>
<p><a id="ERR_IMPORT_ASSERTION_TYPE_MISSING"></a></p>
<h4><code>ERR_IMPORT_ASSERTION_TYPE_MISSING</code><span><a class="mark" href="#all_errors_err_import_assertion_type_missing" id="all_errors_err_import_assertion_type_missing">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_import_assertion_type_missing"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<p>An import attribute is missing, preventing the specified module to be imported.</p>
<p><a id="ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED"></a></p>
<h4><code>ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED</code><span><a class="mark" href="#all_errors_err_import_assertion_type_unsupported" id="all_errors_err_import_assertion_type_unsupported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_import_assertion_type_unsupported"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<p>An import attribute is not supported by this version of Node.js.</p>
<p><a id="ERR_IMPORT_ATTRIBUTE_UNSUPPORTED"></a></p>
<h4><code>ERR_IMPORT_ATTRIBUTE_UNSUPPORTED</code><span><a class="mark" href="#all_errors_err_import_attribute_unsupported" id="all_errors_err_import_attribute_unsupported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_import_attribute_unsupported"></a></h4>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p>An import attribute is not supported by this version of Node.js.</p>
<p><a id="ERR_INCOMPATIBLE_OPTION_PAIR"></a></p>
<h4><code>ERR_INCOMPATIBLE_OPTION_PAIR</code><span><a class="mark" href="#all_errors_err_incompatible_option_pair" id="all_errors_err_incompatible_option_pair">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_incompatible_option_pair"></a></h4>
<p>An option pair is incompatible with each other and cannot be used at the same
time.</p>
<p><a id="ERR_INPUT_TYPE_NOT_ALLOWED"></a></p>
<h4><code>ERR_INPUT_TYPE_NOT_ALLOWED</code><span><a class="mark" href="#all_errors_err_input_type_not_allowed" id="all_errors_err_input_type_not_allowed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_input_type_not_allowed"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>The <code>--input-type</code> flag was used to attempt to execute a file. This flag can
only be used with input via <code>--eval</code>, <code>--print</code>, or <code>STDIN</code>.</p>
<p><a id="ERR_INSPECTOR_ALREADY_ACTIVATED"></a></p>
<h4><code>ERR_INSPECTOR_ALREADY_ACTIVATED</code><span><a class="mark" href="#all_errors_err_inspector_already_activated" id="all_errors_err_inspector_already_activated">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_already_activated"></a></h4>
<p>While using the <code>node:inspector</code> module, an attempt was made to activate the
inspector when it already started to listen on a port. Use <code>inspector.close()</code>
before activating it on a different address.</p>
<p><a id="ERR_INSPECTOR_ALREADY_CONNECTED"></a></p>
<h4><code>ERR_INSPECTOR_ALREADY_CONNECTED</code><span><a class="mark" href="#all_errors_err_inspector_already_connected" id="all_errors_err_inspector_already_connected">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_already_connected"></a></h4>
<p>While using the <code>node:inspector</code> module, an attempt was made to connect when the
inspector was already connected.</p>
<p><a id="ERR_INSPECTOR_CLOSED"></a></p>
<h4><code>ERR_INSPECTOR_CLOSED</code><span><a class="mark" href="#all_errors_err_inspector_closed" id="all_errors_err_inspector_closed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_closed"></a></h4>
<p>While using the <code>node:inspector</code> module, an attempt was made to use the
inspector after the session had already closed.</p>
<p><a id="ERR_INSPECTOR_COMMAND"></a></p>
<h4><code>ERR_INSPECTOR_COMMAND</code><span><a class="mark" href="#all_errors_err_inspector_command" id="all_errors_err_inspector_command">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_command"></a></h4>
<p>An error occurred while issuing a command via the <code>node:inspector</code> module.</p>
<p><a id="ERR_INSPECTOR_NOT_ACTIVE"></a></p>
<h4><code>ERR_INSPECTOR_NOT_ACTIVE</code><span><a class="mark" href="#all_errors_err_inspector_not_active" id="all_errors_err_inspector_not_active">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_not_active"></a></h4>
<p>The <code>inspector</code> is not active when <code>inspector.waitForDebugger()</code> is called.</p>
<p><a id="ERR_INSPECTOR_NOT_AVAILABLE"></a></p>
<h4><code>ERR_INSPECTOR_NOT_AVAILABLE</code><span><a class="mark" href="#all_errors_err_inspector_not_available" id="all_errors_err_inspector_not_available">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_not_available"></a></h4>
<p>The <code>node:inspector</code> module is not available for use.</p>
<p><a id="ERR_INSPECTOR_NOT_CONNECTED"></a></p>
<h4><code>ERR_INSPECTOR_NOT_CONNECTED</code><span><a class="mark" href="#all_errors_err_inspector_not_connected" id="all_errors_err_inspector_not_connected">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_not_connected"></a></h4>
<p>While using the <code>node:inspector</code> module, an attempt was made to use the
inspector before it was connected.</p>
<p><a id="ERR_INSPECTOR_NOT_WORKER"></a></p>
<h4><code>ERR_INSPECTOR_NOT_WORKER</code><span><a class="mark" href="#all_errors_err_inspector_not_worker" id="all_errors_err_inspector_not_worker">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_not_worker"></a></h4>
<p>An API was called on the main thread that can only be used from
the worker thread.</p>
<p><a id="ERR_INTERNAL_ASSERTION"></a></p>
<h4><code>ERR_INTERNAL_ASSERTION</code><span><a class="mark" href="#all_errors_err_internal_assertion" id="all_errors_err_internal_assertion">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_internal_assertion"></a></h4>
<p>There was a bug in Node.js or incorrect usage of Node.js internals.
To fix the error, open an issue at <a href="https://github.com/nodejs/node/issues">https://github.com/nodejs/node/issues</a>.</p>
<p><a id="ERR_INVALID_ADDRESS"></a></p>
<h4><code>ERR_INVALID_ADDRESS</code><span><a class="mark" href="#all_errors_err_invalid_address" id="all_errors_err_invalid_address">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_address"></a></h4>
<p>The provided address is not understood by the Node.js API.</p>
<p><a id="ERR_INVALID_ADDRESS_FAMILY"></a></p>
<h4><code>ERR_INVALID_ADDRESS_FAMILY</code><span><a class="mark" href="#all_errors_err_invalid_address_family" id="all_errors_err_invalid_address_family">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_address_family"></a></h4>
<p>The provided address family is not understood by the Node.js API.</p>
<p><a id="ERR_INVALID_ARG_TYPE"></a></p>
<h4><code>ERR_INVALID_ARG_TYPE</code><span><a class="mark" href="#all_errors_err_invalid_arg_type" id="all_errors_err_invalid_arg_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_arg_type"></a></h4>
<p>An argument of the wrong type was passed to a Node.js API.</p>
<p><a id="ERR_INVALID_ARG_VALUE"></a></p>
<h4><code>ERR_INVALID_ARG_VALUE</code><span><a class="mark" href="#all_errors_err_invalid_arg_value" id="all_errors_err_invalid_arg_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_arg_value"></a></h4>
<p>An invalid or unsupported value was passed for a given argument.</p>
<p><a id="ERR_INVALID_ASYNC_ID"></a></p>
<h4><code>ERR_INVALID_ASYNC_ID</code><span><a class="mark" href="#all_errors_err_invalid_async_id" id="all_errors_err_invalid_async_id">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_async_id"></a></h4>
<p>An invalid <code>asyncId</code> or <code>triggerAsyncId</code> was passed using <code>AsyncHooks</code>. An id
less than -1 should never happen.</p>
<p><a id="ERR_INVALID_BUFFER_SIZE"></a></p>
<h4><code>ERR_INVALID_BUFFER_SIZE</code><span><a class="mark" href="#all_errors_err_invalid_buffer_size" id="all_errors_err_invalid_buffer_size">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_buffer_size"></a></h4>
<p>A swap was performed on a <code>Buffer</code> but its size was not compatible with the
operation.</p>
<p><a id="ERR_INVALID_CHAR"></a></p>
<h4><code>ERR_INVALID_CHAR</code><span><a class="mark" href="#all_errors_err_invalid_char" id="all_errors_err_invalid_char">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_char"></a></h4>
<p>Invalid characters were detected in headers.</p>
<p><a id="ERR_INVALID_CURSOR_POS"></a></p>
<h4><code>ERR_INVALID_CURSOR_POS</code><span><a class="mark" href="#all_errors_err_invalid_cursor_pos" id="all_errors_err_invalid_cursor_pos">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_cursor_pos"></a></h4>
<p>A cursor on a given stream cannot be moved to a specified row without a
specified column.</p>
<p><a id="ERR_INVALID_FD"></a></p>
<h4><code>ERR_INVALID_FD</code><span><a class="mark" href="#all_errors_err_invalid_fd" id="all_errors_err_invalid_fd">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_fd"></a></h4>
<p>A file descriptor ('fd') was not valid (e.g. it was a negative value).</p>
<p><a id="ERR_INVALID_FD_TYPE"></a></p>
<h4><code>ERR_INVALID_FD_TYPE</code><span><a class="mark" href="#all_errors_err_invalid_fd_type" id="all_errors_err_invalid_fd_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_fd_type"></a></h4>
<p>A file descriptor ('fd') type was not valid.</p>
<p><a id="ERR_INVALID_FILE_URL_HOST"></a></p>
<h4><code>ERR_INVALID_FILE_URL_HOST</code><span><a class="mark" href="#all_errors_err_invalid_file_url_host" id="all_errors_err_invalid_file_url_host">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_file_url_host"></a></h4>
<p>A Node.js API that consumes <code>file:</code> URLs (such as certain functions in the
<a href="fs.html"><code>fs</code></a> module) encountered a file URL with an incompatible host. This
situation can only occur on Unix-like systems where only <code>localhost</code> or an empty
host is supported.</p>
<p><a id="ERR_INVALID_FILE_URL_PATH"></a></p>
<h4><code>ERR_INVALID_FILE_URL_PATH</code><span><a class="mark" href="#all_errors_err_invalid_file_url_path" id="all_errors_err_invalid_file_url_path">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_file_url_path"></a></h4>
<p>A Node.js API that consumes <code>file:</code> URLs (such as certain functions in the
<a href="fs.html"><code>fs</code></a> module) encountered a file URL with an incompatible path. The exact
semantics for determining whether a path can be used is platform-dependent.</p>
<p><a id="ERR_INVALID_HANDLE_TYPE"></a></p>
<h4><code>ERR_INVALID_HANDLE_TYPE</code><span><a class="mark" href="#all_errors_err_invalid_handle_type" id="all_errors_err_invalid_handle_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_handle_type"></a></h4>
<p>An attempt was made to send an unsupported "handle" over an IPC communication
channel to a child process. See <a href="#all_child_process_subprocesssendmessage-sendhandle-options-callback"><code>subprocess.send()</code></a> and <a href="#all_process_processsendmessage-sendhandle-options-callback"><code>process.send()</code></a>
for more information.</p>
<p><a id="ERR_INVALID_HTTP_TOKEN"></a></p>
<h4><code>ERR_INVALID_HTTP_TOKEN</code><span><a class="mark" href="#all_errors_err_invalid_http_token" id="all_errors_err_invalid_http_token">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_http_token"></a></h4>
<p>An invalid HTTP token was supplied.</p>
<p><a id="ERR_INVALID_IP_ADDRESS"></a></p>
<h4><code>ERR_INVALID_IP_ADDRESS</code><span><a class="mark" href="#all_errors_err_invalid_ip_address" id="all_errors_err_invalid_ip_address">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_ip_address"></a></h4>
<p>An IP address is not valid.</p>
<p><a id="ERR_INVALID_MIME_SYNTAX"></a></p>
<h4><code>ERR_INVALID_MIME_SYNTAX</code><span><a class="mark" href="#all_errors_err_invalid_mime_syntax" id="all_errors_err_invalid_mime_syntax">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_mime_syntax"></a></h4>
<p>The syntax of a MIME is not valid.</p>
<p><a id="ERR_INVALID_MODULE"></a></p>
<h4><code>ERR_INVALID_MODULE</code><span><a class="mark" href="#all_errors_err_invalid_module" id="all_errors_err_invalid_module">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_module"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<p>An attempt was made to load a module that does not exist or was otherwise not
valid.</p>
<p><a id="ERR_INVALID_MODULE_SPECIFIER"></a></p>
<h4><code>ERR_INVALID_MODULE_SPECIFIER</code><span><a class="mark" href="#all_errors_err_invalid_module_specifier" id="all_errors_err_invalid_module_specifier">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_module_specifier"></a></h4>
<p>The imported module string is an invalid URL, package name, or package subpath
specifier.</p>
<p><a id="ERR_INVALID_OBJECT_DEFINE_PROPERTY"></a></p>
<h4><code>ERR_INVALID_OBJECT_DEFINE_PROPERTY</code><span><a class="mark" href="#all_errors_err_invalid_object_define_property" id="all_errors_err_invalid_object_define_property">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_object_define_property"></a></h4>
<p>An error occurred while setting an invalid attribute on the property of
an object.</p>
<p><a id="ERR_INVALID_PACKAGE_CONFIG"></a></p>
<h4><code>ERR_INVALID_PACKAGE_CONFIG</code><span><a class="mark" href="#all_errors_err_invalid_package_config" id="all_errors_err_invalid_package_config">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_package_config"></a></h4>
<p>An invalid <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file failed parsing.</p>
<p><a id="ERR_INVALID_PACKAGE_TARGET"></a></p>
<h4><code>ERR_INVALID_PACKAGE_TARGET</code><span><a class="mark" href="#all_errors_err_invalid_package_target" id="all_errors_err_invalid_package_target">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_package_target"></a></h4>
<p>The <code>package.json</code> <a href="#all_packages_exports"><code>"exports"</code></a> field contains an invalid target mapping
value for the attempted module resolution.</p>
<p><a id="ERR_INVALID_PERFORMANCE_MARK"></a></p>
<h4><code>ERR_INVALID_PERFORMANCE_MARK</code><span><a class="mark" href="#all_errors_err_invalid_performance_mark" id="all_errors_err_invalid_performance_mark">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_performance_mark"></a></h4>
<p>While using the Performance Timing API (<code>perf_hooks</code>), a performance mark is
invalid.</p>
<p><a id="ERR_INVALID_PROTOCOL"></a></p>
<h4><code>ERR_INVALID_PROTOCOL</code><span><a class="mark" href="#all_errors_err_invalid_protocol" id="all_errors_err_invalid_protocol">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_protocol"></a></h4>
<p>An invalid <code>options.protocol</code> was passed to <code>http.request()</code>.</p>
<p><a id="ERR_INVALID_REPL_EVAL_CONFIG"></a></p>
<h4><code>ERR_INVALID_REPL_EVAL_CONFIG</code><span><a class="mark" href="#all_errors_err_invalid_repl_eval_config" id="all_errors_err_invalid_repl_eval_config">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_repl_eval_config"></a></h4>
<p>Both <code>breakEvalOnSigint</code> and <code>eval</code> options were set in the <a href="repl.html"><code>REPL</code></a> config,
which is not supported.</p>
<p><a id="ERR_INVALID_REPL_INPUT"></a></p>
<h4><code>ERR_INVALID_REPL_INPUT</code><span><a class="mark" href="#all_errors_err_invalid_repl_input" id="all_errors_err_invalid_repl_input">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_repl_input"></a></h4>
<p>The input may not be used in the <a href="repl.html"><code>REPL</code></a>. The conditions under which this
error is used are described in the <a href="repl.html"><code>REPL</code></a> documentation.</p>
<p><a id="ERR_INVALID_RETURN_PROPERTY"></a></p>
<h4><code>ERR_INVALID_RETURN_PROPERTY</code><span><a class="mark" href="#all_errors_err_invalid_return_property" id="all_errors_err_invalid_return_property">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_return_property"></a></h4>
<p>Thrown in case a function option does not provide a valid value for one of its
returned object properties on execution.</p>
<p><a id="ERR_INVALID_RETURN_PROPERTY_VALUE"></a></p>
<h4><code>ERR_INVALID_RETURN_PROPERTY_VALUE</code><span><a class="mark" href="#all_errors_err_invalid_return_property_value" id="all_errors_err_invalid_return_property_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_return_property_value"></a></h4>
<p>Thrown in case a function option does not provide an expected value
type for one of its returned object properties on execution.</p>
<p><a id="ERR_INVALID_RETURN_VALUE"></a></p>
<h4><code>ERR_INVALID_RETURN_VALUE</code><span><a class="mark" href="#all_errors_err_invalid_return_value" id="all_errors_err_invalid_return_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_return_value"></a></h4>
<p>Thrown in case a function option does not return an expected value
type on execution, such as when a function is expected to return a promise.</p>
<p><a id="ERR_INVALID_STATE"></a></p>
<h4><code>ERR_INVALID_STATE</code><span><a class="mark" href="#all_errors_err_invalid_state" id="all_errors_err_invalid_state">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_state"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>Indicates that an operation cannot be completed due to an invalid state.
For instance, an object may have already been destroyed, or may be
performing another operation.</p>
<p><a id="ERR_INVALID_SYNC_FORK_INPUT"></a></p>
<h4><code>ERR_INVALID_SYNC_FORK_INPUT</code><span><a class="mark" href="#all_errors_err_invalid_sync_fork_input" id="all_errors_err_invalid_sync_fork_input">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_sync_fork_input"></a></h4>
<p>A <code>Buffer</code>, <code>TypedArray</code>, <code>DataView</code>, or <code>string</code> was provided as stdio input to
an asynchronous fork. See the documentation for the <a href="child_process.html"><code>child_process</code></a> module
for more information.</p>
<p><a id="ERR_INVALID_THIS"></a></p>
<h4><code>ERR_INVALID_THIS</code><span><a class="mark" href="#all_errors_err_invalid_this" id="all_errors_err_invalid_this">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_this"></a></h4>
<p>A Node.js API function was called with an incompatible <code>this</code> value.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> urlSearchParams = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-string">'foo=bar&baz=new'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">1</span>);
urlSearchParams.<span class="hljs-property">has</span>.<span class="hljs-title function_">call</span>(buf, <span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Throws a TypeError with code 'ERR_INVALID_THIS'</span></code> <button class="copy-button">copy</button></pre>
<p><a id="ERR_INVALID_TRANSFER_OBJECT"></a></p>
<h4><code>ERR_INVALID_TRANSFER_OBJECT</code><span><a class="mark" href="#all_errors_err_invalid_transfer_object" id="all_errors_err_invalid_transfer_object">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_transfer_object"></a></h4>
<p>An invalid transfer object was passed to <code>postMessage()</code>.</p>
<p><a id="ERR_INVALID_TUPLE"></a></p>
<h4><code>ERR_INVALID_TUPLE</code><span><a class="mark" href="#all_errors_err_invalid_tuple" id="all_errors_err_invalid_tuple">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_tuple"></a></h4>
<p>An element in the <code>iterable</code> provided to the <a href="#all_url_the-whatwg-url-api">WHATWG</a>
<a href="#all_url_new-urlsearchparamsiterable"><code>URLSearchParams</code> constructor</a> did not
represent a <code>[name, value]</code> tuple – that is, if an element is not iterable, or
does not consist of exactly two elements.</p>
<p><a id="ERR_INVALID_URI"></a></p>
<h4><code>ERR_INVALID_URI</code><span><a class="mark" href="#all_errors_err_invalid_uri" id="all_errors_err_invalid_uri">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_uri"></a></h4>
<p>An invalid URI was passed.</p>
<p><a id="ERR_INVALID_URL"></a></p>
<h4><code>ERR_INVALID_URL</code><span><a class="mark" href="#all_errors_err_invalid_url" id="all_errors_err_invalid_url">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_url"></a></h4>
<p>An invalid URL was passed to the <a href="#all_url_the-whatwg-url-api">WHATWG</a> <a href="#all_url_new-urlinput-base"><code>URL</code>
constructor</a> or the legacy <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a> to be parsed.
The thrown error object typically has an additional property <code>'input'</code> that
contains the URL that failed to parse.</p>
<p><a id="ERR_INVALID_URL_SCHEME"></a></p>
<h4><code>ERR_INVALID_URL_SCHEME</code><span><a class="mark" href="#all_errors_err_invalid_url_scheme" id="all_errors_err_invalid_url_scheme">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_url_scheme"></a></h4>
<p>An attempt was made to use a URL of an incompatible scheme (protocol) for a
specific purpose. It is only used in the <a href="#all_url_the-whatwg-url-api">WHATWG URL API</a> support in the
<a href="fs.html"><code>fs</code></a> module (which only accepts URLs with <code>'file'</code> scheme), but may be used
in other Node.js APIs as well in the future.</p>
<p><a id="ERR_IPC_CHANNEL_CLOSED"></a></p>
<h4><code>ERR_IPC_CHANNEL_CLOSED</code><span><a class="mark" href="#all_errors_err_ipc_channel_closed" id="all_errors_err_ipc_channel_closed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_ipc_channel_closed"></a></h4>
<p>An attempt was made to use an IPC communication channel that was already closed.</p>
<p><a id="ERR_IPC_DISCONNECTED"></a></p>
<h4><code>ERR_IPC_DISCONNECTED</code><span><a class="mark" href="#all_errors_err_ipc_disconnected" id="all_errors_err_ipc_disconnected">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_ipc_disconnected"></a></h4>
<p>An attempt was made to disconnect an IPC communication channel that was already
disconnected. See the documentation for the <a href="child_process.html"><code>child_process</code></a> module
for more information.</p>
<p><a id="ERR_IPC_ONE_PIPE"></a></p>
<h4><code>ERR_IPC_ONE_PIPE</code><span><a class="mark" href="#all_errors_err_ipc_one_pipe" id="all_errors_err_ipc_one_pipe">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_ipc_one_pipe"></a></h4>
<p>An attempt was made to create a child Node.js process using more than one IPC
communication channel. See the documentation for the <a href="child_process.html"><code>child_process</code></a> module
for more information.</p>
<p><a id="ERR_IPC_SYNC_FORK"></a></p>
<h4><code>ERR_IPC_SYNC_FORK</code><span><a class="mark" href="#all_errors_err_ipc_sync_fork" id="all_errors_err_ipc_sync_fork">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_ipc_sync_fork"></a></h4>
<p>An attempt was made to open an IPC communication channel with a synchronously
forked Node.js process. See the documentation for the <a href="child_process.html"><code>child_process</code></a> module
for more information.</p>
<p><a id="ERR_LOADER_CHAIN_INCOMPLETE"></a></p>
<h4><code>ERR_LOADER_CHAIN_INCOMPLETE</code><span><a class="mark" href="#all_errors_err_loader_chain_incomplete" id="all_errors_err_loader_chain_incomplete">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_loader_chain_incomplete"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.0</span>
</div>
<p>An ESM loader hook returned without calling <code>next()</code> and without explicitly
signaling a short circuit.</p>
<p><a id="ERR_MANIFEST_ASSERT_INTEGRITY"></a></p>
<h4><code>ERR_MANIFEST_ASSERT_INTEGRITY</code><span><a class="mark" href="#all_errors_err_manifest_assert_integrity" id="all_errors_err_manifest_assert_integrity">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_assert_integrity"></a></h4>
<p>An attempt was made to load a resource, but the resource did not match the
integrity defined by the policy manifest. See the documentation for <a href="#all_permissions_policies">policy</a>
manifests for more information.</p>
<p><a id="ERR_MANIFEST_DEPENDENCY_MISSING"></a></p>
<h4><code>ERR_MANIFEST_DEPENDENCY_MISSING</code><span><a class="mark" href="#all_errors_err_manifest_dependency_missing" id="all_errors_err_manifest_dependency_missing">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_dependency_missing"></a></h4>
<p>An attempt was made to load a resource, but the resource was not listed as a
dependency from the location that attempted to load it. See the documentation
for <a href="#all_permissions_policies">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_INTEGRITY_MISMATCH"></a></p>
<h4><code>ERR_MANIFEST_INTEGRITY_MISMATCH</code><span><a class="mark" href="#all_errors_err_manifest_integrity_mismatch" id="all_errors_err_manifest_integrity_mismatch">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_integrity_mismatch"></a></h4>
<p>An attempt was made to load a policy manifest, but the manifest had multiple
entries for a resource which did not match each other. Update the manifest
entries to match in order to resolve this error. See the documentation for
<a href="#all_permissions_policies">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_INVALID_RESOURCE_FIELD"></a></p>
<h4><code>ERR_MANIFEST_INVALID_RESOURCE_FIELD</code><span><a class="mark" href="#all_errors_err_manifest_invalid_resource_field" id="all_errors_err_manifest_invalid_resource_field">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_invalid_resource_field"></a></h4>
<p>A policy manifest resource had an invalid value for one of its fields. Update
the manifest entry to match in order to resolve this error. See the
documentation for <a href="#all_permissions_policies">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_INVALID_SPECIFIER"></a></p>
<h4><code>ERR_MANIFEST_INVALID_SPECIFIER</code><span><a class="mark" href="#all_errors_err_manifest_invalid_specifier" id="all_errors_err_manifest_invalid_specifier">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_invalid_specifier"></a></h4>
<p>A policy manifest resource had an invalid value for one of its dependency
mappings. Update the manifest entry to match to resolve this error. See the
documentation for <a href="#all_permissions_policies">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_PARSE_POLICY"></a></p>
<h4><code>ERR_MANIFEST_PARSE_POLICY</code><span><a class="mark" href="#all_errors_err_manifest_parse_policy" id="all_errors_err_manifest_parse_policy">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_parse_policy"></a></h4>
<p>An attempt was made to load a policy manifest, but the manifest was unable to
be parsed. See the documentation for <a href="#all_permissions_policies">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_TDZ"></a></p>
<h4><code>ERR_MANIFEST_TDZ</code><span><a class="mark" href="#all_errors_err_manifest_tdz" id="all_errors_err_manifest_tdz">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_tdz"></a></h4>
<p>An attempt was made to read from a policy manifest, but the manifest
initialization has not yet taken place. This is likely a bug in Node.js.</p>
<p><a id="ERR_MANIFEST_UNKNOWN_ONERROR"></a></p>
<h4><code>ERR_MANIFEST_UNKNOWN_ONERROR</code><span><a class="mark" href="#all_errors_err_manifest_unknown_onerror" id="all_errors_err_manifest_unknown_onerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_unknown_onerror"></a></h4>
<p>A policy manifest was loaded, but had an unknown value for its "onerror"
behavior. See the documentation for <a href="#all_permissions_policies">policy</a> manifests for more information.</p>
<p><a id="ERR_MEMORY_ALLOCATION_FAILED"></a></p>
<h4><code>ERR_MEMORY_ALLOCATION_FAILED</code><span><a class="mark" href="#all_errors_err_memory_allocation_failed" id="all_errors_err_memory_allocation_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_memory_allocation_failed"></a></h4>
<p>An attempt was made to allocate memory (usually in the C++ layer) but it
failed.</p>
<p><a id="ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE"></a></p>
<h4><code>ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE</code><span><a class="mark" href="#all_errors_err_message_target_context_unavailable" id="all_errors_err_message_target_context_unavailable">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_message_target_context_unavailable"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</div>
<p>A message posted to a <a href="#all_worker_threads_class-messageport"><code>MessagePort</code></a> could not be deserialized in the target
<a href="vm.html">vm</a> <code>Context</code>. Not all Node.js objects can be successfully instantiated in
any context at this time, and attempting to transfer them using <code>postMessage()</code>
can fail on the receiving side in that case.</p>
<p><a id="ERR_METHOD_NOT_IMPLEMENTED"></a></p>
<h4><code>ERR_METHOD_NOT_IMPLEMENTED</code><span><a class="mark" href="#all_errors_err_method_not_implemented" id="all_errors_err_method_not_implemented">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_method_not_implemented"></a></h4>
<p>A method is required but not implemented.</p>
<p><a id="ERR_MISSING_ARGS"></a></p>
<h4><code>ERR_MISSING_ARGS</code><span><a class="mark" href="#all_errors_err_missing_args" id="all_errors_err_missing_args">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_missing_args"></a></h4>
<p>A required argument of a Node.js API was not passed. This is only used for
strict compliance with the API specification (which in some cases may accept
<code>func(undefined)</code> but not <code>func()</code>). In most native Node.js APIs,
<code>func(undefined)</code> and <code>func()</code> are treated identically, and the
<a href="#all_errors_err_invalid_arg_type"><code>ERR_INVALID_ARG_TYPE</code></a> error code may be used instead.</p>
<p><a id="ERR_MISSING_OPTION"></a></p>
<h4><code>ERR_MISSING_OPTION</code><span><a class="mark" href="#all_errors_err_missing_option" id="all_errors_err_missing_option">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_missing_option"></a></h4>
<p>For APIs that accept options objects, some options might be mandatory. This code
is thrown if a required option is missing.</p>
<p><a id="ERR_MISSING_PASSPHRASE"></a></p>
<h4><code>ERR_MISSING_PASSPHRASE</code><span><a class="mark" href="#all_errors_err_missing_passphrase" id="all_errors_err_missing_passphrase">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_missing_passphrase"></a></h4>
<p>An attempt was made to read an encrypted key without specifying a passphrase.</p>
<p><a id="ERR_MISSING_PLATFORM_FOR_WORKER"></a></p>
<h4><code>ERR_MISSING_PLATFORM_FOR_WORKER</code><span><a class="mark" href="#all_errors_err_missing_platform_for_worker" id="all_errors_err_missing_platform_for_worker">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_missing_platform_for_worker"></a></h4>
<p>The V8 platform used by this instance of Node.js does not support creating
Workers. This is caused by lack of embedder support for Workers. In particular,
this error will not occur with standard builds of Node.js.</p>
<p><a id="ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST"></a></p>
<h4><code>ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST</code><span><a class="mark" href="#all_errors_err_missing_transferable_in_transfer_list" id="all_errors_err_missing_transferable_in_transfer_list">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_missing_transferable_in_transfer_list"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An object that needs to be explicitly listed in the <code>transferList</code> argument
is in the object passed to a <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>postMessage()</code></a> call, but is not provided
in the <code>transferList</code> for that call. Usually, this is a <code>MessagePort</code>.</p>
<p>In Node.js versions prior to v15.0.0, the error code being used here was
<a href="#all_errors_err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a>. However, the set of
transferable object types has been expanded to cover more types than
<code>MessagePort</code>.</p>
<p><a id="ERR_MODULE_NOT_FOUND"></a></p>
<h4><code>ERR_MODULE_NOT_FOUND</code><span><a class="mark" href="#all_errors_err_module_not_found" id="all_errors_err_module_not_found">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_module_not_found"></a></h4>
<p>A module file could not be resolved by the ECMAScript modules loader while
attempting an <code>import</code> operation or when loading the program entry point.</p>
<p><a id="ERR_MULTIPLE_CALLBACK"></a></p>
<h4><code>ERR_MULTIPLE_CALLBACK</code><span><a class="mark" href="#all_errors_err_multiple_callback" id="all_errors_err_multiple_callback">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_multiple_callback"></a></h4>
<p>A callback was called more than once.</p>
<p>A callback is almost always meant to only be called once as the query
can either be fulfilled or rejected but not both at the same time. The latter
would be possible by calling a callback more than once.</p>
<p><a id="ERR_NAPI_CONS_FUNCTION"></a></p>
<h4><code>ERR_NAPI_CONS_FUNCTION</code><span><a class="mark" href="#all_errors_err_napi_cons_function" id="all_errors_err_napi_cons_function">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_cons_function"></a></h4>
<p>While using <code>Node-API</code>, a constructor passed was not a function.</p>
<p><a id="ERR_NAPI_INVALID_DATAVIEW_ARGS"></a></p>
<h4><code>ERR_NAPI_INVALID_DATAVIEW_ARGS</code><span><a class="mark" href="#all_errors_err_napi_invalid_dataview_args" id="all_errors_err_napi_invalid_dataview_args">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_invalid_dataview_args"></a></h4>
<p>While calling <code>napi_create_dataview()</code>, a given <code>offset</code> was outside the bounds
of the dataview or <code>offset + length</code> was larger than a length of given <code>buffer</code>.</p>
<p><a id="ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT"></a></p>
<h4><code>ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT</code><span><a class="mark" href="#all_errors_err_napi_invalid_typedarray_alignment" id="all_errors_err_napi_invalid_typedarray_alignment">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_invalid_typedarray_alignment"></a></h4>
<p>While calling <code>napi_create_typedarray()</code>, the provided <code>offset</code> was not a
multiple of the element size.</p>
<p><a id="ERR_NAPI_INVALID_TYPEDARRAY_LENGTH"></a></p>
<h4><code>ERR_NAPI_INVALID_TYPEDARRAY_LENGTH</code><span><a class="mark" href="#all_errors_err_napi_invalid_typedarray_length" id="all_errors_err_napi_invalid_typedarray_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_invalid_typedarray_length"></a></h4>
<p>While calling <code>napi_create_typedarray()</code>, <code>(length * size_of_element) + byte_offset</code> was larger than the length of given <code>buffer</code>.</p>
<p><a id="ERR_NAPI_TSFN_CALL_JS"></a></p>
<h4><code>ERR_NAPI_TSFN_CALL_JS</code><span><a class="mark" href="#all_errors_err_napi_tsfn_call_js" id="all_errors_err_napi_tsfn_call_js">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_tsfn_call_js"></a></h4>
<p>An error occurred while invoking the JavaScript portion of the thread-safe
function.</p>
<p><a id="ERR_NAPI_TSFN_GET_UNDEFINED"></a></p>
<h4><code>ERR_NAPI_TSFN_GET_UNDEFINED</code><span><a class="mark" href="#all_errors_err_napi_tsfn_get_undefined" id="all_errors_err_napi_tsfn_get_undefined">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_tsfn_get_undefined"></a></h4>
<p>An error occurred while attempting to retrieve the JavaScript <code>undefined</code>
value.</p>
<p><a id="ERR_NAPI_TSFN_START_IDLE_LOOP"></a></p>
<h4><code>ERR_NAPI_TSFN_START_IDLE_LOOP</code><span><a class="mark" href="#all_errors_err_napi_tsfn_start_idle_loop" id="all_errors_err_napi_tsfn_start_idle_loop">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_tsfn_start_idle_loop"></a></h4>
<p>On the main thread, values are removed from the queue associated with the
thread-safe function in an idle loop. This error indicates that an error
has occurred when attempting to start the loop.</p>
<p><a id="ERR_NAPI_TSFN_STOP_IDLE_LOOP"></a></p>
<h4><code>ERR_NAPI_TSFN_STOP_IDLE_LOOP</code><span><a class="mark" href="#all_errors_err_napi_tsfn_stop_idle_loop" id="all_errors_err_napi_tsfn_stop_idle_loop">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_tsfn_stop_idle_loop"></a></h4>
<p>Once no more items are left in the queue, the idle loop must be suspended. This
error indicates that the idle loop has failed to stop.</p>
<p><a id="ERR_NOT_BUILDING_SNAPSHOT"></a></p>
<h4><code>ERR_NOT_BUILDING_SNAPSHOT</code><span><a class="mark" href="#all_errors_err_not_building_snapshot" id="all_errors_err_not_building_snapshot">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_not_building_snapshot"></a></h4>
<p>An attempt was made to use operations that can only be used when building
V8 startup snapshot even though Node.js isn't building one.</p>
<p><a id="ERR_NOT_IN_SINGLE_EXECUTABLE_APPLICATION"></a></p>
<h4><code>ERR_NOT_IN_SINGLE_EXECUTABLE_APPLICATION</code><span><a class="mark" href="#all_errors_err_not_in_single_executable_application" id="all_errors_err_not_in_single_executable_application">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_not_in_single_executable_application"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p>The operation cannot be performed when it's not in a single-executable
application.</p>
<p><a id="ERR_NOT_SUPPORTED_IN_SNAPSHOT"></a></p>
<h4><code>ERR_NOT_SUPPORTED_IN_SNAPSHOT</code><span><a class="mark" href="#all_errors_err_not_supported_in_snapshot" id="all_errors_err_not_supported_in_snapshot">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_not_supported_in_snapshot"></a></h4>
<p>An attempt was made to perform operations that are not supported when
building a startup snapshot.</p>
<p><a id="ERR_NO_CRYPTO"></a></p>
<h4><code>ERR_NO_CRYPTO</code><span><a class="mark" href="#all_errors_err_no_crypto" id="all_errors_err_no_crypto">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_no_crypto"></a></h4>
<p>An attempt was made to use crypto features while Node.js was not compiled with
OpenSSL crypto support.</p>
<p><a id="ERR_NO_ICU"></a></p>
<h4><code>ERR_NO_ICU</code><span><a class="mark" href="#all_errors_err_no_icu" id="all_errors_err_no_icu">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_no_icu"></a></h4>
<p>An attempt was made to use features that require <a href="#all_intl_internationalization-support">ICU</a>, but Node.js was not
compiled with ICU support.</p>
<p><a id="ERR_NON_CONTEXT_AWARE_DISABLED"></a></p>
<h4><code>ERR_NON_CONTEXT_AWARE_DISABLED</code><span><a class="mark" href="#all_errors_err_non_context_aware_disabled" id="all_errors_err_non_context_aware_disabled">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_non_context_aware_disabled"></a></h4>
<p>A non-context-aware native addon was loaded in a process that disallows them.</p>
<p><a id="ERR_OUT_OF_RANGE"></a></p>
<h4><code>ERR_OUT_OF_RANGE</code><span><a class="mark" href="#all_errors_err_out_of_range" id="all_errors_err_out_of_range">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_out_of_range"></a></h4>
<p>A given value is out of the accepted range.</p>
<p><a id="ERR_PACKAGE_IMPORT_NOT_DEFINED"></a></p>
<h4><code>ERR_PACKAGE_IMPORT_NOT_DEFINED</code><span><a class="mark" href="#all_errors_err_package_import_not_defined" id="all_errors_err_package_import_not_defined">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_package_import_not_defined"></a></h4>
<p>The <code>package.json</code> <a href="#all_packages_imports"><code>"imports"</code></a> field does not define the given internal
package specifier mapping.</p>
<p><a id="ERR_PACKAGE_PATH_NOT_EXPORTED"></a></p>
<h4><code>ERR_PACKAGE_PATH_NOT_EXPORTED</code><span><a class="mark" href="#all_errors_err_package_path_not_exported" id="all_errors_err_package_path_not_exported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_package_path_not_exported"></a></h4>
<p>The <code>package.json</code> <a href="#all_packages_exports"><code>"exports"</code></a> field does not export the requested subpath.
Because exports are encapsulated, private internal modules that are not exported
cannot be imported through the package resolution, unless using an absolute URL.</p>
<p><a id="ERR_PARSE_ARGS_INVALID_OPTION_VALUE"></a></p>
<h4><code>ERR_PARSE_ARGS_INVALID_OPTION_VALUE</code><span><a class="mark" href="#all_errors_err_parse_args_invalid_option_value" id="all_errors_err_parse_args_invalid_option_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_parse_args_invalid_option_value"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<p>When <code>strict</code> set to <code>true</code>, thrown by <a href="#all_util_utilparseargsconfig"><code>util.parseArgs()</code></a> if a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a>
value is provided for an option of type <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, or if a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>
value is provided for an option of type <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a>.</p>
<p><a id="ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL"></a></p>
<h4><code>ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL</code><span><a class="mark" href="#all_errors_err_parse_args_unexpected_positional" id="all_errors_err_parse_args_unexpected_positional">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_parse_args_unexpected_positional"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<p>Thrown by <a href="#all_util_utilparseargsconfig"><code>util.parseArgs()</code></a>, when a positional argument is provided and
<code>allowPositionals</code> is set to <code>false</code>.</p>
<p><a id="ERR_PARSE_ARGS_UNKNOWN_OPTION"></a></p>
<h4><code>ERR_PARSE_ARGS_UNKNOWN_OPTION</code><span><a class="mark" href="#all_errors_err_parse_args_unknown_option" id="all_errors_err_parse_args_unknown_option">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_parse_args_unknown_option"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<p>When <code>strict</code> set to <code>true</code>, thrown by <a href="#all_util_utilparseargsconfig"><code>util.parseArgs()</code></a> if an argument
is not configured in <code>options</code>.</p>
<p><a id="ERR_PERFORMANCE_INVALID_TIMESTAMP"></a></p>
<h4><code>ERR_PERFORMANCE_INVALID_TIMESTAMP</code><span><a class="mark" href="#all_errors_err_performance_invalid_timestamp" id="all_errors_err_performance_invalid_timestamp">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_performance_invalid_timestamp"></a></h4>
<p>An invalid timestamp value was provided for a performance mark or measure.</p>
<p><a id="ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS"></a></p>
<h4><code>ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS</code><span><a class="mark" href="#all_errors_err_performance_measure_invalid_options" id="all_errors_err_performance_measure_invalid_options">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_performance_measure_invalid_options"></a></h4>
<p>Invalid options were provided for a performance measure.</p>
<p><a id="ERR_PROTO_ACCESS"></a></p>
<h4><code>ERR_PROTO_ACCESS</code><span><a class="mark" href="#all_errors_err_proto_access" id="all_errors_err_proto_access">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_proto_access"></a></h4>
<p>Accessing <code>Object.prototype.__proto__</code> has been forbidden using
<a href="#all_cli_--disable-protomode"><code>--disable-proto=throw</code></a>. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf"><code>Object.getPrototypeOf</code></a> and
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf"><code>Object.setPrototypeOf</code></a> should be used to get and set the prototype of an
object.</p>
<p><a id="ERR_REQUIRE_CYCLE_MODULE"></a></p>
<h4><code>ERR_REQUIRE_CYCLE_MODULE</code><span><a class="mark" href="#all_errors_err_require_cycle_module" id="all_errors_err_require_cycle_module">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_require_cycle_module"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>When trying to <code>require()</code> a <a href="esm.html">ES Module</a>, a CommonJS to ESM or ESM to CommonJS edge
participates in an immediate cycle.
This is not allowed because ES Modules cannot be evaluated while they are
already being evaluated.</p>
<p>To avoid the cycle, the <code>require()</code> call involved in a cycle should not happen
at the top-level of either an ES Module (via <code>createRequire()</code>) or a CommonJS
module, and should be done lazily in an inner function.</p>
<p><a id="ERR_REQUIRE_ASYNC_MODULE"></a></p>
<h4><code>ERR_REQUIRE_ASYNC_MODULE</code><span><a class="mark" href="#all_errors_err_require_async_module" id="all_errors_err_require_async_module">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_require_async_module"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>When trying to <code>require()</code> a <a href="esm.html">ES Module</a>, the module turns out to be asynchronous.
That is, it contains top-level await.</p>
<p>To see where the top-level await is, use
<code>--experimental-print-required-tla</code> (this would execute the modules
before looking for the top-level awaits).</p>
<p><a id="ERR_REQUIRE_ESM"></a></p>
<h4><code>ERR_REQUIRE_ESM</code><span><a class="mark" href="#all_errors_err_require_esm" id="all_errors_err_require_esm">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_require_esm"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.19.0</td>
<td><p>require() now supports loading synchronous ES modules by default.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p>An attempt was made to <code>require()</code> an <a href="esm.html">ES Module</a>.</p>
<p>This error has been deprecated since <code>require()</code> now supports loading synchronous
ES modules. When <code>require()</code> encounters an ES module that contains top-level
<code>await</code>, it will throw <a href="#all_errors_err_require_async_module"><code>ERR_REQUIRE_ASYNC_MODULE</code></a> instead.</p>
<p><a id="ERR_SCRIPT_EXECUTION_INTERRUPTED"></a></p>
<h4><code>ERR_SCRIPT_EXECUTION_INTERRUPTED</code><span><a class="mark" href="#all_errors_err_script_execution_interrupted" id="all_errors_err_script_execution_interrupted">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_script_execution_interrupted"></a></h4>
<p>Script execution was interrupted by <code>SIGINT</code> (For
example, <kbd>Ctrl</kbd>+<kbd>C</kbd> was pressed.)</p>
<p><a id="ERR_SCRIPT_EXECUTION_TIMEOUT"></a></p>
<h4><code>ERR_SCRIPT_EXECUTION_TIMEOUT</code><span><a class="mark" href="#all_errors_err_script_execution_timeout" id="all_errors_err_script_execution_timeout">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_script_execution_timeout"></a></h4>
<p>Script execution timed out, possibly due to bugs in the script being executed.</p>
<p><a id="ERR_SERVER_ALREADY_LISTEN"></a></p>
<h4><code>ERR_SERVER_ALREADY_LISTEN</code><span><a class="mark" href="#all_errors_err_server_already_listen" id="all_errors_err_server_already_listen">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_server_already_listen"></a></h4>
<p>The <a href="#all_net_serverlisten"><code>server.listen()</code></a> method was called while a <code>net.Server</code> was already
listening. This applies to all instances of <code>net.Server</code>, including HTTP, HTTPS,
and HTTP/2 <code>Server</code> instances.</p>
<p><a id="ERR_SERVER_NOT_RUNNING"></a></p>
<h4><code>ERR_SERVER_NOT_RUNNING</code><span><a class="mark" href="#all_errors_err_server_not_running" id="all_errors_err_server_not_running">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_server_not_running"></a></h4>
<p>The <a href="#all_net_serverclosecallback"><code>server.close()</code></a> method was called when a <code>net.Server</code> was not
running. This applies to all instances of <code>net.Server</code>, including HTTP, HTTPS,
and HTTP/2 <code>Server</code> instances.</p>
<p><a id="ERR_SINGLE_EXECUTABLE_APPLICATION_ASSET_NOT_FOUND"></a></p>
<h4><code>ERR_SINGLE_EXECUTABLE_APPLICATION_ASSET_NOT_FOUND</code><span><a class="mark" href="#all_errors_err_single_executable_application_asset_not_found" id="all_errors_err_single_executable_application_asset_not_found">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_single_executable_application_asset_not_found"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p>A key was passed to single executable application APIs to identify an asset,
but no match could be found.</p>
<p><a id="ERR_SOCKET_ALREADY_BOUND"></a></p>
<h4><code>ERR_SOCKET_ALREADY_BOUND</code><span><a class="mark" href="#all_errors_err_socket_already_bound" id="all_errors_err_socket_already_bound">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_already_bound"></a></h4>
<p>An attempt was made to bind a socket that has already been bound.</p>
<p><a id="ERR_SOCKET_BAD_BUFFER_SIZE"></a></p>
<h4><code>ERR_SOCKET_BAD_BUFFER_SIZE</code><span><a class="mark" href="#all_errors_err_socket_bad_buffer_size" id="all_errors_err_socket_bad_buffer_size">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_bad_buffer_size"></a></h4>
<p>An invalid (negative) size was passed for either the <code>recvBufferSize</code> or
<code>sendBufferSize</code> options in <a href="#all_dgram_dgramcreatesocketoptions-callback"><code>dgram.createSocket()</code></a>.</p>
<p><a id="ERR_SOCKET_BAD_PORT"></a></p>
<h4><code>ERR_SOCKET_BAD_PORT</code><span><a class="mark" href="#all_errors_err_socket_bad_port" id="all_errors_err_socket_bad_port">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_bad_port"></a></h4>
<p>An API function expecting a port >= 0 and < 65536 received an invalid value.</p>
<p><a id="ERR_SOCKET_BAD_TYPE"></a></p>
<h4><code>ERR_SOCKET_BAD_TYPE</code><span><a class="mark" href="#all_errors_err_socket_bad_type" id="all_errors_err_socket_bad_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_bad_type"></a></h4>
<p>An API function expecting a socket type (<code>udp4</code> or <code>udp6</code>) received an invalid
value.</p>
<p><a id="ERR_SOCKET_BUFFER_SIZE"></a></p>
<h4><code>ERR_SOCKET_BUFFER_SIZE</code><span><a class="mark" href="#all_errors_err_socket_buffer_size" id="all_errors_err_socket_buffer_size">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_buffer_size"></a></h4>
<p>While using <a href="#all_dgram_dgramcreatesocketoptions-callback"><code>dgram.createSocket()</code></a>, the size of the receive or send <code>Buffer</code>
could not be determined.</p>
<p><a id="ERR_SOCKET_CLOSED"></a></p>
<h4><code>ERR_SOCKET_CLOSED</code><span><a class="mark" href="#all_errors_err_socket_closed" id="all_errors_err_socket_closed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_closed"></a></h4>
<p>An attempt was made to operate on an already closed socket.</p>
<p><a id="ERR_SOCKET_CLOSED_BEFORE_CONNECTION"></a></p>
<h4><code>ERR_SOCKET_CLOSED_BEFORE_CONNECTION</code><span><a class="mark" href="#all_errors_err_socket_closed_before_connection" id="all_errors_err_socket_closed_before_connection">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_closed_before_connection"></a></h4>
<p>When calling <a href="#all_net_socketwritedata-encoding-callback"><code>net.Socket.write()</code></a> on a connecting socket and the socket was
closed before the connection was established.</p>
<p><a id="ERR_SOCKET_CONNECTION_TIMEOUT"></a></p>
<h4><code>ERR_SOCKET_CONNECTION_TIMEOUT</code><span><a class="mark" href="#all_errors_err_socket_connection_timeout" id="all_errors_err_socket_connection_timeout">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_connection_timeout"></a></h4>
<p>The socket was unable to connect to any address returned by the DNS within the
allowed timeout when using the family autoselection algorithm.</p>
<p><a id="ERR_SOCKET_DGRAM_IS_CONNECTED"></a></p>
<h4><code>ERR_SOCKET_DGRAM_IS_CONNECTED</code><span><a class="mark" href="#all_errors_err_socket_dgram_is_connected" id="all_errors_err_socket_dgram_is_connected">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_dgram_is_connected"></a></h4>
<p>A <a href="#all_dgram_socketconnectport-address-callback"><code>dgram.connect()</code></a> call was made on an already connected socket.</p>
<p><a id="ERR_SOCKET_DGRAM_NOT_CONNECTED"></a></p>
<h4><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code><span><a class="mark" href="#all_errors_err_socket_dgram_not_connected" id="all_errors_err_socket_dgram_not_connected">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_dgram_not_connected"></a></h4>
<p>A <a href="#all_dgram_socketdisconnect"><code>dgram.disconnect()</code></a> or <a href="#all_dgram_socketremoteaddress"><code>dgram.remoteAddress()</code></a> call was made on a
disconnected socket.</p>
<p><a id="ERR_SOCKET_DGRAM_NOT_RUNNING"></a></p>
<h4><code>ERR_SOCKET_DGRAM_NOT_RUNNING</code><span><a class="mark" href="#all_errors_err_socket_dgram_not_running" id="all_errors_err_socket_dgram_not_running">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_dgram_not_running"></a></h4>
<p>A call was made and the UDP subsystem was not running.</p>
<p><a id="ERR_SRI_PARSE"></a></p>
<h4><code>ERR_SRI_PARSE</code><span><a class="mark" href="#all_errors_err_sri_parse" id="all_errors_err_sri_parse">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_sri_parse"></a></h4>
<p>A string was provided for a Subresource Integrity check, but was unable to be
parsed. Check the format of integrity attributes by looking at the
<a href="https://www.w3.org/TR/SRI/#the-integrity-attribute">Subresource Integrity specification</a>.</p>
<p><a id="ERR_STREAM_ALREADY_FINISHED"></a></p>
<h4><code>ERR_STREAM_ALREADY_FINISHED</code><span><a class="mark" href="#all_errors_err_stream_already_finished" id="all_errors_err_stream_already_finished">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_already_finished"></a></h4>
<p>A stream method was called that cannot complete because the stream was
finished.</p>
<p><a id="ERR_STREAM_CANNOT_PIPE"></a></p>
<h4><code>ERR_STREAM_CANNOT_PIPE</code><span><a class="mark" href="#all_errors_err_stream_cannot_pipe" id="all_errors_err_stream_cannot_pipe">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_cannot_pipe"></a></h4>
<p>An attempt was made to call <a href="#all_stream_readablepipedestination-options"><code>stream.pipe()</code></a> on a <a href="#all_stream_class-streamwritable"><code>Writable</code></a> stream.</p>
<p><a id="ERR_STREAM_DESTROYED"></a></p>
<h4><code>ERR_STREAM_DESTROYED</code><span><a class="mark" href="#all_errors_err_stream_destroyed" id="all_errors_err_stream_destroyed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_destroyed"></a></h4>
<p>A stream method was called that cannot complete because the stream was
destroyed using <code>stream.destroy()</code>.</p>
<p><a id="ERR_STREAM_NULL_VALUES"></a></p>
<h4><code>ERR_STREAM_NULL_VALUES</code><span><a class="mark" href="#all_errors_err_stream_null_values" id="all_errors_err_stream_null_values">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_null_values"></a></h4>
<p>An attempt was made to call <a href="#all_stream_writablewritechunk-encoding-callback"><code>stream.write()</code></a> with a <code>null</code> chunk.</p>
<p><a id="ERR_STREAM_PREMATURE_CLOSE"></a></p>
<h4><code>ERR_STREAM_PREMATURE_CLOSE</code><span><a class="mark" href="#all_errors_err_stream_premature_close" id="all_errors_err_stream_premature_close">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_premature_close"></a></h4>
<p>An error returned by <code>stream.finished()</code> and <code>stream.pipeline()</code>, when a stream
or a pipeline ends non gracefully with no explicit error.</p>
<p><a id="ERR_STREAM_PUSH_AFTER_EOF"></a></p>
<h4><code>ERR_STREAM_PUSH_AFTER_EOF</code><span><a class="mark" href="#all_errors_err_stream_push_after_eof" id="all_errors_err_stream_push_after_eof">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_push_after_eof"></a></h4>
<p>An attempt was made to call <a href="#all_stream_readablepushchunk-encoding"><code>stream.push()</code></a> after a <code>null</code>(EOF) had been
pushed to the stream.</p>
<p><a id="ERR_STREAM_UNSHIFT_AFTER_END_EVENT"></a></p>
<h4><code>ERR_STREAM_UNSHIFT_AFTER_END_EVENT</code><span><a class="mark" href="#all_errors_err_stream_unshift_after_end_event" id="all_errors_err_stream_unshift_after_end_event">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_unshift_after_end_event"></a></h4>
<p>An attempt was made to call <a href="#all_stream_readableunshiftchunk-encoding"><code>stream.unshift()</code></a> after the <code>'end'</code> event was
emitted.</p>
<p><a id="ERR_STREAM_WRAP"></a></p>
<h4><code>ERR_STREAM_WRAP</code><span><a class="mark" href="#all_errors_err_stream_wrap" id="all_errors_err_stream_wrap">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_wrap"></a></h4>
<p>Prevents an abort if a string decoder was set on the Socket or if the decoder
is in <code>objectMode</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">Socket</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>).<span class="hljs-property">Socket</span>;
<span class="hljs-keyword">const</span> instance = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Socket</span>();
instance.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);</code> <button class="copy-button">copy</button></pre>
<p><a id="ERR_STREAM_WRITE_AFTER_END"></a></p>
<h4><code>ERR_STREAM_WRITE_AFTER_END</code><span><a class="mark" href="#all_errors_err_stream_write_after_end" id="all_errors_err_stream_write_after_end">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_write_after_end"></a></h4>
<p>An attempt was made to call <a href="#all_stream_writablewritechunk-encoding-callback"><code>stream.write()</code></a> after <code>stream.end()</code> has been
called.</p>
<p><a id="ERR_STRING_TOO_LONG"></a></p>
<h4><code>ERR_STRING_TOO_LONG</code><span><a class="mark" href="#all_errors_err_string_too_long" id="all_errors_err_string_too_long">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_string_too_long"></a></h4>
<p>An attempt has been made to create a string longer than the maximum allowed
length.</p>
<p><a id="ERR_SYNTHETIC"></a></p>
<h4><code>ERR_SYNTHETIC</code><span><a class="mark" href="#all_errors_err_synthetic" id="all_errors_err_synthetic">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_synthetic"></a></h4>
<p>An artificial error object used to capture the call stack for diagnostic
reports.</p>
<p><a id="ERR_SYSTEM_ERROR"></a></p>
<h4><code>ERR_SYSTEM_ERROR</code><span><a class="mark" href="#all_errors_err_system_error" id="all_errors_err_system_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_system_error"></a></h4>
<p>An unspecified or non-specific system error has occurred within the Node.js
process. The error object will have an <code>err.info</code> object property with
additional details.</p>
<p><a id="ERR_TEST_FAILURE"></a></p>
<h4><code>ERR_TEST_FAILURE</code><span><a class="mark" href="#all_errors_err_test_failure" id="all_errors_err_test_failure">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_test_failure"></a></h4>
<p>This error represents a failed test. Additional information about the failure
is available via the <code>cause</code> property. The <code>failureType</code> property specifies
what the test was doing when the failure occurred.</p>
<p><a id="ERR_TLS_ALPN_CALLBACK_INVALID_RESULT"></a></p>
<h4><code>ERR_TLS_ALPN_CALLBACK_INVALID_RESULT</code><span><a class="mark" href="#all_errors_err_tls_alpn_callback_invalid_result" id="all_errors_err_tls_alpn_callback_invalid_result">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_alpn_callback_invalid_result"></a></h4>
<p>This error is thrown when an <code>ALPNCallback</code> returns a value that is not in the
list of ALPN protocols offered by the client.</p>
<p><a id="ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS"></a></p>
<h4><code>ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS</code><span><a class="mark" href="#all_errors_err_tls_alpn_callback_with_protocols" id="all_errors_err_tls_alpn_callback_with_protocols">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_alpn_callback_with_protocols"></a></h4>
<p>This error is thrown when creating a <code>TLSServer</code> if the TLS options include
both <code>ALPNProtocols</code> and <code>ALPNCallback</code>. These options are mutually exclusive.</p>
<p><a id="ERR_TLS_CERT_ALTNAME_FORMAT"></a></p>
<h4><code>ERR_TLS_CERT_ALTNAME_FORMAT</code><span><a class="mark" href="#all_errors_err_tls_cert_altname_format" id="all_errors_err_tls_cert_altname_format">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_cert_altname_format"></a></h4>
<p>This error is thrown by <code>checkServerIdentity</code> if a user-supplied
<code>subjectaltname</code> property violates encoding rules. Certificate objects produced
by Node.js itself always comply with encoding rules and will never cause
this error.</p>
<p><a id="ERR_TLS_CERT_ALTNAME_INVALID"></a></p>
<h4><code>ERR_TLS_CERT_ALTNAME_INVALID</code><span><a class="mark" href="#all_errors_err_tls_cert_altname_invalid" id="all_errors_err_tls_cert_altname_invalid">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_cert_altname_invalid"></a></h4>
<p>While using TLS, the host name/IP of the peer did not match any of the
<code>subjectAltNames</code> in its certificate.</p>
<p><a id="ERR_TLS_DH_PARAM_SIZE"></a></p>
<h4><code>ERR_TLS_DH_PARAM_SIZE</code><span><a class="mark" href="#all_errors_err_tls_dh_param_size" id="all_errors_err_tls_dh_param_size">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_dh_param_size"></a></h4>
<p>While using TLS, the parameter offered for the Diffie-Hellman (<code>DH</code>)
key-agreement protocol is too small. By default, the key length must be greater
than or equal to 1024 bits to avoid vulnerabilities, even though it is strongly
recommended to use 2048 bits or larger for stronger security.</p>
<p><a id="ERR_TLS_HANDSHAKE_TIMEOUT"></a></p>
<h4><code>ERR_TLS_HANDSHAKE_TIMEOUT</code><span><a class="mark" href="#all_errors_err_tls_handshake_timeout" id="all_errors_err_tls_handshake_timeout">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_handshake_timeout"></a></h4>
<p>A TLS/SSL handshake timed out. In this case, the server must also abort the
connection.</p>
<p><a id="ERR_TLS_INVALID_CONTEXT"></a></p>
<h4><code>ERR_TLS_INVALID_CONTEXT</code><span><a class="mark" href="#all_errors_err_tls_invalid_context" id="all_errors_err_tls_invalid_context">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_invalid_context"></a></h4>
<div class="api_metadata">
<span>Added in: v13.3.0</span>
</div>
<p>The context must be a <code>SecureContext</code>.</p>
<p><a id="ERR_TLS_INVALID_PROTOCOL_METHOD"></a></p>
<h4><code>ERR_TLS_INVALID_PROTOCOL_METHOD</code><span><a class="mark" href="#all_errors_err_tls_invalid_protocol_method" id="all_errors_err_tls_invalid_protocol_method">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_invalid_protocol_method"></a></h4>
<p>The specified <code>secureProtocol</code> method is invalid. It is either unknown, or
disabled because it is insecure.</p>
<p><a id="ERR_TLS_INVALID_PROTOCOL_VERSION"></a></p>
<h4><code>ERR_TLS_INVALID_PROTOCOL_VERSION</code><span><a class="mark" href="#all_errors_err_tls_invalid_protocol_version" id="all_errors_err_tls_invalid_protocol_version">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_invalid_protocol_version"></a></h4>
<p>Valid TLS protocol versions are <code>'TLSv1'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1.2'</code>.</p>
<p><a id="ERR_TLS_INVALID_STATE"></a></p>
<h4><code>ERR_TLS_INVALID_STATE</code><span><a class="mark" href="#all_errors_err_tls_invalid_state" id="all_errors_err_tls_invalid_state">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_invalid_state"></a></h4>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<p>The TLS socket must be connected and securely established. Ensure the 'secure'
event is emitted before continuing.</p>
<p><a id="ERR_TLS_PROTOCOL_VERSION_CONFLICT"></a></p>
<h4><code>ERR_TLS_PROTOCOL_VERSION_CONFLICT</code><span><a class="mark" href="#all_errors_err_tls_protocol_version_conflict" id="all_errors_err_tls_protocol_version_conflict">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_protocol_version_conflict"></a></h4>
<p>Attempting to set a TLS protocol <code>minVersion</code> or <code>maxVersion</code> conflicts with an
attempt to set the <code>secureProtocol</code> explicitly. Use one mechanism or the other.</p>
<p><a id="ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED"></a></p>
<h4><code>ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED</code><span><a class="mark" href="#all_errors_err_tls_psk_set_identiy_hint_failed" id="all_errors_err_tls_psk_set_identiy_hint_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_psk_set_identiy_hint_failed"></a></h4>
<p>Failed to set PSK identity hint. Hint may be too long.</p>
<p><a id="ERR_TLS_RENEGOTIATION_DISABLED"></a></p>
<h4><code>ERR_TLS_RENEGOTIATION_DISABLED</code><span><a class="mark" href="#all_errors_err_tls_renegotiation_disabled" id="all_errors_err_tls_renegotiation_disabled">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_renegotiation_disabled"></a></h4>
<p>An attempt was made to renegotiate TLS on a socket instance with renegotiation
disabled.</p>
<p><a id="ERR_TLS_REQUIRED_SERVER_NAME"></a></p>
<h4><code>ERR_TLS_REQUIRED_SERVER_NAME</code><span><a class="mark" href="#all_errors_err_tls_required_server_name" id="all_errors_err_tls_required_server_name">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_required_server_name"></a></h4>
<p>While using TLS, the <code>server.addContext()</code> method was called without providing
a host name in the first parameter.</p>
<p><a id="ERR_TLS_SESSION_ATTACK"></a></p>
<h4><code>ERR_TLS_SESSION_ATTACK</code><span><a class="mark" href="#all_errors_err_tls_session_attack" id="all_errors_err_tls_session_attack">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_session_attack"></a></h4>
<p>An excessive amount of TLS renegotiations is detected, which is a potential
vector for denial-of-service attacks.</p>
<p><a id="ERR_TLS_SNI_FROM_SERVER"></a></p>
<h4><code>ERR_TLS_SNI_FROM_SERVER</code><span><a class="mark" href="#all_errors_err_tls_sni_from_server" id="all_errors_err_tls_sni_from_server">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_sni_from_server"></a></h4>
<p>An attempt was made to issue Server Name Indication from a TLS server-side
socket, which is only valid from a client.</p>
<p><a id="ERR_TRACE_EVENTS_CATEGORY_REQUIRED"></a></p>
<h4><code>ERR_TRACE_EVENTS_CATEGORY_REQUIRED</code><span><a class="mark" href="#all_errors_err_trace_events_category_required" id="all_errors_err_trace_events_category_required">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_trace_events_category_required"></a></h4>
<p>The <code>trace_events.createTracing()</code> method requires at least one trace event
category.</p>
<p><a id="ERR_TRACE_EVENTS_UNAVAILABLE"></a></p>
<h4><code>ERR_TRACE_EVENTS_UNAVAILABLE</code><span><a class="mark" href="#all_errors_err_trace_events_unavailable" id="all_errors_err_trace_events_unavailable">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_trace_events_unavailable"></a></h4>
<p>The <code>node:trace_events</code> module could not be loaded because Node.js was compiled
with the <code>--without-v8-platform</code> flag.</p>
<p><a id="ERR_TRANSFORM_ALREADY_TRANSFORMING"></a></p>
<h4><code>ERR_TRANSFORM_ALREADY_TRANSFORMING</code><span><a class="mark" href="#all_errors_err_transform_already_transforming" id="all_errors_err_transform_already_transforming">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_transform_already_transforming"></a></h4>
<p>A <code>Transform</code> stream finished while it was still transforming.</p>
<p><a id="ERR_TRANSFORM_WITH_LENGTH_0"></a></p>
<h4><code>ERR_TRANSFORM_WITH_LENGTH_0</code><span><a class="mark" href="#all_errors_err_transform_with_length_0" id="all_errors_err_transform_with_length_0">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_transform_with_length_0"></a></h4>
<p>A <code>Transform</code> stream finished with data still in the write buffer.</p>
<p><a id="ERR_TTY_INIT_FAILED"></a></p>
<h4><code>ERR_TTY_INIT_FAILED</code><span><a class="mark" href="#all_errors_err_tty_init_failed" id="all_errors_err_tty_init_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tty_init_failed"></a></h4>
<p>The initialization of a TTY failed due to a system error.</p>
<p><a id="ERR_UNAVAILABLE_DURING_EXIT"></a></p>
<h4><code>ERR_UNAVAILABLE_DURING_EXIT</code><span><a class="mark" href="#all_errors_err_unavailable_during_exit" id="all_errors_err_unavailable_during_exit">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unavailable_during_exit"></a></h4>
<p>Function was called within a <a href="#all_process_event-exit"><code>process.on('exit')</code></a> handler that shouldn't be
called within <a href="#all_process_event-exit"><code>process.on('exit')</code></a> handler.</p>
<p><a id="ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET"></a></p>
<h4><code>ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET</code><span><a class="mark" href="#all_errors_err_uncaught_exception_capture_already_set" id="all_errors_err_uncaught_exception_capture_already_set">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_uncaught_exception_capture_already_set"></a></h4>
<p><a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> was called twice,
without first resetting the callback to <code>null</code>.</p>
<p>This error is designed to prevent accidentally overwriting a callback registered
from another module.</p>
<p><a id="ERR_UNESCAPED_CHARACTERS"></a></p>
<h4><code>ERR_UNESCAPED_CHARACTERS</code><span><a class="mark" href="#all_errors_err_unescaped_characters" id="all_errors_err_unescaped_characters">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unescaped_characters"></a></h4>
<p>A string that contained unescaped characters was received.</p>
<p><a id="ERR_UNHANDLED_ERROR"></a></p>
<h4><code>ERR_UNHANDLED_ERROR</code><span><a class="mark" href="#all_errors_err_unhandled_error" id="all_errors_err_unhandled_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unhandled_error"></a></h4>
<p>An unhandled error occurred (for instance, when an <code>'error'</code> event is emitted
by an <a href="#all_events_class-eventemitter"><code>EventEmitter</code></a> but an <code>'error'</code> handler is not registered).</p>
<p><a id="ERR_UNKNOWN_BUILTIN_MODULE"></a></p>
<h4><code>ERR_UNKNOWN_BUILTIN_MODULE</code><span><a class="mark" href="#all_errors_err_unknown_builtin_module" id="all_errors_err_unknown_builtin_module">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_builtin_module"></a></h4>
<p>Used to identify a specific kind of internal Node.js error that should not
typically be triggered by user code. Instances of this error point to an
internal bug within the Node.js binary itself.</p>
<p><a id="ERR_UNKNOWN_CREDENTIAL"></a></p>
<h4><code>ERR_UNKNOWN_CREDENTIAL</code><span><a class="mark" href="#all_errors_err_unknown_credential" id="all_errors_err_unknown_credential">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_credential"></a></h4>
<p>A Unix group or user identifier that does not exist was passed.</p>
<p><a id="ERR_UNKNOWN_ENCODING"></a></p>
<h4><code>ERR_UNKNOWN_ENCODING</code><span><a class="mark" href="#all_errors_err_unknown_encoding" id="all_errors_err_unknown_encoding">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_encoding"></a></h4>
<p>An invalid or unknown encoding option was passed to an API.</p>
<p><a id="ERR_UNKNOWN_FILE_EXTENSION"></a></p>
<h4><code>ERR_UNKNOWN_FILE_EXTENSION</code><span><a class="mark" href="#all_errors_err_unknown_file_extension" id="all_errors_err_unknown_file_extension">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_file_extension"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>An attempt was made to load a module with an unknown or unsupported file
extension.</p>
<p><a id="ERR_UNKNOWN_MODULE_FORMAT"></a></p>
<h4><code>ERR_UNKNOWN_MODULE_FORMAT</code><span><a class="mark" href="#all_errors_err_unknown_module_format" id="all_errors_err_unknown_module_format">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_module_format"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>An attempt was made to load a module with an unknown or unsupported format.</p>
<p><a id="ERR_UNKNOWN_SIGNAL"></a></p>
<h4><code>ERR_UNKNOWN_SIGNAL</code><span><a class="mark" href="#all_errors_err_unknown_signal" id="all_errors_err_unknown_signal">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_signal"></a></h4>
<p>An invalid or unknown process signal was passed to an API expecting a valid
signal (such as <a href="#all_child_process_subprocesskillsignal"><code>subprocess.kill()</code></a>).</p>
<p><a id="ERR_UNSUPPORTED_DIR_IMPORT"></a></p>
<h4><code>ERR_UNSUPPORTED_DIR_IMPORT</code><span><a class="mark" href="#all_errors_err_unsupported_dir_import" id="all_errors_err_unsupported_dir_import">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unsupported_dir_import"></a></h4>
<p><code>import</code> a directory URL is unsupported. Instead,
<a href="#all_packages_self-referencing-a-package-using-its-name">self-reference a package using its name</a> and <a href="#all_packages_subpath-exports">define a custom subpath</a> in
the <a href="#all_packages_exports"><code>"exports"</code></a> field of the <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> <span class="hljs-string">'./'</span>; <span class="hljs-comment">// unsupported</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./index.js'</span>; <span class="hljs-comment">// supported</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'package-name'</span>; <span class="hljs-comment">// supported</span></code> <button class="copy-button">copy</button></pre>
<p><a id="ERR_UNSUPPORTED_ESM_URL_SCHEME"></a></p>
<h4><code>ERR_UNSUPPORTED_ESM_URL_SCHEME</code><span><a class="mark" href="#all_errors_err_unsupported_esm_url_scheme" id="all_errors_err_unsupported_esm_url_scheme">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unsupported_esm_url_scheme"></a></h4>
<p><code>import</code> with URL schemes other than <code>file</code> and <code>data</code> is unsupported.</p>
<p><a id="ERR_UNSUPPORTED_RESOLVE_REQUEST"></a></p>
<h4><code>ERR_UNSUPPORTED_RESOLVE_REQUEST</code><span><a class="mark" href="#all_errors_err_unsupported_resolve_request" id="all_errors_err_unsupported_resolve_request">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unsupported_resolve_request"></a></h4>
<p>An attempt was made to resolve an invalid module referrer. This can happen when
importing or calling <code>import.meta.resolve()</code> with either:</p>
<ul>
<li>a bare specifier that is not a builtin module from a module whose URL scheme
is not <code>file</code>.</li>
<li>a <a href="https://url.spec.whatwg.org/#relative-url-string">relative URL</a> from a module whose URL scheme is not a <a href="https://url.spec.whatwg.org/#special-scheme">special scheme</a>.</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">try</span> {
<span class="hljs-comment">// Trying to import the package 'bare-specifier' from a `data:` URL module:</span>
<span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'data:text/javascript,import "bare-specifier"'</span>);
} <span class="hljs-keyword">catch</span> (e) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e.<span class="hljs-property">code</span>); <span class="hljs-comment">// ERR_UNSUPPORTED_RESOLVE_REQUEST</span>
}</code> <button class="copy-button">copy</button></pre>
<p><a id="ERR_USE_AFTER_CLOSE"></a></p>
<h4><code>ERR_USE_AFTER_CLOSE</code><span><a class="mark" href="#all_errors_err_use_after_close" id="all_errors_err_use_after_close">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_use_after_close"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>An attempt was made to use something that was already closed.</p>
<p><a id="ERR_VALID_PERFORMANCE_ENTRY_TYPE"></a></p>
<h4><code>ERR_VALID_PERFORMANCE_ENTRY_TYPE</code><span><a class="mark" href="#all_errors_err_valid_performance_entry_type" id="all_errors_err_valid_performance_entry_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_valid_performance_entry_type"></a></h4>
<p>While using the Performance Timing API (<code>perf_hooks</code>), no valid performance
entry types are found.</p>
<p><a id="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG"></a></p>
<h4><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code><span><a class="mark" href="#all_errors_err_vm_dynamic_import_callback_missing_flag" id="all_errors_err_vm_dynamic_import_callback_missing_flag">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_dynamic_import_callback_missing_flag"></a></h4>
<p>A dynamic import callback was invoked without <code>--experimental-vm-modules</code>.</p>
<p><a id="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING"></a></p>
<h4><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code><span><a class="mark" href="#all_errors_err_vm_dynamic_import_callback_missing" id="all_errors_err_vm_dynamic_import_callback_missing">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_dynamic_import_callback_missing"></a></h4>
<p>A dynamic import callback was not specified.</p>
<p><a id="ERR_VM_MODULE_ALREADY_LINKED"></a></p>
<h4><code>ERR_VM_MODULE_ALREADY_LINKED</code><span><a class="mark" href="#all_errors_err_vm_module_already_linked" id="all_errors_err_vm_module_already_linked">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_already_linked"></a></h4>
<p>The module attempted to be linked is not eligible for linking, because of one of
the following reasons:</p>
<ul>
<li>It has already been linked (<code>linkingStatus</code> is <code>'linked'</code>)</li>
<li>It is being linked (<code>linkingStatus</code> is <code>'linking'</code>)</li>
<li>Linking has failed for this module (<code>linkingStatus</code> is <code>'errored'</code>)</li>
</ul>
<p><a id="ERR_VM_MODULE_CACHED_DATA_REJECTED"></a></p>
<h4><code>ERR_VM_MODULE_CACHED_DATA_REJECTED</code><span><a class="mark" href="#all_errors_err_vm_module_cached_data_rejected" id="all_errors_err_vm_module_cached_data_rejected">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_cached_data_rejected"></a></h4>
<p>The <code>cachedData</code> option passed to a module constructor is invalid.</p>
<p><a id="ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA"></a></p>
<h4><code>ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA</code><span><a class="mark" href="#all_errors_err_vm_module_cannot_create_cached_data" id="all_errors_err_vm_module_cannot_create_cached_data">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_cannot_create_cached_data"></a></h4>
<p>Cached data cannot be created for modules which have already been evaluated.</p>
<p><a id="ERR_VM_MODULE_DIFFERENT_CONTEXT"></a></p>
<h4><code>ERR_VM_MODULE_DIFFERENT_CONTEXT</code><span><a class="mark" href="#all_errors_err_vm_module_different_context" id="all_errors_err_vm_module_different_context">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_different_context"></a></h4>
<p>The module being returned from the linker function is from a different context
than the parent module. Linked modules must share the same context.</p>
<p><a id="ERR_VM_MODULE_LINK_FAILURE"></a></p>
<h4><code>ERR_VM_MODULE_LINK_FAILURE</code><span><a class="mark" href="#all_errors_err_vm_module_link_failure" id="all_errors_err_vm_module_link_failure">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_link_failure"></a></h4>
<p>The module was unable to be linked due to a failure.</p>
<p><a id="ERR_VM_MODULE_NOT_MODULE"></a></p>
<h4><code>ERR_VM_MODULE_NOT_MODULE</code><span><a class="mark" href="#all_errors_err_vm_module_not_module" id="all_errors_err_vm_module_not_module">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_not_module"></a></h4>
<p>The fulfilled value of a linking promise is not a <code>vm.Module</code> object.</p>
<p><a id="ERR_VM_MODULE_STATUS"></a></p>
<h4><code>ERR_VM_MODULE_STATUS</code><span><a class="mark" href="#all_errors_err_vm_module_status" id="all_errors_err_vm_module_status">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_status"></a></h4>
<p>The current module's status does not allow for this operation. The specific
meaning of the error depends on the specific function.</p>
<p><a id="ERR_WASI_ALREADY_STARTED"></a></p>
<h4><code>ERR_WASI_ALREADY_STARTED</code><span><a class="mark" href="#all_errors_err_wasi_already_started" id="all_errors_err_wasi_already_started">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_wasi_already_started"></a></h4>
<p>The WASI instance has already started.</p>
<p><a id="ERR_WASI_NOT_STARTED"></a></p>
<h4><code>ERR_WASI_NOT_STARTED</code><span><a class="mark" href="#all_errors_err_wasi_not_started" id="all_errors_err_wasi_not_started">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_wasi_not_started"></a></h4>
<p>The WASI instance has not been started.</p>
<p><a id="ERR_WEBASSEMBLY_RESPONSE"></a></p>
<h4><code>ERR_WEBASSEMBLY_RESPONSE</code><span><a class="mark" href="#all_errors_err_webassembly_response" id="all_errors_err_webassembly_response">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_webassembly_response"></a></h4>
<div class="api_metadata">
<span>Added in: v18.1.0</span>
</div>
<p>The <code>Response</code> that has been passed to <code>WebAssembly.compileStreaming</code> or to
<code>WebAssembly.instantiateStreaming</code> is not a valid WebAssembly response.</p>
<p><a id="ERR_WORKER_INIT_FAILED"></a></p>
<h4><code>ERR_WORKER_INIT_FAILED</code><span><a class="mark" href="#all_errors_err_worker_init_failed" id="all_errors_err_worker_init_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_init_failed"></a></h4>
<p>The <code>Worker</code> initialization failed.</p>
<p><a id="ERR_WORKER_INVALID_EXEC_ARGV"></a></p>
<h4><code>ERR_WORKER_INVALID_EXEC_ARGV</code><span><a class="mark" href="#all_errors_err_worker_invalid_exec_argv" id="all_errors_err_worker_invalid_exec_argv">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_invalid_exec_argv"></a></h4>
<p>The <code>execArgv</code> option passed to the <code>Worker</code> constructor contains
invalid flags.</p>
<p><a id="ERR_WORKER_NOT_RUNNING"></a></p>
<h4><code>ERR_WORKER_NOT_RUNNING</code><span><a class="mark" href="#all_errors_err_worker_not_running" id="all_errors_err_worker_not_running">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_not_running"></a></h4>
<p>An operation failed because the <code>Worker</code> instance is not currently running.</p>
<p><a id="ERR_WORKER_OUT_OF_MEMORY"></a></p>
<h4><code>ERR_WORKER_OUT_OF_MEMORY</code><span><a class="mark" href="#all_errors_err_worker_out_of_memory" id="all_errors_err_worker_out_of_memory">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_out_of_memory"></a></h4>
<p>The <code>Worker</code> instance terminated because it reached its memory limit.</p>
<p><a id="ERR_WORKER_PATH"></a></p>
<h4><code>ERR_WORKER_PATH</code><span><a class="mark" href="#all_errors_err_worker_path" id="all_errors_err_worker_path">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_path"></a></h4>
<p>The path for the main script of a worker is neither an absolute path
nor a relative path starting with <code>./</code> or <code>../</code>.</p>
<p><a id="ERR_WORKER_MESSAGING_ERRORED"></a></p>
<h4><code>ERR_WORKER_MESSAGING_ERRORED</code><span><a class="mark" href="#all_errors_err_worker_messaging_errored" id="all_errors_err_worker_messaging_errored">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_messaging_errored"></a></h4>
<div class="api_metadata">
<span>Added in: v20.19.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>The destination thread threw an error while processing a message sent via <a href="#all_worker_threads_workerpostmessagetothreadthreadid-value-transferlist-timeout"><code>postMessageToThread()</code></a>.</p>
<p><a id="ERR_WORKER_MESSAGING_FAILED"></a></p>
<h4><code>ERR_WORKER_MESSAGING_FAILED</code><span><a class="mark" href="#all_errors_err_worker_messaging_failed" id="all_errors_err_worker_messaging_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_messaging_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v20.19.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>The thread requested in <a href="#all_worker_threads_workerpostmessagetothreadthreadid-value-transferlist-timeout"><code>postMessageToThread()</code></a> is invalid or has no <code>workerMessage</code> listener.</p>
<p><a id="ERR_WORKER_MESSAGING_SAME_THREAD"></a></p>
<h4><code>ERR_WORKER_MESSAGING_SAME_THREAD</code><span><a class="mark" href="#all_errors_err_worker_messaging_same_thread" id="all_errors_err_worker_messaging_same_thread">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_messaging_same_thread"></a></h4>
<div class="api_metadata">
<span>Added in: v20.19.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>The thread id requested in <a href="#all_worker_threads_workerpostmessagetothreadthreadid-value-transferlist-timeout"><code>postMessageToThread()</code></a> is the current thread id.</p>
<p><a id="ERR_WORKER_MESSAGING_TIMEOUT"></a></p>
<h4><code>ERR_WORKER_MESSAGING_TIMEOUT</code><span><a class="mark" href="#all_errors_err_worker_messaging_timeout" id="all_errors_err_worker_messaging_timeout">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_messaging_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v20.19.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>Sending a message via <a href="#all_worker_threads_workerpostmessagetothreadthreadid-value-transferlist-timeout"><code>postMessageToThread()</code></a> timed out.</p>
<p><a id="ERR_WORKER_UNSERIALIZABLE_ERROR"></a></p>
<h4><code>ERR_WORKER_UNSERIALIZABLE_ERROR</code><span><a class="mark" href="#all_errors_err_worker_unserializable_error" id="all_errors_err_worker_unserializable_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_unserializable_error"></a></h4>
<p>All attempts at serializing an uncaught exception from a worker thread failed.</p>
<p><a id="ERR_WORKER_UNSUPPORTED_OPERATION"></a></p>
<h4><code>ERR_WORKER_UNSUPPORTED_OPERATION</code><span><a class="mark" href="#all_errors_err_worker_unsupported_operation" id="all_errors_err_worker_unsupported_operation">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_unsupported_operation"></a></h4>
<p>The requested functionality is not supported in worker threads.</p>
<p><a id="ERR_ZLIB_INITIALIZATION_FAILED"></a></p>
<h4><code>ERR_ZLIB_INITIALIZATION_FAILED</code><span><a class="mark" href="#all_errors_err_zlib_initialization_failed" id="all_errors_err_zlib_initialization_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_zlib_initialization_failed"></a></h4>
<p>Creation of a <a href="zlib.html"><code>zlib</code></a> object failed due to incorrect configuration.</p>
<p><a id="HPE_HEADER_OVERFLOW"></a></p>
<h4><code>HPE_HEADER_OVERFLOW</code><span><a class="mark" href="#all_errors_hpe_header_overflow" id="all_errors_hpe_header_overflow">#</a></span><a aria-hidden="true" class="legacy" id="errors_hpe_header_overflow"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.4.0, v10.15.0</td>
<td><p>Max header size in <code>http_parser</code> was set to 8 KiB.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Too much HTTP header data was received. In order to protect against malicious or
malconfigured clients, if more than <code>maxHeaderSize</code> of HTTP header data is received then
HTTP parsing will abort without a request or response object being created, and
an <code>Error</code> with this code will be emitted.</p>
<p><a id="HPE_CHUNK_EXTENSIONS_OVERFLOW"></a></p>
<h4><code>HPE_CHUNK_EXTENSIONS_OVERFLOW</code><span><a class="mark" href="#all_errors_hpe_chunk_extensions_overflow" id="all_errors_hpe_chunk_extensions_overflow">#</a></span><a aria-hidden="true" class="legacy" id="errors_hpe_chunk_extensions_overflow"></a></h4>
<div class="api_metadata">
<span>Added in: v20.11.1</span>
</div>
<p>Too much data was received for a chunk extensions. In order to protect against
malicious or malconfigured clients, if more than 16 KiB of data is received
then an <code>Error</code> with this code will be emitted.</p>
<p><a id="HPE_UNEXPECTED_CONTENT_LENGTH"></a></p>
<h4><code>HPE_UNEXPECTED_CONTENT_LENGTH</code><span><a class="mark" href="#all_errors_hpe_unexpected_content_length" id="all_errors_hpe_unexpected_content_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_hpe_unexpected_content_length"></a></h4>
<p>Server is sending both a <code>Content-Length</code> header and <code>Transfer-Encoding: chunked</code>.</p>
<p><code>Transfer-Encoding: chunked</code> allows the server to maintain an HTTP persistent
connection for dynamically generated content.
In this case, the <code>Content-Length</code> HTTP header cannot be used.</p>
<p>Use <code>Content-Length</code> or <code>Transfer-Encoding: chunked</code>.</p>
<p><a id="MODULE_NOT_FOUND"></a></p>
<h4><code>MODULE_NOT_FOUND</code><span><a class="mark" href="#all_errors_module_not_found" id="all_errors_module_not_found">#</a></span><a aria-hidden="true" class="legacy" id="errors_module_not_found"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Added <code>requireStack</code> property.</p></td></tr>
</tbody></table>
</details>
</div>
<p>A module file could not be resolved by the CommonJS modules loader while
attempting a <a href="#all_modules_requireid"><code>require()</code></a> operation or when loading the program entry point.</p>
</section><section><h3>Legacy Node.js error codes<span><a class="mark" href="#all_errors_legacy-nodejs-error-codes" id="all_errors_legacy-nodejs-error-codes">#</a></span><a aria-hidden="true" class="legacy" id="errors_legacy_node_js_error_codes"></a></h3>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. These error codes are either inconsistent, or have
been removed.</div><p></p>
<p><a id="ERR_CANNOT_TRANSFER_OBJECT"></a></p>
<h4><code>ERR_CANNOT_TRANSFER_OBJECT</code><span><a class="mark" href="#all_errors_err_cannot_transfer_object" id="all_errors_err_cannot_transfer_object">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_cannot_transfer_object"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span><span>Removed in: v12.5.0</span>
</div>
<p>The value passed to <code>postMessage()</code> contained an object that is not supported
for transferring.</p>
<p><a id="ERR_CRYPTO_HASH_DIGEST_NO_UTF16"></a></p>
<h4><code>ERR_CRYPTO_HASH_DIGEST_NO_UTF16</code><span><a class="mark" href="#all_errors_err_crypto_hash_digest_no_utf16" id="all_errors_err_crypto_hash_digest_no_utf16">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_hash_digest_no_utf16"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v12.12.0</span>
</div>
<p>The UTF-16 encoding was used with <a href="#all_crypto_hashdigestencoding"><code>hash.digest()</code></a>. While the
<code>hash.digest()</code> method does allow an <code>encoding</code> argument to be passed in,
causing the method to return a string rather than a <code>Buffer</code>, the UTF-16
encoding (e.g. <code>ucs</code> or <code>utf16le</code>) is not supported.</p>
<p><a id="ERR_HTTP2_FRAME_ERROR"></a></p>
<h4><code>ERR_HTTP2_FRAME_ERROR</code><span><a class="mark" href="#all_errors_err_http2_frame_error" id="all_errors_err_http2_frame_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_frame_error"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when a failure occurs sending an individual frame on the HTTP/2
session.</p>
<p><a id="ERR_HTTP2_HEADERS_OBJECT"></a></p>
<h4><code>ERR_HTTP2_HEADERS_OBJECT</code><span><a class="mark" href="#all_errors_err_http2_headers_object" id="all_errors_err_http2_headers_object">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_headers_object"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when an HTTP/2 Headers Object is expected.</p>
<p><a id="ERR_HTTP2_HEADER_REQUIRED"></a></p>
<h4><code>ERR_HTTP2_HEADER_REQUIRED</code><span><a class="mark" href="#all_errors_err_http2_header_required" id="all_errors_err_http2_header_required">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_header_required"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when a required header is missing in an HTTP/2 message.</p>
<p><a id="ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND"></a></p>
<h4><code>ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND</code><span><a class="mark" href="#all_errors_err_http2_info_headers_after_respond" id="all_errors_err_http2_info_headers_after_respond">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_info_headers_after_respond"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>HTTP/2 informational headers must only be sent <em>prior</em> to calling the
<code>Http2Stream.prototype.respond()</code> method.</p>
<p><a id="ERR_HTTP2_STREAM_CLOSED"></a></p>
<h4><code>ERR_HTTP2_STREAM_CLOSED</code><span><a class="mark" href="#all_errors_err_http2_stream_closed" id="all_errors_err_http2_stream_closed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_stream_closed"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when an action has been performed on an HTTP/2 Stream that has already
been closed.</p>
<p><a id="ERR_HTTP_INVALID_CHAR"></a></p>
<h4><code>ERR_HTTP_INVALID_CHAR</code><span><a class="mark" href="#all_errors_err_http_invalid_char" id="all_errors_err_http_invalid_char">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_invalid_char"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when an invalid character is found in an HTTP response status message
(reason phrase).</p>
<p><a id="ERR_INDEX_OUT_OF_RANGE"></a></p>
<h4><code>ERR_INDEX_OUT_OF_RANGE</code><span><a class="mark" href="#all_errors_err_index_out_of_range" id="all_errors_err_index_out_of_range">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_index_out_of_range"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span><span>Removed in: v11.0.0</span>
</div>
<p>A given index was out of the accepted range (e.g. negative offsets).</p>
<p><a id="ERR_INVALID_OPT_VALUE"></a></p>
<h4><code>ERR_INVALID_OPT_VALUE</code><span><a class="mark" href="#all_errors_err_invalid_opt_value" id="all_errors_err_invalid_opt_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_opt_value"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span><span>Removed in: v15.0.0</span>
</div>
<p>An invalid or unexpected value was passed in an options object.</p>
<p><a id="ERR_INVALID_OPT_VALUE_ENCODING"></a></p>
<h4><code>ERR_INVALID_OPT_VALUE_ENCODING</code><span><a class="mark" href="#all_errors_err_invalid_opt_value_encoding" id="all_errors_err_invalid_opt_value_encoding">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_opt_value_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v15.0.0</span>
</div>
<p>An invalid or unknown file encoding was passed.</p>
<p><a id="ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST"></a></p>
<h4><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code><span><a class="mark" href="#all_errors_err_missing_message_port_in_transfer_list" id="all_errors_err_missing_message_port_in_transfer_list">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_missing_message_port_in_transfer_list"></a></h4>
<div class="api_metadata">
<span>Removed in: v15.0.0</span>
</div>
<p>This error code was replaced by <a href="#all_errors_err_missing_transferable_in_transfer_list"><code>ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST</code></a>
in Node.js v15.0.0, because it is no longer accurate as other types of
transferable objects also exist now.</p>
<p><a id="ERR_NAPI_CONS_PROTOTYPE_OBJECT"></a></p>
<h4><code>ERR_NAPI_CONS_PROTOTYPE_OBJECT</code><span><a class="mark" href="#all_errors_err_napi_cons_prototype_object" id="all_errors_err_napi_cons_prototype_object">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_cons_prototype_object"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used by the <code>Node-API</code> when <code>Constructor.prototype</code> is not an object.</p>
<p><a id="ERR_NETWORK_IMPORT_BAD_RESPONSE"></a></p>
<h4><code>ERR_NETWORK_IMPORT_BAD_RESPONSE</code><span><a class="mark" href="#all_errors_err_network_import_bad_response" id="all_errors_err_network_import_bad_response">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_network_import_bad_response"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Response was received but was invalid when importing a module over the network.</p>
<p><a id="ERR_NETWORK_IMPORT_DISALLOWED"></a></p>
<h4><code>ERR_NETWORK_IMPORT_DISALLOWED</code><span><a class="mark" href="#all_errors_err_network_import_disallowed" id="all_errors_err_network_import_disallowed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_network_import_disallowed"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>A network module attempted to load another module that it is not allowed to
load. Likely this restriction is for security reasons.</p>
<p><a id="ERR_NO_LONGER_SUPPORTED"></a></p>
<h4><code>ERR_NO_LONGER_SUPPORTED</code><span><a class="mark" href="#all_errors_err_no_longer_supported" id="all_errors_err_no_longer_supported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_no_longer_supported"></a></h4>
<p>A Node.js API was called in an unsupported manner, such as
<code>Buffer.write(string, encoding, offset[, length])</code>.</p>
<p><a id="ERR_OPERATION_FAILED"></a></p>
<h4><code>ERR_OPERATION_FAILED</code><span><a class="mark" href="#all_errors_err_operation_failed" id="all_errors_err_operation_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_operation_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An operation failed. This is typically used to signal the general failure
of an asynchronous operation.</p>
<p><a id="ERR_OUTOFMEMORY"></a></p>
<h4><code>ERR_OUTOFMEMORY</code><span><a class="mark" href="#all_errors_err_outofmemory" id="all_errors_err_outofmemory">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_outofmemory"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used generically to identify that an operation caused an out of memory
condition.</p>
<p><a id="ERR_PARSE_HISTORY_DATA"></a></p>
<h4><code>ERR_PARSE_HISTORY_DATA</code><span><a class="mark" href="#all_errors_err_parse_history_data" id="all_errors_err_parse_history_data">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_parse_history_data"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>The <code>node:repl</code> module was unable to parse data from the REPL history file.</p>
<p><a id="ERR_SOCKET_CANNOT_SEND"></a></p>
<h4><code>ERR_SOCKET_CANNOT_SEND</code><span><a class="mark" href="#all_errors_err_socket_cannot_send" id="all_errors_err_socket_cannot_send">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_cannot_send"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v14.0.0</span>
</div>
<p>Data could not be sent on a socket.</p>
<p><a id="ERR_STDERR_CLOSE"></a></p>
<h4><code>ERR_STDERR_CLOSE</code><span><a class="mark" href="#all_errors_err_stderr_close" id="all_errors_err_stderr_close">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stderr_close"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.12.0</td>
<td><p>Rather than emitting an error, <code>process.stderr.end()</code> now only closes the stream side but not the underlying resource, making this error obsolete.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p><span>Removed in: v10.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An attempt was made to close the <code>process.stderr</code> stream. By design, Node.js
does not allow <code>stdout</code> or <code>stderr</code> streams to be closed by user code.</p>
<p><a id="ERR_STDOUT_CLOSE"></a></p>
<h4><code>ERR_STDOUT_CLOSE</code><span><a class="mark" href="#all_errors_err_stdout_close" id="all_errors_err_stdout_close">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stdout_close"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.12.0</td>
<td><p>Rather than emitting an error, <code>process.stderr.end()</code> now only closes the stream side but not the underlying resource, making this error obsolete.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p><span>Removed in: v10.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An attempt was made to close the <code>process.stdout</code> stream. By design, Node.js
does not allow <code>stdout</code> or <code>stderr</code> streams to be closed by user code.</p>
<p><a id="ERR_STREAM_READ_NOT_IMPLEMENTED"></a></p>
<h4><code>ERR_STREAM_READ_NOT_IMPLEMENTED</code><span><a class="mark" href="#all_errors_err_stream_read_not_implemented" id="all_errors_err_stream_read_not_implemented">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_read_not_implemented"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when an attempt is made to use a readable stream that has not implemented
<a href="#all_stream_readable_readsize"><code>readable._read()</code></a>.</p>
<p><a id="ERR_TAP_LEXER_ERROR"></a></p>
<h4><code>ERR_TAP_LEXER_ERROR</code><span><a class="mark" href="#all_errors_err_tap_lexer_error" id="all_errors_err_tap_lexer_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tap_lexer_error"></a></h4>
<p>An error representing a failing lexer state.</p>
<p><a id="ERR_TAP_PARSER_ERROR"></a></p>
<h4><code>ERR_TAP_PARSER_ERROR</code><span><a class="mark" href="#all_errors_err_tap_parser_error" id="all_errors_err_tap_parser_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tap_parser_error"></a></h4>
<p>An error representing a failing parser state. Additional information about
the token causing the error is available via the <code>cause</code> property.</p>
<p><a id="ERR_TAP_VALIDATION_ERROR"></a></p>
<h4><code>ERR_TAP_VALIDATION_ERROR</code><span><a class="mark" href="#all_errors_err_tap_validation_error" id="all_errors_err_tap_validation_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tap_validation_error"></a></h4>
<p>This error represents a failed TAP validation.</p>
<p><a id="ERR_TLS_RENEGOTIATION_FAILED"></a></p>
<h4><code>ERR_TLS_RENEGOTIATION_FAILED</code><span><a class="mark" href="#all_errors_err_tls_renegotiation_failed" id="all_errors_err_tls_renegotiation_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_renegotiation_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when a TLS renegotiation request has failed in a non-specific way.</p>
<p><a id="ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER"></a></p>
<h4><code>ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER</code><span><a class="mark" href="#all_errors_err_transferring_externalized_sharedarraybuffer" id="all_errors_err_transferring_externalized_sharedarraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_transferring_externalized_sharedarraybuffer"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span><span>Removed in: v14.0.0</span>
</div>
<p>A <code>SharedArrayBuffer</code> whose memory is not managed by the JavaScript engine
or by Node.js was encountered during serialization. Such a <code>SharedArrayBuffer</code>
cannot be serialized.</p>
<p>This can only happen when native addons create <code>SharedArrayBuffer</code>s in
"externalized" mode, or put existing <code>SharedArrayBuffer</code> into externalized mode.</p>
<p><a id="ERR_UNKNOWN_STDIN_TYPE"></a></p>
<h4><code>ERR_UNKNOWN_STDIN_TYPE</code><span><a class="mark" href="#all_errors_err_unknown_stdin_type" id="all_errors_err_unknown_stdin_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_stdin_type"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span><span>Removed in: v11.7.0</span>
</div>
<p>An attempt was made to launch a Node.js process with an unknown <code>stdin</code> file
type. This error is usually an indication of a bug within Node.js itself,
although it is possible for user code to trigger it.</p>
<p><a id="ERR_UNKNOWN_STREAM_TYPE"></a></p>
<h4><code>ERR_UNKNOWN_STREAM_TYPE</code><span><a class="mark" href="#all_errors_err_unknown_stream_type" id="all_errors_err_unknown_stream_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_stream_type"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span><span>Removed in: v11.7.0</span>
</div>
<p>An attempt was made to launch a Node.js process with an unknown <code>stdout</code> or
<code>stderr</code> file type. This error is usually an indication of a bug within Node.js
itself, although it is possible for user code to trigger it.</p>
<p><a id="ERR_V8BREAKITERATOR"></a></p>
<h4><code>ERR_V8BREAKITERATOR</code><span><a class="mark" href="#all_errors_err_v8breakiterator" id="all_errors_err_v8breakiterator">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_v8breakiterator"></a></h4>
<p>The V8 <code>BreakIterator</code> API was used but the full ICU data set is not installed.</p>
<p><a id="ERR_VALUE_OUT_OF_RANGE"></a></p>
<h4><code>ERR_VALUE_OUT_OF_RANGE</code><span><a class="mark" href="#all_errors_err_value_out_of_range" id="all_errors_err_value_out_of_range">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_value_out_of_range"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when a given value is out of the accepted range.</p>
<p><a id="ERR_VM_MODULE_NOT_LINKED"></a></p>
<h4><code>ERR_VM_MODULE_NOT_LINKED</code><span><a class="mark" href="#all_errors_err_vm_module_not_linked" id="all_errors_err_vm_module_not_linked">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_not_linked"></a></h4>
<p>The module must be successfully linked before instantiation.</p>
<p><a id="ERR_VM_MODULE_LINKING_ERRORED"></a></p>
<h4><code>ERR_VM_MODULE_LINKING_ERRORED</code><span><a class="mark" href="#all_errors_err_vm_module_linking_errored" id="all_errors_err_vm_module_linking_errored">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_linking_errored"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span><span>Removed in: v18.1.0, v16.17.0</span>
</div>
<p>The linker function returned a module for which linking has failed.</p>
<p><a id="ERR_WORKER_UNSUPPORTED_EXTENSION"></a></p>
<h4><code>ERR_WORKER_UNSUPPORTED_EXTENSION</code><span><a class="mark" href="#all_errors_err_worker_unsupported_extension" id="all_errors_err_worker_unsupported_extension">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_unsupported_extension"></a></h4>
<div class="api_metadata">
<span>Added in: v11.0.0</span><span>Removed in: v16.9.0</span>
</div>
<p>The pathname used for the main script of a worker has an
unknown file extension.</p>
<p><a id="ERR_ZLIB_BINDING_CLOSED"></a></p>
<h4><code>ERR_ZLIB_BINDING_CLOSED</code><span><a class="mark" href="#all_errors_err_zlib_binding_closed" id="all_errors_err_zlib_binding_closed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_zlib_binding_closed"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when an attempt is made to use a <code>zlib</code> object after it has already been
closed.</p>
<p><a id="ERR_CPU_USAGE"></a></p>
<h4><code>ERR_CPU_USAGE</code><span><a class="mark" href="#all_errors_err_cpu_usage" id="all_errors_err_cpu_usage">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_cpu_usage"></a></h4>
<div class="api_metadata">
<span>Removed in: v15.0.0</span>
</div>
<p>The native call from <code>process.cpuUsage</code> could not be processed.</p>
<p><a id="openssl-error-codes"></a></p>
</section><section><h3>OpenSSL Error Codes<span><a class="mark" href="#all_errors_openssl-error-codes" id="all_errors_openssl-error-codes">#</a></span><a aria-hidden="true" class="legacy" id="errors_openssl_error_codes"></a></h3>
<p><a id="Time Validity Errors"></a></p>
<h4>Time Validity Errors<span><a class="mark" href="#all_errors_time-validity-errors" id="all_errors_time-validity-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_time_validity_errors"></a></h4>
<p><a id="CERT_NOT_YET_VALID"></a></p>
<h5><code>CERT_NOT_YET_VALID</code><span><a class="mark" href="#all_errors_cert_not_yet_valid" id="all_errors_cert_not_yet_valid">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_not_yet_valid"></a></h5>
<p>The certificate is not yet valid: the notBefore date is after the current time.</p>
<p><a id="CERT_HAS_EXPIRED"></a></p>
<h5><code>CERT_HAS_EXPIRED</code><span><a class="mark" href="#all_errors_cert_has_expired" id="all_errors_cert_has_expired">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_has_expired"></a></h5>
<p>The certificate has expired: the notAfter date is before the current time.</p>
<p><a id="CRL_NOT_YET_VALID"></a></p>
<h5><code>CRL_NOT_YET_VALID</code><span><a class="mark" href="#all_errors_crl_not_yet_valid" id="all_errors_crl_not_yet_valid">#</a></span><a aria-hidden="true" class="legacy" id="errors_crl_not_yet_valid"></a></h5>
<p>The certificate revocation list (CRL) has a future issue date.</p>
<p><a id="CRL_HAS_EXPIRED"></a></p>
<h5><code>CRL_HAS_EXPIRED</code><span><a class="mark" href="#all_errors_crl_has_expired" id="all_errors_crl_has_expired">#</a></span><a aria-hidden="true" class="legacy" id="errors_crl_has_expired"></a></h5>
<p>The certificate revocation list (CRL) has expired.</p>
<p><a id="CERT_REVOKED"></a></p>
<h5><code>CERT_REVOKED</code><span><a class="mark" href="#all_errors_cert_revoked" id="all_errors_cert_revoked">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_revoked"></a></h5>
<p>The certificate has been revoked; it is on a certificate revocation list (CRL).</p>
<p><a id="Trust or Chain Related Errors"></a></p>
<h4>Trust or Chain Related Errors<span><a class="mark" href="#all_errors_trust-or-chain-related-errors" id="all_errors_trust-or-chain-related-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_trust_or_chain_related_errors"></a></h4>
<p><a id="UNABLE_TO_GET_ISSUER_CERT"></a></p>
<h5><code>UNABLE_TO_GET_ISSUER_CERT</code><span><a class="mark" href="#all_errors_unable_to_get_issuer_cert" id="all_errors_unable_to_get_issuer_cert">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_get_issuer_cert"></a></h5>
<p>The issuer certificate of a looked up certificate could not be found. This
normally means the list of trusted certificates is not complete.</p>
<p><a id="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"></a></p>
<h5><code>UNABLE_TO_GET_ISSUER_CERT_LOCALLY</code><span><a class="mark" href="#all_errors_unable_to_get_issuer_cert_locally" id="all_errors_unable_to_get_issuer_cert_locally">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_get_issuer_cert_locally"></a></h5>
<p>The certificate’s issuer is not known. This is the case if the issuer is not
included in the trusted certificate list.</p>
<p><a id="DEPTH_ZERO_SELF_SIGNED_CERT"></a></p>
<h5><code>DEPTH_ZERO_SELF_SIGNED_CERT</code><span><a class="mark" href="#all_errors_depth_zero_self_signed_cert" id="all_errors_depth_zero_self_signed_cert">#</a></span><a aria-hidden="true" class="legacy" id="errors_depth_zero_self_signed_cert"></a></h5>
<p>The passed certificate is self-signed and the same certificate cannot be found
in the list of trusted certificates.</p>
<p><a id="SELF_SIGNED_CERT_IN_CHAIN"></a></p>
<h5><code>SELF_SIGNED_CERT_IN_CHAIN</code><span><a class="mark" href="#all_errors_self_signed_cert_in_chain" id="all_errors_self_signed_cert_in_chain">#</a></span><a aria-hidden="true" class="legacy" id="errors_self_signed_cert_in_chain"></a></h5>
<p>The certificate’s issuer is not known. This is the case if the issuer is not
included in the trusted certificate list.</p>
<p><a id="CERT_CHAIN_TOO_LONG"></a></p>
<h5><code>CERT_CHAIN_TOO_LONG</code><span><a class="mark" href="#all_errors_cert_chain_too_long" id="all_errors_cert_chain_too_long">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_chain_too_long"></a></h5>
<p>The certificate chain length is greater than the maximum depth.</p>
<p><a id="UNABLE_TO_GET_CRL"></a></p>
<h5><code>UNABLE_TO_GET_CRL</code><span><a class="mark" href="#all_errors_unable_to_get_crl" id="all_errors_unable_to_get_crl">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_get_crl"></a></h5>
<p>The CRL reference by the certificate could not be found.</p>
<p><a id="UNABLE_TO_VERIFY_LEAF_SIGNATURE"></a></p>
<h5><code>UNABLE_TO_VERIFY_LEAF_SIGNATURE</code><span><a class="mark" href="#all_errors_unable_to_verify_leaf_signature" id="all_errors_unable_to_verify_leaf_signature">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_verify_leaf_signature"></a></h5>
<p>No signatures could be verified because the chain contains only one certificate
and it is not self signed.</p>
<p><a id="CERT_UNTRUSTED"></a></p>
<h5><code>CERT_UNTRUSTED</code><span><a class="mark" href="#all_errors_cert_untrusted" id="all_errors_cert_untrusted">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_untrusted"></a></h5>
<p>The root certificate authority (CA) is not marked as trusted for the specified
purpose.</p>
<p><a id="Basic Extension Errors"></a></p>
<h4>Basic Extension Errors<span><a class="mark" href="#all_errors_basic-extension-errors" id="all_errors_basic-extension-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_basic_extension_errors"></a></h4>
<p><a id="INVALID_CA"></a></p>
<h5><code>INVALID_CA</code><span><a class="mark" href="#all_errors_invalid_ca" id="all_errors_invalid_ca">#</a></span><a aria-hidden="true" class="legacy" id="errors_invalid_ca"></a></h5>
<p>A CA certificate is invalid. Either it is not a CA or its extensions are not
consistent with the supplied purpose.</p>
<p><a id="PATH_LENGTH_EXCEEDED"></a></p>
<h5><code>PATH_LENGTH_EXCEEDED</code><span><a class="mark" href="#all_errors_path_length_exceeded" id="all_errors_path_length_exceeded">#</a></span><a aria-hidden="true" class="legacy" id="errors_path_length_exceeded"></a></h5>
<p>The basicConstraints pathlength parameter has been exceeded.</p>
<p><a id="Name Related Errors"></a></p>
<h4>Name Related Errors<span><a class="mark" href="#all_errors_name-related-errors" id="all_errors_name-related-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_name_related_errors"></a></h4>
<p><a id="HOSTNAME_MISMATCH"></a></p>
<h5><code>HOSTNAME_MISMATCH</code><span><a class="mark" href="#all_errors_hostname_mismatch" id="all_errors_hostname_mismatch">#</a></span><a aria-hidden="true" class="legacy" id="errors_hostname_mismatch"></a></h5>
<p>Certificate does not match provided name.</p>
<p><a id="Usage and Policy Errors"></a></p>
<h4>Usage and Policy Errors<span><a class="mark" href="#all_errors_usage-and-policy-errors" id="all_errors_usage-and-policy-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_usage_and_policy_errors"></a></h4>
<p><a id="INVALID_PURPOSE"></a></p>
<h5><code>INVALID_PURPOSE</code><span><a class="mark" href="#all_errors_invalid_purpose" id="all_errors_invalid_purpose">#</a></span><a aria-hidden="true" class="legacy" id="errors_invalid_purpose"></a></h5>
<p>The supplied certificate cannot be used for the specified purpose.</p>
<p><a id="CERT_REJECTED"></a></p>
<h5><code>CERT_REJECTED</code><span><a class="mark" href="#all_errors_cert_rejected" id="all_errors_cert_rejected">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_rejected"></a></h5>
<p>The root CA is marked to reject the specified purpose.</p>
<p><a id="Formatting Errors"></a></p>
<h4>Formatting Errors<span><a class="mark" href="#all_errors_formatting-errors" id="all_errors_formatting-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_formatting_errors"></a></h4>
<p><a id="CERT_SIGNATURE_FAILURE"></a></p>
<h5><code>CERT_SIGNATURE_FAILURE</code><span><a class="mark" href="#all_errors_cert_signature_failure" id="all_errors_cert_signature_failure">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_signature_failure"></a></h5>
<p>The signature of the certificate is invalid.</p>
<p><a id="CRL_SIGNATURE_FAILURE"></a></p>
<h5><code>CRL_SIGNATURE_FAILURE</code><span><a class="mark" href="#all_errors_crl_signature_failure" id="all_errors_crl_signature_failure">#</a></span><a aria-hidden="true" class="legacy" id="errors_crl_signature_failure"></a></h5>
<p>The signature of the certificate revocation list (CRL) is invalid.</p>
<p><a id="ERROR_IN_CERT_NOT_BEFORE_FIELD"></a></p>
<h5><code>ERROR_IN_CERT_NOT_BEFORE_FIELD</code><span><a class="mark" href="#all_errors_error_in_cert_not_before_field" id="all_errors_error_in_cert_not_before_field">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_in_cert_not_before_field"></a></h5>
<p>The certificate notBefore field contains an invalid time.</p>
<p><a id="ERROR_IN_CERT_NOT_AFTER_FIELD"></a></p>
<h5><code>ERROR_IN_CERT_NOT_AFTER_FIELD</code><span><a class="mark" href="#all_errors_error_in_cert_not_after_field" id="all_errors_error_in_cert_not_after_field">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_in_cert_not_after_field"></a></h5>
<p>The certificate notAfter field contains an invalid time.</p>
<p><a id="ERROR_IN_CRL_LAST_UPDATE_FIELD"></a></p>
<h5><code>ERROR_IN_CRL_LAST_UPDATE_FIELD</code><span><a class="mark" href="#all_errors_error_in_crl_last_update_field" id="all_errors_error_in_crl_last_update_field">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_in_crl_last_update_field"></a></h5>
<p>The CRL lastUpdate field contains an invalid time.</p>
<p><a id="ERROR_IN_CRL_NEXT_UPDATE_FIELD"></a></p>
<h5><code>ERROR_IN_CRL_NEXT_UPDATE_FIELD</code><span><a class="mark" href="#all_errors_error_in_crl_next_update_field" id="all_errors_error_in_crl_next_update_field">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_in_crl_next_update_field"></a></h5>
<p>The CRL nextUpdate field contains an invalid time.</p>
<p><a id="UNABLE_TO_DECRYPT_CERT_SIGNATURE"></a></p>
<h5><code>UNABLE_TO_DECRYPT_CERT_SIGNATURE</code><span><a class="mark" href="#all_errors_unable_to_decrypt_cert_signature" id="all_errors_unable_to_decrypt_cert_signature">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_decrypt_cert_signature"></a></h5>
<p>The certificate signature could not be decrypted. This means that the actual
signature value could not be determined rather than it not matching the expected
value, this is only meaningful for RSA keys.</p>
<p><a id="UNABLE_TO_DECRYPT_CRL_SIGNATURE"></a></p>
<h5><code>UNABLE_TO_DECRYPT_CRL_SIGNATURE</code><span><a class="mark" href="#all_errors_unable_to_decrypt_crl_signature" id="all_errors_unable_to_decrypt_crl_signature">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_decrypt_crl_signature"></a></h5>
<p>The certificate revocation list (CRL) signature could not be decrypted: this
means that the actual signature value could not be determined rather than it not
matching the expected value.</p>
<p><a id="UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY"></a></p>
<h5><code>UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY</code><span><a class="mark" href="#all_errors_unable_to_decode_issuer_public_key" id="all_errors_unable_to_decode_issuer_public_key">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_decode_issuer_public_key"></a></h5>
<p>The public key in the certificate SubjectPublicKeyInfo could not be read.</p>
<p><a id="Other OpenSSL Errors"></a></p>
<h4>Other OpenSSL Errors<span><a class="mark" href="#all_errors_other-openssl-errors" id="all_errors_other-openssl-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_other_openssl_errors"></a></h4>
<p><a id="OUT_OF_MEM"></a></p>
<h5><code>OUT_OF_MEM</code><span><a class="mark" href="#all_errors_out_of_mem" id="all_errors_out_of_mem">#</a></span><a aria-hidden="true" class="legacy" id="errors_out_of_mem"></a></h5>
<p>An error occurred trying to allocate memory. This should never happen.</p></section>
</section>
<section><h2>Events<span><a class="mark" href="#all_events_events" id="all_events_events">#</a></span><a aria-hidden="true" class="legacy" id="events_events"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/events.js">lib/events.js</a></p>
<p>Much of the Node.js core API is built around an idiomatic asynchronous
event-driven architecture in which certain kinds of objects (called "emitters")
emit named events that cause <code>Function</code> objects ("listeners") to be called.</p>
<p>For instance: a <a href="#all_net_class-netserver"><code>net.Server</code></a> object emits an event each time a peer
connects to it; a <a href="#all_fs_class-fsreadstream"><code>fs.ReadStream</code></a> emits an event when the file is opened;
a <a href="stream.html">stream</a> emits an event whenever data is available to be read.</p>
<p>All objects that emit events are instances of the <code>EventEmitter</code> class. These
objects expose an <code>eventEmitter.on()</code> function that allows one or more
functions to be attached to named events emitted by the object. Typically,
event names are camel-cased strings but any valid JavaScript property key
can be used.</p>
<p>When the <code>EventEmitter</code> object emits an event, all of the functions attached
to that specific event are called <em>synchronously</em>. Any values returned by the
called listeners are <em>ignored</em> and discarded.</p>
<p>The following example shows a simple <code>EventEmitter</code> instance with a single
listener. The <code>eventEmitter.on()</code> method is used to register listeners, while
the <code>eventEmitter.emit()</code> method is used to trigger the event.</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'an event occurred!'</span>);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'an event occurred!'</span>);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>Passing arguments and <code>this</code> to listeners<span><a class="mark" href="#all_events_passing-arguments-and-this-to-listeners" id="all_events_passing-arguments-and-this-to-listeners">#</a></span><a aria-hidden="true" class="legacy" id="events_passing_arguments_and_this_to_listeners"></a></h3>
<p>The <code>eventEmitter.emit()</code> method allows an arbitrary set of arguments to be
passed to the listener functions. Keep in mind that when
an ordinary listener function is called, the standard <code>this</code> keyword
is intentionally set to reference the <code>EventEmitter</code> instance to which the
listener is attached.</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a, b, <span class="hljs-variable language_">this</span>, <span class="hljs-variable language_">this</span> === myEmitter);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// a b MyEmitter {</span>
<span class="hljs-comment">// _events: [Object: null prototype] { event: [Function (anonymous)] },</span>
<span class="hljs-comment">// _eventsCount: 1,</span>
<span class="hljs-comment">// _maxListeners: undefined,</span>
<span class="hljs-comment">// [Symbol(shapeMode)]: false,</span>
<span class="hljs-comment">// [Symbol(kCapture)]: false</span>
<span class="hljs-comment">// } true</span>
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a, b, <span class="hljs-variable language_">this</span>, <span class="hljs-variable language_">this</span> === myEmitter);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// a b MyEmitter {</span>
<span class="hljs-comment">// _events: [Object: null prototype] { event: [Function (anonymous)] },</span>
<span class="hljs-comment">// _eventsCount: 1,</span>
<span class="hljs-comment">// _maxListeners: undefined,</span>
<span class="hljs-comment">// [Symbol(shapeMode)]: false,</span>
<span class="hljs-comment">// [Symbol(kCapture)]: false</span>
<span class="hljs-comment">// } true</span>
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</code><button class="copy-button">copy</button></pre>
<p>It is possible to use ES6 Arrow Functions as listeners, however, when doing so,
the <code>this</code> keyword will no longer reference the <code>EventEmitter</code> instance:</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a, b, <span class="hljs-variable language_">this</span>);
<span class="hljs-comment">// Prints: a b undefined</span>
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a, b, <span class="hljs-variable language_">this</span>);
<span class="hljs-comment">// Prints: a b {}</span>
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Asynchronous vs. synchronous<span><a class="mark" href="#all_events_asynchronous-vs-synchronous" id="all_events_asynchronous-vs-synchronous">#</a></span><a aria-hidden="true" class="legacy" id="events_asynchronous_vs_synchronous"></a></h3>
<p>The <code>EventEmitter</code> calls all listeners synchronously in the order in which
they were registered. This ensures the proper sequencing of
events and helps avoid race conditions and logic errors. When appropriate,
listener functions can switch to an asynchronous mode of operation using
the <code>setImmediate()</code> or <code>process.nextTick()</code> methods:</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> {
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'this happens asynchronously'</span>);
});
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> {
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'this happens asynchronously'</span>);
});
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Handling events only once<span><a class="mark" href="#all_events_handling-events-only-once" id="all_events_handling-events-only-once">#</a></span><a aria-hidden="true" class="legacy" id="events_handling_events_only_once"></a></h3>
<p>When a listener is registered using the <code>eventEmitter.on()</code> method, that
listener is invoked <em>every time</em> the named event is emitted.</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-keyword">let</span> m = <span class="hljs-number">0</span>;
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(++m);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints: 1</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints: 2</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-keyword">let</span> m = <span class="hljs-number">0</span>;
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(++m);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints: 1</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints: 2</span></code><button class="copy-button">copy</button></pre>
<p>Using the <code>eventEmitter.once()</code> method, it is possible to register a listener
that is called at most once for a particular event. Once the event is emitted,
the listener is unregistered and <em>then</em> called.</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-keyword">let</span> m = <span class="hljs-number">0</span>;
myEmitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(++m);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints: 1</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Ignored</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-keyword">let</span> m = <span class="hljs-number">0</span>;
myEmitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(++m);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints: 1</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Ignored</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Error events<span><a class="mark" href="#all_events_error-events" id="all_events_error-events">#</a></span><a aria-hidden="true" class="legacy" id="events_error_events"></a></h3>
<p>When an error occurs within an <code>EventEmitter</code> instance, the typical action is
for an <code>'error'</code> event to be emitted. These are treated as special cases
within Node.js.</p>
<p>If an <code>EventEmitter</code> does <em>not</em> have at least one listener registered for the
<code>'error'</code> event, and an <code>'error'</code> event is emitted, the error is thrown, a
stack trace is printed, and the Node.js process exits.</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>));
<span class="hljs-comment">// Throws and crashes Node.js</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>));
<span class="hljs-comment">// Throws and crashes Node.js</span></code><button class="copy-button">copy</button></pre>
<p>To guard against crashing the Node.js process the <a href="domain.html"><code>domain</code></a> module can be
used. (Note, however, that the <code>node:domain</code> module is deprecated.)</p>
<p>As a best practice, listeners should always be added for the <code>'error'</code> events.</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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>(<span class="hljs-string">'whoops! there was an error'</span>);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>));
<span class="hljs-comment">// Prints: whoops! there was an error</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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>(<span class="hljs-string">'whoops! there was an error'</span>);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>));
<span class="hljs-comment">// Prints: whoops! there was an error</span></code><button class="copy-button">copy</button></pre>
<p>It is possible to monitor <code>'error'</code> events without consuming the emitted error
by installing a listener using the symbol <code>events.errorMonitor</code>.</p>
<pre class="with-62-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_">EventEmitter</span>, errorMonitor } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(errorMonitor, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-title class_">MyMonitoringTool</span>.<span class="hljs-title function_">log</span>(err);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>));
<span class="hljs-comment">// Still throws and crashes Node.js</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, errorMonitor } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(errorMonitor, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-title class_">MyMonitoringTool</span>.<span class="hljs-title function_">log</span>(err);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>));
<span class="hljs-comment">// Still throws and crashes Node.js</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Capture rejections of promises<span><a class="mark" href="#all_events_capture-rejections-of-promises" id="all_events_capture-rejections-of-promises">#</a></span><a aria-hidden="true" class="legacy" id="events_capture_rejections_of_promises"></a></h3>
<p>Using <code>async</code> functions with event handlers is problematic, because it
can lead to an unhandled rejection in case of a thrown exception:</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-title function_">async</span> (value) => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-title function_">async</span> (value) => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>The <code>captureRejections</code> option in the <code>EventEmitter</code> constructor or the global
setting change this behavior, installing a <code>.then(undefined, handler)</code>
handler on the <code>Promise</code>. This handler routes the exception
asynchronously to the <a href="#all_events_emittersymbolfornodejsrejectionerr-eventname-args"><code>Symbol.for('nodejs.rejection')</code></a> method
if there is one, or to <a href="#all_events_error-events"><code>'error'</code></a> event handler if there is none.</p>
<pre class="with-58-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> });
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-title function_">async</span> (value) => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);
<span class="hljs-keyword">const</span> ee2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> });
ee2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-title function_">async</span> (value) => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});
ee2[<span class="hljs-title class_">Symbol</span>.<span class="hljs-title function_">for</span>(<span class="hljs-string">'nodejs.rejection'</span>)] = <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> });
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-title function_">async</span> (value) => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);
<span class="hljs-keyword">const</span> ee2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> });
ee2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-title function_">async</span> (value) => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});
ee2[<span class="hljs-title class_">Symbol</span>.<span class="hljs-title function_">for</span>(<span class="hljs-string">'nodejs.rejection'</span>)] = <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>;</code><button class="copy-button">copy</button></pre>
<p>Setting <code>events.captureRejections = true</code> will change the default for all
new instances of <code>EventEmitter</code>.</p>
<pre class="with-43-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-title class_">EventEmitter</span>.<span class="hljs-property">captureRejections</span> = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-title function_">async</span> (value) => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
events.<span class="hljs-property">captureRejections</span> = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> events.<span class="hljs-title class_">EventEmitter</span>();
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-title function_">async</span> (value) => {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
<p>The <code>'error'</code> events that are generated by the <code>captureRejections</code> behavior
do not have a catch handler to avoid infinite error loops: the
recommendation is to <strong>not use <code>async</code> functions as <code>'error'</code> event handlers</strong>.</p>
</section><section><h3>Class: <code>EventEmitter</code><span><a class="mark" href="#all_events_class-eventemitter" id="all_events_class-eventemitter">#</a></span><a aria-hidden="true" class="legacy" id="events_class_eventemitter"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.4.0, v12.16.0</td>
<td><p>Added captureRejections option.</p></td></tr>
<tr><td>v0.1.26</td>
<td><p><span>Added in: v0.1.26</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>EventEmitter</code> class is defined and exposed by the <code>node:events</code> module:</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);</code><button class="copy-button">copy</button></pre>
<p>All <code>EventEmitter</code>s emit the event <code>'newListener'</code> when new listeners are
added and <code>'removeListener'</code> when existing listeners are removed.</p>
<p>It supports the following option:</p>
<ul>
<li><code>captureRejections</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> It enables
<a href="#all_events_capture-rejections-of-promises">automatic capturing of promise rejection</a>.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
<h4>Event: <code>'newListener'</code><span><a class="mark" href="#all_events_event-newlistener" id="all_events_event-newlistener">#</a></span><a aria-hidden="true" class="legacy" id="events_event_newlistener"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.26</span>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a> The name of the event being listened for</li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The event handler function</li>
</ul>
<p>The <code>EventEmitter</code> instance will emit its own <code>'newListener'</code> event <em>before</em>
a listener is added to its internal array of listeners.</p>
<p>Listeners registered for the <code>'newListener'</code> event are passed the event
name and a reference to the listener being added.</p>
<p>The fact that the event is triggered before adding the listener has a subtle
but important side effect: any <em>additional</em> listeners registered to the same
<code>name</code> <em>within</em> the <code>'newListener'</code> callback are inserted <em>before</em> the
listener that is in the process of being added.</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-comment">// Only do this once so we don't loop forever</span>
myEmitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'newListener'</span>, <span class="hljs-function">(<span class="hljs-params">event, listener</span>) =></span> {
<span class="hljs-keyword">if</span> (event === <span class="hljs-string">'event'</span>) {
<span class="hljs-comment">// Insert a new listener in front</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'B'</span>);
});
}
});
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'A'</span>);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// B</span>
<span class="hljs-comment">// A</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-comment">// Only do this once so we don't loop forever</span>
myEmitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'newListener'</span>, <span class="hljs-function">(<span class="hljs-params">event, listener</span>) =></span> {
<span class="hljs-keyword">if</span> (event === <span class="hljs-string">'event'</span>) {
<span class="hljs-comment">// Insert a new listener in front</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'B'</span>);
});
}
});
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'A'</span>);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// B</span>
<span class="hljs-comment">// A</span></code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'removeListener'</code><span><a class="mark" href="#all_events_event-removelistener" id="all_events_event-removelistener">#</a></span><a aria-hidden="true" class="legacy" id="events_event_removelistener"></a></h4>
<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, v4.7.0</td>
<td><p>For listeners attached using <code>.once()</code>, the <code>listener</code> argument now yields the original listener function.</p></td></tr>
<tr><td>v0.9.3</td>
<td><p><span>Added in: v0.9.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a> The event name</li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The event handler function</li>
</ul>
<p>The <code>'removeListener'</code> event is emitted <em>after</em> the <code>listener</code> is removed.</p>
<h4><code>emitter.addListener(eventName, listener)</code><span><a class="mark" href="#all_events_emitteraddlistenereventname-listener" id="all_events_emitteraddlistenereventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_addlistener_eventname_listener"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.26</span>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a></li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>Alias for <code>emitter.on(eventName, listener)</code>.</p>
<h4><code>emitter.emit(eventName[, ...args])</code><span><a class="mark" href="#all_events_emitteremiteventname-args" id="all_events_emitteremiteventname-args">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_emit_eventname_args"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.26</span>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a></li>
<li><code>...args</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Synchronously calls each of the listeners registered for the event named
<code>eventName</code>, in the order they were registered, passing the supplied arguments
to each.</p>
<p>Returns <code>true</code> if the event had listeners, <code>false</code> otherwise.</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-comment">// First listener</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">firstListener</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Helloooo! first listener'</span>);
});
<span class="hljs-comment">// Second listener</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">secondListener</span>(<span class="hljs-params">arg1, arg2</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`event with parameters <span class="hljs-subst">${arg1}</span>, <span class="hljs-subst">${arg2}</span> in second listener`</span>);
});
<span class="hljs-comment">// Third listener</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">thirdListener</span>(<span class="hljs-params">...args</span>) {
<span class="hljs-keyword">const</span> parameters = args.<span class="hljs-title function_">join</span>(<span class="hljs-string">', '</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`event with parameters <span class="hljs-subst">${parameters}</span> in third listener`</span>);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myEmitter.<span class="hljs-title function_">listeners</span>(<span class="hljs-string">'event'</span>));
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</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-number">5</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// [Function: firstListener],</span>
<span class="hljs-comment">// [Function: secondListener],</span>
<span class="hljs-comment">// [Function: thirdListener]</span>
<span class="hljs-comment">// ]</span>
<span class="hljs-comment">// Helloooo! first listener</span>
<span class="hljs-comment">// event with parameters 1, 2 in second listener</span>
<span class="hljs-comment">// event with parameters 1, 2, 3, 4, 5 in third listener</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-comment">// First listener</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">firstListener</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Helloooo! first listener'</span>);
});
<span class="hljs-comment">// Second listener</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">secondListener</span>(<span class="hljs-params">arg1, arg2</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`event with parameters <span class="hljs-subst">${arg1}</span>, <span class="hljs-subst">${arg2}</span> in second listener`</span>);
});
<span class="hljs-comment">// Third listener</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">thirdListener</span>(<span class="hljs-params">...args</span>) {
<span class="hljs-keyword">const</span> parameters = args.<span class="hljs-title function_">join</span>(<span class="hljs-string">', '</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`event with parameters <span class="hljs-subst">${parameters}</span> in third listener`</span>);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myEmitter.<span class="hljs-title function_">listeners</span>(<span class="hljs-string">'event'</span>));
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</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-number">5</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// [Function: firstListener],</span>
<span class="hljs-comment">// [Function: secondListener],</span>
<span class="hljs-comment">// [Function: thirdListener]</span>
<span class="hljs-comment">// ]</span>
<span class="hljs-comment">// Helloooo! first listener</span>
<span class="hljs-comment">// event with parameters 1, 2 in second listener</span>
<span class="hljs-comment">// event with parameters 1, 2, 3, 4, 5 in third listener</span></code><button class="copy-button">copy</button></pre>
<h4><code>emitter.eventNames()</code><span><a class="mark" href="#all_events_emittereventnames" id="all_events_emittereventnames">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_eventnames"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>Returns an array listing the events for which the emitter has registered
listeners. The values in the array are strings or <code>Symbol</code>s.</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {});
myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'bar'</span>, <span class="hljs-function">() =></span> {});
<span class="hljs-keyword">const</span> sym = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'symbol'</span>);
myEE.<span class="hljs-title function_">on</span>(sym, <span class="hljs-function">() =></span> {});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myEE.<span class="hljs-title function_">eventNames</span>());
<span class="hljs-comment">// Prints: [ 'foo', 'bar', Symbol(symbol) ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {});
myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'bar'</span>, <span class="hljs-function">() =></span> {});
<span class="hljs-keyword">const</span> sym = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'symbol'</span>);
myEE.<span class="hljs-title function_">on</span>(sym, <span class="hljs-function">() =></span> {});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myEE.<span class="hljs-title function_">eventNames</span>());
<span class="hljs-comment">// Prints: [ 'foo', 'bar', Symbol(symbol) ]</span></code><button class="copy-button">copy</button></pre>
<h4><code>emitter.getMaxListeners()</code><span><a class="mark" href="#all_events_emittergetmaxlisteners" id="all_events_emittergetmaxlisteners">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_getmaxlisteners"></a></h4>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div>
<ul>
<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 current max listener value for the <code>EventEmitter</code> which is either
set by <a href="#all_events_emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a> or defaults to
<a href="#all_events_eventsdefaultmaxlisteners"><code>events.defaultMaxListeners</code></a>.</p>
<h4><code>emitter.listenerCount(eventName[, listener])</code><span><a class="mark" href="#all_events_emitterlistenercounteventname-listener" id="all_events_emitterlistenercounteventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_listenercount_eventname_listener"></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.8.0</td>
<td><p>Added the <code>listener</code> argument.</p></td></tr>
<tr><td>v3.2.0</td>
<td><p><span>Added in: v3.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a> The name of the event being listened for</li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The event handler function</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 number of listeners listening for the event named <code>eventName</code>.
If <code>listener</code> is provided, it will return how many times the listener is found
in the list of the listeners of the event.</p>
<h4><code>emitter.listeners(eventName)</code><span><a class="mark" href="#all_events_emitterlistenerseventname" id="all_events_emitterlistenerseventname">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_listeners_eventname"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>For listeners attached using <code>.once()</code> this returns the original listeners instead of wrapper functions now.</p></td></tr>
<tr><td>v0.1.26</td>
<td><p><span>Added in: v0.1.26</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a></li>
</ul>
<p>Returns a copy of the array of listeners for the event named <code>eventName</code>.</p>
<pre><code class="language-js">server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'someone connected!'</span>);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-title function_">inspect</span>(server.<span class="hljs-title function_">listeners</span>(<span class="hljs-string">'connection'</span>)));
<span class="hljs-comment">// Prints: [ [Function] ]</span></code> <button class="copy-button">copy</button></pre>
<h4><code>emitter.off(eventName, listener)</code><span><a class="mark" href="#all_events_emitteroffeventname-listener" id="all_events_emitteroffeventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_off_eventname_listener"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a></li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>Alias for <a href="#all_events_emitterremovelistenereventname-listener"><code>emitter.removeListener()</code></a>.</p>
<h4><code>emitter.on(eventName, listener)</code><span><a class="mark" href="#all_events_emitteroneventname-listener" id="all_events_emitteroneventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_on_eventname_listener"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.101</span>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a> The name of the event.</li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li>
<li>Returns: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>Adds the <code>listener</code> function to the end of the listeners array for the
event named <code>eventName</code>. No checks are made to see if the <code>listener</code> has
already been added. Multiple calls passing the same combination of <code>eventName</code>
and <code>listener</code> will result in the <code>listener</code> being added, and called, multiple
times.</p>
<pre><code class="language-js">server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'someone connected!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<p>By default, event listeners are invoked in the order they are added. The
<code>emitter.prependListener()</code> method can be used as an alternative to add the
event listener to the beginning of the listeners array.</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a'</span>));
myEE.<span class="hljs-title function_">prependListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b'</span>));
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// b</span>
<span class="hljs-comment">// a</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a'</span>));
myEE.<span class="hljs-title function_">prependListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b'</span>));
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// b</span>
<span class="hljs-comment">// a</span></code><button class="copy-button">copy</button></pre>
<h4><code>emitter.once(eventName, listener)</code><span><a class="mark" href="#all_events_emitteronceeventname-listener" id="all_events_emitteronceeventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_once_eventname_listener"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a> The name of the event.</li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li>
<li>Returns: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>Adds a <strong>one-time</strong> <code>listener</code> function for the event named <code>eventName</code>. The
next time <code>eventName</code> is triggered, this listener is removed and then invoked.</p>
<pre><code class="language-js">server.<span class="hljs-title function_">once</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Ah, we have our first user!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<p>By default, event listeners are invoked in the order they are added. The
<code>emitter.prependOnceListener()</code> method can be used as an alternative to add the
event listener to the beginning of the listeners array.</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEE.<span class="hljs-title function_">once</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a'</span>));
myEE.<span class="hljs-title function_">prependOnceListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b'</span>));
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// b</span>
<span class="hljs-comment">// a</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEE.<span class="hljs-title function_">once</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a'</span>));
myEE.<span class="hljs-title function_">prependOnceListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b'</span>));
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// b</span>
<span class="hljs-comment">// a</span></code><button class="copy-button">copy</button></pre>
<h4><code>emitter.prependListener(eventName, listener)</code><span><a class="mark" href="#all_events_emitterprependlistenereventname-listener" id="all_events_emitterprependlistenereventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_prependlistener_eventname_listener"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a> The name of the event.</li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li>
<li>Returns: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>Adds the <code>listener</code> function to the <em>beginning</em> of the listeners array for the
event named <code>eventName</code>. No checks are made to see if the <code>listener</code> has
already been added. Multiple calls passing the same combination of <code>eventName</code>
and <code>listener</code> will result in the <code>listener</code> being added, and called, multiple
times.</p>
<pre><code class="language-js">server.<span class="hljs-title function_">prependListener</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'someone connected!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<h4><code>emitter.prependOnceListener(eventName, listener)</code><span><a class="mark" href="#all_events_emitterprependoncelistenereventname-listener" id="all_events_emitterprependoncelistenereventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_prependoncelistener_eventname_listener"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a> The name of the event.</li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li>
<li>Returns: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>Adds a <strong>one-time</strong> <code>listener</code> function for the event named <code>eventName</code> to the
<em>beginning</em> of the listeners array. The next time <code>eventName</code> is triggered, this
listener is removed, and then invoked.</p>
<pre><code class="language-js">server.<span class="hljs-title function_">prependOnceListener</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Ah, we have our first user!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<h4><code>emitter.removeAllListeners([eventName])</code><span><a class="mark" href="#all_events_emitterremovealllistenerseventname" id="all_events_emitterremovealllistenerseventname">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_removealllisteners_eventname"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.26</span>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a></li>
<li>Returns: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>Removes all listeners, or those of the specified <code>eventName</code>.</p>
<p>It is bad practice to remove listeners added elsewhere in the code,
particularly when the <code>EventEmitter</code> instance was created by some other
component or module (e.g. sockets or file streams).</p>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<h4><code>emitter.removeListener(eventName, listener)</code><span><a class="mark" href="#all_events_emitterremovelistenereventname-listener" id="all_events_emitterremovelistenereventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_removelistener_eventname_listener"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.26</span>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a></li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>Removes the specified <code>listener</code> from the listener array for the event named
<code>eventName</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title function_">callback</span> = (<span class="hljs-params">stream</span>) => {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'someone connected!'</span>);
};
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, callback);
<span class="hljs-comment">// ...</span>
server.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'connection'</span>, callback);</code> <button class="copy-button">copy</button></pre>
<p><code>removeListener()</code> will remove, at most, one instance of a listener from the
listener array. If any single listener has been added multiple times to the
listener array for the specified <code>eventName</code>, then <code>removeListener()</code> must be
called multiple times to remove each instance.</p>
<p>Once an event is emitted, all listeners attached to it at the
time of emitting are called in order. This implies that any
<code>removeListener()</code> or <code>removeAllListeners()</code> calls <em>after</em> emitting and
<em>before</em> the last listener finishes execution will not remove them from
<code>emit()</code> in progress. Subsequent events behave as expected.</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-keyword">const</span> <span class="hljs-title function_">callbackA</span> = (<span class="hljs-params"></span>) => {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'A'</span>);
myEmitter.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'event'</span>, callbackB);
};
<span class="hljs-keyword">const</span> <span class="hljs-title function_">callbackB</span> = (<span class="hljs-params"></span>) => {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'B'</span>);
};
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, callbackA);
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, callbackB);
<span class="hljs-comment">// callbackA removes listener callbackB but it will still be called.</span>
<span class="hljs-comment">// Internal listener array at time of emit [callbackA, callbackB]</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// A</span>
<span class="hljs-comment">// B</span>
<span class="hljs-comment">// callbackB is now removed.</span>
<span class="hljs-comment">// Internal listener array [callbackA]</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// A</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-keyword">const</span> <span class="hljs-title function_">callbackA</span> = (<span class="hljs-params"></span>) => {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'A'</span>);
myEmitter.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'event'</span>, callbackB);
};
<span class="hljs-keyword">const</span> <span class="hljs-title function_">callbackB</span> = (<span class="hljs-params"></span>) => {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'B'</span>);
};
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, callbackA);
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, callbackB);
<span class="hljs-comment">// callbackA removes listener callbackB but it will still be called.</span>
<span class="hljs-comment">// Internal listener array at time of emit [callbackA, callbackB]</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// A</span>
<span class="hljs-comment">// B</span>
<span class="hljs-comment">// callbackB is now removed.</span>
<span class="hljs-comment">// Internal listener array [callbackA]</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// A</span></code><button class="copy-button">copy</button></pre>
<p>Because listeners are managed using an internal array, calling this will
change the position indexes of any listener registered <em>after</em> the listener
being removed. This will not impact the order in which listeners are called,
but it means that any copies of the listener array as returned by
the <code>emitter.listeners()</code> method will need to be recreated.</p>
<p>When a single function has been added as a handler multiple times for a single
event (as in the example below), <code>removeListener()</code> will remove the most
recently added instance. In the example the <code>once('ping')</code>
listener is removed:</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">pong</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'pong'</span>);
}
ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'ping'</span>, pong);
ee.<span class="hljs-title function_">once</span>(<span class="hljs-string">'ping'</span>, pong);
ee.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'ping'</span>, pong);
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ping'</span>);
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ping'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">pong</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'pong'</span>);
}
ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'ping'</span>, pong);
ee.<span class="hljs-title function_">once</span>(<span class="hljs-string">'ping'</span>, pong);
ee.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'ping'</span>, pong);
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ping'</span>);
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ping'</span>);</code><button class="copy-button">copy</button></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<h4><code>emitter.setMaxListeners(n)</code><span><a class="mark" href="#all_events_emittersetmaxlistenersn" id="all_events_emittersetmaxlistenersn">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_setmaxlisteners_n"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.5</span>
</div>
<ul>
<li><code>n</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li>Returns: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>By default <code>EventEmitter</code>s will print a warning if more than <code>10</code> listeners are
added for a particular event. This is a useful default that helps finding
memory leaks. The <code>emitter.setMaxListeners()</code> method allows the limit to be
modified for this specific <code>EventEmitter</code> instance. The value can be set to
<code>Infinity</code> (or <code>0</code>) to indicate an unlimited number of listeners.</p>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<h4><code>emitter.rawListeners(eventName)</code><span><a class="mark" href="#all_events_emitterrawlistenerseventname" id="all_events_emitterrawlistenerseventname">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_rawlisteners_eventname"></a></h4>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a></li>
</ul>
<p>Returns a copy of the array of listeners for the event named <code>eventName</code>,
including any wrappers (such as those created by <code>.once()</code>).</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
emitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'log'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'log once'</span>));
<span class="hljs-comment">// Returns a new Array with a function `onceWrapper` which has a property</span>
<span class="hljs-comment">// `listener` which contains the original listener bound above</span>
<span class="hljs-keyword">const</span> listeners = emitter.<span class="hljs-title function_">rawListeners</span>(<span class="hljs-string">'log'</span>);
<span class="hljs-keyword">const</span> logFnWrapper = listeners[<span class="hljs-number">0</span>];
<span class="hljs-comment">// Logs "log once" to the console and does not unbind the `once` event</span>
logFnWrapper.<span class="hljs-title function_">listener</span>();
<span class="hljs-comment">// Logs "log once" to the console and removes the listener</span>
<span class="hljs-title function_">logFnWrapper</span>();
emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'log'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'log persistently'</span>));
<span class="hljs-comment">// Will return a new Array with a single function bound by `.on()` above</span>
<span class="hljs-keyword">const</span> newListeners = emitter.<span class="hljs-title function_">rawListeners</span>(<span class="hljs-string">'log'</span>);
<span class="hljs-comment">// Logs "log persistently" twice</span>
newListeners[<span class="hljs-number">0</span>]();
emitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'log'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
emitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'log'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'log once'</span>));
<span class="hljs-comment">// Returns a new Array with a function `onceWrapper` which has a property</span>
<span class="hljs-comment">// `listener` which contains the original listener bound above</span>
<span class="hljs-keyword">const</span> listeners = emitter.<span class="hljs-title function_">rawListeners</span>(<span class="hljs-string">'log'</span>);
<span class="hljs-keyword">const</span> logFnWrapper = listeners[<span class="hljs-number">0</span>];
<span class="hljs-comment">// Logs "log once" to the console and does not unbind the `once` event</span>
logFnWrapper.<span class="hljs-title function_">listener</span>();
<span class="hljs-comment">// Logs "log once" to the console and removes the listener</span>
<span class="hljs-title function_">logFnWrapper</span>();
emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'log'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'log persistently'</span>));
<span class="hljs-comment">// Will return a new Array with a single function bound by `.on()` above</span>
<span class="hljs-keyword">const</span> newListeners = emitter.<span class="hljs-title function_">rawListeners</span>(<span class="hljs-string">'log'</span>);
<span class="hljs-comment">// Logs "log persistently" twice</span>
newListeners[<span class="hljs-number">0</span>]();
emitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'log'</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])</code><span><a class="mark" href="#all_events_emittersymbolfornodejsrejectionerr-eventname-args" id="all_events_emittersymbolfornodejsrejectionerr-eventname-args">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_symbol_for_nodejs_rejection_err_eventname_args"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.4.0, v16.14.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v13.4.0, v12.16.0</td>
<td><p><span>Added in: v13.4.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>err</code> Error</li>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>The <code>Symbol.for('nodejs.rejection')</code> method is called in case a
promise rejection happens when emitting an event and
<a href="#all_events_capture-rejections-of-promises"><code>captureRejections</code></a> is enabled on the emitter.
It is possible to use <a href="#all_events_eventscapturerejectionsymbol"><code>events.captureRejectionSymbol</code></a> in
place of <code>Symbol.for('nodejs.rejection')</code>.</p>
<pre class="with-72-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_">EventEmitter</span>, captureRejectionSymbol } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">super</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> });
}
[captureRejectionSymbol](err, event, ...args) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'rejection happened for'</span>, event, <span class="hljs-string">'with'</span>, err, ...args);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err);
}
<span class="hljs-title function_">destroy</span>(<span class="hljs-params">err</span>) {
<span class="hljs-comment">// Tear the resource down here.</span>
}
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, captureRejectionSymbol } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">super</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> });
}
[captureRejectionSymbol](err, event, ...args) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'rejection happened for'</span>, event, <span class="hljs-string">'with'</span>, err, ...args);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err);
}
<span class="hljs-title function_">destroy</span>(<span class="hljs-params">err</span>) {
<span class="hljs-comment">// Tear the resource down here.</span>
}
}</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.defaultMaxListeners</code><span><a class="mark" href="#all_events_eventsdefaultmaxlisteners" id="all_events_eventsdefaultmaxlisteners">#</a></span><a aria-hidden="true" class="legacy" id="events_events_defaultmaxlisteners"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div>
<p>By default, a maximum of <code>10</code> listeners can be registered for any single
event. This limit can be changed for individual <code>EventEmitter</code> instances
using the <a href="#all_events_emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a> method. To change the default
for <em>all</em> <code>EventEmitter</code> instances, the <code>events.defaultMaxListeners</code>
property can be used. If this value is not a positive number, a <code>RangeError</code>
is thrown.</p>
<p>Take caution when setting the <code>events.defaultMaxListeners</code> because the
change affects <em>all</em> <code>EventEmitter</code> instances, including those created before
the change is made. However, calling <a href="#all_events_emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a> still has
precedence over <code>events.defaultMaxListeners</code>.</p>
<p>This is not a hard limit. The <code>EventEmitter</code> instance will allow
more listeners to be added but will output a trace warning to stderr indicating
that a "possible EventEmitter memory leak" has been detected. For any single
<code>EventEmitter</code>, the <code>emitter.getMaxListeners()</code> and <code>emitter.setMaxListeners()</code>
methods can be used to temporarily avoid this warning:</p>
<pre class="with-44-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_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
emitter.<span class="hljs-title function_">setMaxListeners</span>(emitter.<span class="hljs-title function_">getMaxListeners</span>() + <span class="hljs-number">1</span>);
emitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// do stuff</span>
emitter.<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">max</span>(emitter.<span class="hljs-title function_">getMaxListeners</span>() - <span class="hljs-number">1</span>, <span class="hljs-number">0</span>));
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
emitter.<span class="hljs-title function_">setMaxListeners</span>(emitter.<span class="hljs-title function_">getMaxListeners</span>() + <span class="hljs-number">1</span>);
emitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// do stuff</span>
emitter.<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">max</span>(emitter.<span class="hljs-title function_">getMaxListeners</span>() - <span class="hljs-number">1</span>, <span class="hljs-number">0</span>));
});</code><button class="copy-button">copy</button></pre>
<p>The <a href="#all_cli_--trace-warnings"><code>--trace-warnings</code></a> command-line flag can be used to display the
stack trace for such warnings.</p>
<p>The emitted warning can be inspected with <a href="#all_process_event-warning"><code>process.on('warning')</code></a> and will
have the additional <code>emitter</code>, <code>type</code>, and <code>count</code> properties, referring to
the event emitter instance, the event's name and the number of attached
listeners, respectively.
Its <code>name</code> property is set to <code>'MaxListenersExceededWarning'</code>.</p>
</section><section><h3><code>events.errorMonitor</code><span><a class="mark" href="#all_events_eventserrormonitor" id="all_events_eventserrormonitor">#</a></span><a aria-hidden="true" class="legacy" id="events_events_errormonitor"></a></h3>
<div class="api_metadata">
<span>Added in: v13.6.0, v12.17.0</span>
</div>
<p>This symbol shall be used to install a listener for only monitoring <code>'error'</code>
events. Listeners installed using this symbol are called before the regular
<code>'error'</code> listeners are called.</p>
<p>Installing a listener using this symbol does not change the behavior once an
<code>'error'</code> event is emitted. Therefore, the process will still crash if no
regular <code>'error'</code> listener is installed.</p>
</section><section><h3><code>events.getEventListeners(emitterOrTarget, eventName)</code><span><a class="mark" href="#all_events_eventsgeteventlistenersemitterortarget-eventname" id="all_events_eventsgeteventlistenersemitterortarget-eventname">#</a></span><a aria-hidden="true" class="legacy" id="events_events_geteventlisteners_emitterortarget_eventname"></a></h3>
<div class="api_metadata">
<span>Added in: v15.2.0, v14.17.0</span>
</div>
<ul>
<li><code>emitterOrTarget</code> <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a> | <a href="#all_events_class-eventtarget" class="type"><EventTarget></a></li>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a></li>
</ul>
<p>Returns a copy of the array of listeners for the event named <code>eventName</code>.</p>
<p>For <code>EventEmitter</code>s this behaves exactly the same as calling <code>.listeners</code> on
the emitter.</p>
<p>For <code>EventTarget</code>s this is the only way to get the event listeners for the
event target. This is useful for debugging and diagnostic purposes.</p>
<pre class="with-67-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> { getEventListeners, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
{
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-keyword">const</span> <span class="hljs-title function_">listener</span> = (<span class="hljs-params"></span>) => <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Events are fun'</span>);
ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, listener);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEventListeners</span>(ee, <span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// [ [Function: listener] ]</span>
}
{
<span class="hljs-keyword">const</span> et = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
<span class="hljs-keyword">const</span> <span class="hljs-title function_">listener</span> = (<span class="hljs-params"></span>) => <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Events are fun'</span>);
et.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, listener);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEventListeners</span>(et, <span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// [ [Function: listener] ]</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { getEventListeners, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
{
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-keyword">const</span> <span class="hljs-title function_">listener</span> = (<span class="hljs-params"></span>) => <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Events are fun'</span>);
ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, listener);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEventListeners</span>(ee, <span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// [ [Function: listener] ]</span>
}
{
<span class="hljs-keyword">const</span> et = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
<span class="hljs-keyword">const</span> <span class="hljs-title function_">listener</span> = (<span class="hljs-params"></span>) => <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Events are fun'</span>);
et.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, listener);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEventListeners</span>(et, <span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// [ [Function: listener] ]</span>
}</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.getMaxListeners(emitterOrTarget)</code><span><a class="mark" href="#all_events_eventsgetmaxlistenersemitterortarget" id="all_events_eventsgetmaxlistenersemitterortarget">#</a></span><a aria-hidden="true" class="legacy" id="events_events_getmaxlisteners_emitterortarget"></a></h3>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<ul>
<li><code>emitterOrTarget</code> <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a> | <a href="#all_events_class-eventtarget" class="type"><EventTarget></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>
<p>Returns the currently set max amount of listeners.</p>
<p>For <code>EventEmitter</code>s this behaves exactly the same as calling <code>.getMaxListeners</code> on
the emitter.</p>
<p>For <code>EventTarget</code>s this is the only way to get the max event listeners for the
event target. If the number of event handlers on a single EventTarget exceeds
the max set, the EventTarget will print a warning.</p>
<pre class="with-82-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> { getMaxListeners, setMaxListeners, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
{
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(ee)); <span class="hljs-comment">// 10</span>
<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">11</span>, ee);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(ee)); <span class="hljs-comment">// 11</span>
}
{
<span class="hljs-keyword">const</span> et = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(et)); <span class="hljs-comment">// 10</span>
<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">11</span>, et);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(et)); <span class="hljs-comment">// 11</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { getMaxListeners, setMaxListeners, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
{
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(ee)); <span class="hljs-comment">// 10</span>
<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">11</span>, ee);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(ee)); <span class="hljs-comment">// 11</span>
}
{
<span class="hljs-keyword">const</span> et = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(et)); <span class="hljs-comment">// 10</span>
<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">11</span>, et);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(et)); <span class="hljs-comment">// 11</span>
}</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.once(emitter, name[, options])</code><span><a class="mark" href="#all_events_eventsonceemitter-name-options" id="all_events_eventsonceemitter-name-options">#</a></span><a aria-hidden="true" class="legacy" id="events_events_once_emitter_name_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>signal</code> option is supported now.</p></td></tr>
<tr><td>v11.13.0, v10.16.0</td>
<td><p><span>Added in: v11.13.0, v10.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>emitter</code> <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
<li><code>name</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#Symbol_type" class="type"><symbol></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="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Can be used to cancel waiting for the event.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Creates a <code>Promise</code> that is fulfilled when the <code>EventEmitter</code> emits the given
event or that is rejected if the <code>EventEmitter</code> emits <code>'error'</code> while waiting.
The <code>Promise</code> will resolve with an array of all the arguments emitted to the
given event.</p>
<p>This method is intentionally generic and works with the web platform
<a href="https://dom.spec.whatwg.org/#interface-eventtarget">EventTarget</a> interface, which has no special
<code>'error'</code> event semantics and does not listen to the <code>'error'</code> event.</p>
<pre class="with-54-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> { once, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'myevent'</span>, <span class="hljs-number">42</span>);
});
<span class="hljs-keyword">const</span> [value] = <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'myevent'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);
<span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err);
});
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'myevent'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'error happened'</span>, err);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { once, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</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> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'myevent'</span>, <span class="hljs-number">42</span>);
});
<span class="hljs-keyword">const</span> [value] = <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'myevent'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);
<span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err);
});
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'myevent'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'error happened'</span>, err);
}
}
<span class="hljs-title function_">run</span>();</code><button class="copy-button">copy</button></pre>
<p>The special handling of the <code>'error'</code> event is only used when <code>events.once()</code>
is used to wait for another event. If <code>events.once()</code> is used to wait for the
'<code>error'</code> event itself, then it is treated as any other kind of event without
special handling:</p>
<pre class="with-54-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_">EventEmitter</span>, once } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'error'</span>)
.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">[err]</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'ok'</span>, err.<span class="hljs-property">message</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>(<span class="hljs-string">'error'</span>, err.<span class="hljs-property">message</span>));
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'boom'</span>));
<span class="hljs-comment">// Prints: ok boom</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'error'</span>)
.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">[err]</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'ok'</span>, err.<span class="hljs-property">message</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>(<span class="hljs-string">'error'</span>, err.<span class="hljs-property">message</span>));
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'boom'</span>));
<span class="hljs-comment">// Prints: ok boom</span></code><button class="copy-button">copy</button></pre>
<p>An <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> can be used to cancel waiting for the event:</p>
<pre class="with-54-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_">EventEmitter</span>, once } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</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">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params">emitter, event, signal</span>) {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(emitter, event, { signal });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'event emitted!'</span>);
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-keyword">if</span> (error.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Waiting for the event was canceled!'</span>);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'There was an error'</span>, error.<span class="hljs-property">message</span>);
}
}
}
<span class="hljs-title function_">foo</span>(ee, <span class="hljs-string">'foo'</span>, ac.<span class="hljs-property">signal</span>);
ac.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Prints: Waiting for the event was canceled!</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</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">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params">emitter, event, signal</span>) {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(emitter, event, { signal });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'event emitted!'</span>);
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-keyword">if</span> (error.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Waiting for the event was canceled!'</span>);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'There was an error'</span>, error.<span class="hljs-property">message</span>);
}
}
}
<span class="hljs-title function_">foo</span>(ee, <span class="hljs-string">'foo'</span>, ac.<span class="hljs-property">signal</span>);
ac.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Prints: Waiting for the event was canceled!</span></code><button class="copy-button">copy</button></pre>
<h4>Awaiting multiple events emitted on <code>process.nextTick()</code><span><a class="mark" href="#all_events_awaiting-multiple-events-emitted-on-processnexttick" id="all_events_awaiting-multiple-events-emitted-on-processnexttick">#</a></span><a aria-hidden="true" class="legacy" id="events_awaiting_multiple_events_emitted_on_process_nexttick"></a></h4>
<p>There is an edge case worth noting when using the <code>events.once()</code> function
to await multiple events emitted on in the same batch of <code>process.nextTick()</code>
operations, or whenever multiple events are emitted synchronously. Specifically,
because the <code>process.nextTick()</code> queue is drained before the <code>Promise</code> microtask
queue, and because <code>EventEmitter</code> emits all events synchronously, it is possible
for <code>events.once()</code> to miss an event.</p>
<pre class="with-54-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_">EventEmitter</span>, once } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'bar'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'bar'</span>);
<span class="hljs-comment">// This Promise will never resolve because the 'foo' event will</span>
<span class="hljs-comment">// have already been emitted before the Promise is created.</span>
<span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>);
}
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'bar'</span>);
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
});
<span class="hljs-title function_">foo</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'bar'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'bar'</span>);
<span class="hljs-comment">// This Promise will never resolve because the 'foo' event will</span>
<span class="hljs-comment">// have already been emitted before the Promise is created.</span>
<span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>);
}
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'bar'</span>);
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
});
<span class="hljs-title function_">foo</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>));</code><button class="copy-button">copy</button></pre>
<p>To catch both events, create each of the Promises <em>before</em> awaiting either
of them, then it becomes possible to use <code>Promise.all()</code>, <code>Promise.race()</code>,
or <code>Promise.allSettled()</code>:</p>
<pre class="with-54-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_">EventEmitter</span>, once } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([<span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'bar'</span>), <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'foo'</span>)]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
}
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'bar'</span>);
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
});
<span class="hljs-title function_">foo</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([<span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'bar'</span>), <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'foo'</span>)]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
}
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'bar'</span>);
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
});
<span class="hljs-title function_">foo</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>));</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.captureRejections</code><span><a class="mark" href="#all_events_eventscapturerejections" id="all_events_eventscapturerejections">#</a></span><a aria-hidden="true" class="legacy" id="events_events_capturerejections"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.4.0, v16.14.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v13.4.0, v12.16.0</td>
<td><p><span>Added in: v13.4.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></p>
<p>Change the default <code>captureRejections</code> option on all new <code>EventEmitter</code> objects.</p>
</section><section><h3><code>events.captureRejectionSymbol</code><span><a class="mark" href="#all_events_eventscapturerejectionsymbol" id="all_events_eventscapturerejectionsymbol">#</a></span><a aria-hidden="true" class="legacy" id="events_events_capturerejectionsymbol"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.4.0, v16.14.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v13.4.0, v12.16.0</td>
<td><p><span>Added in: v13.4.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Value: <code>Symbol.for('nodejs.rejection')</code></p>
<p>See how to write a custom <a href="#all_events_emittersymbolfornodejsrejectionerr-eventname-args">rejection handler</a>.</p>
</section><section><h3><code>events.listenerCount(emitter, eventName)</code><span><a class="mark" href="#all_events_eventslistenercountemitter-eventname" id="all_events_eventslistenercountemitter-eventname">#</a></span><a aria-hidden="true" class="legacy" id="events_events_listenercount_emitter_eventname"></a></h3>
<div class="api_metadata">
<span>Added in: v0.9.12</span><span>Deprecated since: v3.2.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_events_emitterlistenercounteventname-listener"><code>emitter.listenerCount()</code></a> instead.</div><p></p>
<ul>
<li><code>emitter</code> <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a> The emitter to query</li>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a> The event name</li>
</ul>
<p>A class method that returns the number of listeners for the given <code>eventName</code>
registered on the given <code>emitter</code>.</p>
<pre class="with-63-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_">EventEmitter</span>, listenerCount } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {});
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">listenerCount</span>(myEmitter, <span class="hljs-string">'event'</span>));
<span class="hljs-comment">// Prints: 2</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, listenerCount } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {});
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">listenerCount</span>(myEmitter, <span class="hljs-string">'event'</span>));
<span class="hljs-comment">// Prints: 2</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.on(emitter, eventName[, options])</code><span><a class="mark" href="#all_events_eventsonemitter-eventname-options" id="all_events_eventsonemitter-eventname-options">#</a></span><a aria-hidden="true" class="legacy" id="events_events_on_emitter_eventname_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Support <code>highWaterMark</code> and <code>lowWaterMark</code> options, For consistency. Old options are still supported.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p>The <code>close</code>, <code>highWatermark</code>, and <code>lowWatermark</code> options are supported now.</p></td></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p><span>Added in: v13.6.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>emitter</code> <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
<li><code>eventName</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#Symbol_type" class="type"><symbol></a> The name of the event being listened for</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="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Can be used to cancel awaiting events.</li>
<li><code>close</code> - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Names of events that will end the iteration.</li>
<li><code>highWaterMark</code> - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>Number.MAX_SAFE_INTEGER</code>
The high watermark. The emitter is paused every time the size of events
being buffered is higher than it. Supported only on emitters implementing
<code>pause()</code> and <code>resume()</code> methods.</li>
<li><code>lowWaterMark</code> - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>1</code>
The low watermark. The emitter is resumed every time the size of events
being buffered is lower than it. Supported only on emitters implementing
<code>pause()</code> and <code>resume()</code> methods.</li>
</ul>
</li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a> that iterates <code>eventName</code> events emitted by the <code>emitter</code></li>
</ul>
<pre class="with-52-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> { on, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-comment">// Emit later on</span>
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-number">42</span>);
});
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> <span class="hljs-title function_">on</span>(ee, <span class="hljs-string">'foo'</span>)) {
<span class="hljs-comment">// The execution of this inner block is synchronous and it</span>
<span class="hljs-comment">// processes one event at a time (even with await). Do not use</span>
<span class="hljs-comment">// if concurrent execution is required.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event); <span class="hljs-comment">// prints ['bar'] [42]</span>
}
<span class="hljs-comment">// Unreachable here</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { on, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-comment">// Emit later on</span>
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-number">42</span>);
});
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> <span class="hljs-title function_">on</span>(ee, <span class="hljs-string">'foo'</span>)) {
<span class="hljs-comment">// The execution of this inner block is synchronous and it</span>
<span class="hljs-comment">// processes one event at a time (even with await). Do not use</span>
<span class="hljs-comment">// if concurrent execution is required.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event); <span class="hljs-comment">// prints ['bar'] [42]</span>
}
<span class="hljs-comment">// Unreachable here</span>
})();</code><button class="copy-button">copy</button></pre>
<p>Returns an <code>AsyncIterator</code> that iterates <code>eventName</code> events. It will throw
if the <code>EventEmitter</code> emits <code>'error'</code>. It removes all listeners when
exiting the loop. The <code>value</code> returned by each iteration is an array
composed of the emitted event arguments.</p>
<p>An <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> can be used to cancel waiting on events:</p>
<pre class="with-52-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> { on, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-comment">// Emit later on</span>
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-number">42</span>);
});
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> <span class="hljs-title function_">on</span>(ee, <span class="hljs-string">'foo'</span>, { <span class="hljs-attr">signal</span>: ac.<span class="hljs-property">signal</span> })) {
<span class="hljs-comment">// The execution of this inner block is synchronous and it</span>
<span class="hljs-comment">// processes one event at a time (even with await). Do not use</span>
<span class="hljs-comment">// if concurrent execution is required.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event); <span class="hljs-comment">// prints ['bar'] [42]</span>
}
<span class="hljs-comment">// Unreachable here</span>
})();
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>());</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { on, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-comment">// Emit later on</span>
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-number">42</span>);
});
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> <span class="hljs-title function_">on</span>(ee, <span class="hljs-string">'foo'</span>, { <span class="hljs-attr">signal</span>: ac.<span class="hljs-property">signal</span> })) {
<span class="hljs-comment">// The execution of this inner block is synchronous and it</span>
<span class="hljs-comment">// processes one event at a time (even with await). Do not use</span>
<span class="hljs-comment">// if concurrent execution is required.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event); <span class="hljs-comment">// prints ['bar'] [42]</span>
}
<span class="hljs-comment">// Unreachable here</span>
})();
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>());</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.setMaxListeners(n[, ...eventTargets])</code><span><a class="mark" href="#all_events_eventssetmaxlistenersn-eventtargets" id="all_events_eventssetmaxlistenersn-eventtargets">#</a></span><a aria-hidden="true" class="legacy" id="events_events_setmaxlisteners_n_eventtargets"></a></h3>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<ul>
<li><code>n</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A non-negative number. The maximum number of listeners per
<code>EventTarget</code> event.</li>
<li><code>...eventsTargets</code> <a href="#all_events_class-eventtarget" class="type"><EventTarget[]></a> | <a href="#all_events_class-eventemitter" class="type"><EventEmitter[]></a> Zero or more <a href="#all_events_class-eventtarget" class="type"><EventTarget></a>
or <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a> instances. If none are specified, <code>n</code> is set as the default
max for all newly created <a href="#all_events_class-eventtarget" class="type"><EventTarget></a> and <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a> objects.</li>
</ul>
<pre class="with-60-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> { setMaxListeners, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">5</span>, target, emitter);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
setMaxListeners,
<span class="hljs-title class_">EventEmitter</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">5</span>, target, emitter);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.addAbortListener(signal, listener)</code><span><a class="mark" href="#all_events_eventsaddabortlistenersignal-listener" id="all_events_eventsaddabortlistenersignal-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_events_addabortlistener_signal_listener"></a></h3>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a></li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_events_event-listener" class="type"><EventListener></a></li>
<li>Returns: <a href="https://tc39.es/proposal-explicit-resource-management/#sec-disposable-interface" class="type"><Disposable></a> A Disposable that removes the <code>abort</code> listener.</li>
</ul>
<p>Listens once to the <code>abort</code> event on the provided <code>signal</code>.</p>
<p>Listening to the <code>abort</code> event on abort signals is unsafe and may
lead to resource leaks since another third party with the signal can
call <a href="#all_events_eventstopimmediatepropagation"><code>e.stopImmediatePropagation()</code></a>. Unfortunately Node.js cannot change
this since it would violate the web standard. Additionally, the original
API makes it easy to forget to remove listeners.</p>
<p>This API allows safely using <code>AbortSignal</code>s in Node.js APIs by solving these
two issues by listening to the event such that <code>stopImmediatePropagation</code> does
not prevent the listener from running.</p>
<p>Returns a disposable so that it may be unsubscribed from more easily.</p>
<pre class="with-52-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> { addAbortListener } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">example</span>(<span class="hljs-params">signal</span>) {
<span class="hljs-keyword">let</span> disposable;
<span class="hljs-keyword">try</span> {
signal.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'abort'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> e.<span class="hljs-title function_">stopImmediatePropagation</span>());
disposable = <span class="hljs-title function_">addAbortListener</span>(signal, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-comment">// Do something when signal is aborted.</span>
});
} <span class="hljs-keyword">finally</span> {
disposable?.[<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">dispose</span>]();
}
}</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { addAbortListener } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">example</span>(<span class="hljs-params">signal</span>) {
<span class="hljs-keyword">let</span> disposable;
<span class="hljs-keyword">try</span> {
signal.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'abort'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> e.<span class="hljs-title function_">stopImmediatePropagation</span>());
disposable = <span class="hljs-title function_">addAbortListener</span>(signal, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-comment">// Do something when signal is aborted.</span>
});
} <span class="hljs-keyword">finally</span> {
disposable?.[<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">dispose</span>]();
}
}</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>events.EventEmitterAsyncResource extends EventEmitter</code><span><a class="mark" href="#all_events_class-eventseventemitterasyncresource-extends-eventemitter" id="all_events_class-eventseventemitterasyncresource-extends-eventemitter">#</a></span><a aria-hidden="true" class="legacy" id="events_class_events_eventemitterasyncresource_extends_eventemitter"></a></h3>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.0</span>
</div>
<p>Integrates <code>EventEmitter</code> with <a href="#all_async_hooks_class-asyncresource" class="type"><AsyncResource></a> for <code>EventEmitter</code>s that
require manual async tracking. Specifically, all events emitted by instances
of <code>events.EventEmitterAsyncResource</code> will run within its <a href="async_context.html">async context</a>.</p>
<pre class="with-75-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_">EventEmitterAsyncResource</span>, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> { notStrictEqual, strictEqual } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { executionAsyncId, triggerAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-comment">// Async tracking tooling will identify this as 'Q'.</span>
<span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitterAsyncResource</span>({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Q'</span> });
<span class="hljs-comment">// 'foo' listeners will run in the EventEmitters async context.</span>
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">executionAsyncId</span>(), ee1.<span class="hljs-property">asyncId</span>);
<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">triggerAsyncId</span>(), ee1.<span class="hljs-property">triggerAsyncId</span>);
});
<span class="hljs-keyword">const</span> ee2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-comment">// 'foo' listeners on ordinary EventEmitters that do not track async</span>
<span class="hljs-comment">// context, however, run in the same async context as the emit().</span>
ee2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-title function_">executionAsyncId</span>(), ee2.<span class="hljs-property">asyncId</span>);
<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-title function_">triggerAsyncId</span>(), ee2.<span class="hljs-property">triggerAsyncId</span>);
});
<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
ee1.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
ee2.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitterAsyncResource</span>, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> { notStrictEqual, strictEqual } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { executionAsyncId, triggerAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-comment">// Async tracking tooling will identify this as 'Q'.</span>
<span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitterAsyncResource</span>({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Q'</span> });
<span class="hljs-comment">// 'foo' listeners will run in the EventEmitters async context.</span>
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">executionAsyncId</span>(), ee1.<span class="hljs-property">asyncId</span>);
<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">triggerAsyncId</span>(), ee1.<span class="hljs-property">triggerAsyncId</span>);
});
<span class="hljs-keyword">const</span> ee2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-comment">// 'foo' listeners on ordinary EventEmitters that do not track async</span>
<span class="hljs-comment">// context, however, run in the same async context as the emit().</span>
ee2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-title function_">executionAsyncId</span>(), ee2.<span class="hljs-property">asyncId</span>);
<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-title function_">triggerAsyncId</span>(), ee2.<span class="hljs-property">triggerAsyncId</span>);
});
<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
ee1.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
ee2.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>The <code>EventEmitterAsyncResource</code> class has the same methods and takes the
same options as <code>EventEmitter</code> and <code>AsyncResource</code> themselves.</p>
<h4><code>new events.EventEmitterAsyncResource([options])</code><span><a class="mark" href="#all_events_new-eventseventemitterasyncresourceoptions" id="all_events_new-eventseventemitterasyncresourceoptions">#</a></span><a aria-hidden="true" class="legacy" id="events_new_events_eventemitterasyncresource_options"></a></h4>
<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>captureRejections</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> It enables
<a href="#all_events_capture-rejections-of-promises">automatic capturing of promise rejection</a>.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The type of async event. <strong>Default:</strong> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target"><code>new.target.name</code></a>.</li>
<li><code>triggerAsyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ID of the execution context that created this
async event. <strong>Default:</strong> <code>executionAsyncId()</code>.</li>
<li><code>requireManualDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, disables <code>emitDestroy</code>
when the object is garbage collected. This usually does not need to be set
(even if <code>emitDestroy</code> is called manually), unless the resource's <code>asyncId</code>
is retrieved and the sensitive API's <code>emitDestroy</code> is called with it.
When set to <code>false</code>, the <code>emitDestroy</code> call on garbage collection
will only take place if there is at least one active <code>destroy</code> hook.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<h4><code>eventemitterasyncresource.asyncId</code><span><a class="mark" href="#all_events_eventemitterasyncresourceasyncid" id="all_events_eventemitterasyncresourceasyncid">#</a></span><a aria-hidden="true" class="legacy" id="events_eventemitterasyncresource_asyncid"></a></h4>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The unique <code>asyncId</code> assigned to the resource.</li>
</ul>
<h4><code>eventemitterasyncresource.asyncResource</code><span><a class="mark" href="#all_events_eventemitterasyncresourceasyncresource" id="all_events_eventemitterasyncresourceasyncresource">#</a></span><a aria-hidden="true" class="legacy" id="events_eventemitterasyncresource_asyncresource"></a></h4>
<ul>
<li>Type: The underlying <a href="#all_async_hooks_class-asyncresource" class="type"><AsyncResource></a>.</li>
</ul>
<p>The returned <code>AsyncResource</code> object has an additional <code>eventEmitter</code> property
that provides a reference to this <code>EventEmitterAsyncResource</code>.</p>
<h4><code>eventemitterasyncresource.emitDestroy()</code><span><a class="mark" href="#all_events_eventemitterasyncresourceemitdestroy" id="all_events_eventemitterasyncresourceemitdestroy">#</a></span><a aria-hidden="true" class="legacy" id="events_eventemitterasyncresource_emitdestroy"></a></h4>
<p>Call all <code>destroy</code> hooks. This should only ever be called once. An error will
be thrown if it is called more than once. This <strong>must</strong> be manually called. If
the resource is left to be collected by the GC then the <code>destroy</code> hooks will
never be called.</p>
<h4><code>eventemitterasyncresource.triggerAsyncId</code><span><a class="mark" href="#all_events_eventemitterasyncresourcetriggerasyncid" id="all_events_eventemitterasyncresourcetriggerasyncid">#</a></span><a aria-hidden="true" class="legacy" id="events_eventemitterasyncresource_triggerasyncid"></a></h4>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The same <code>triggerAsyncId</code> that is passed to the
<code>AsyncResource</code> constructor.</li>
</ul>
<p><a id="event-target-and-event-api"></a></p>
</section><section><h3><code>EventTarget</code> and <code>Event</code> API<span><a class="mark" href="#all_events_eventtarget-and-event-api" id="all_events_eventtarget-and-event-api">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_and_event_api"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>changed EventTarget error handling.</p></td></tr>
<tr><td>v15.4.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>EventTarget</code> and <code>Event</code> classes are now available as globals.</p></td></tr>
<tr><td>v14.5.0</td>
<td><p><span>Added in: v14.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>EventTarget</code> and <code>Event</code> objects are a Node.js-specific implementation
of the <a href="https://dom.spec.whatwg.org/#eventtarget"><code>EventTarget</code> Web API</a> that are exposed by some Node.js core APIs.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo event happened!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Node.js <code>EventTarget</code> vs. DOM <code>EventTarget</code><span><a class="mark" href="#all_events_nodejs-eventtarget-vs-dom-eventtarget" id="all_events_nodejs-eventtarget-vs-dom-eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="events_node_js_eventtarget_vs_dom_eventtarget"></a></h4>
<p>There are two key differences between the Node.js <code>EventTarget</code> and the
<a href="https://dom.spec.whatwg.org/#eventtarget"><code>EventTarget</code> Web API</a>:</p>
<ol>
<li>Whereas DOM <code>EventTarget</code> instances <em>may</em> be hierarchical, there is no
concept of hierarchy and event propagation in Node.js. That is, an event
dispatched to an <code>EventTarget</code> does not propagate through a hierarchy of
nested target objects that may each have their own set of handlers for the
event.</li>
<li>In the Node.js <code>EventTarget</code>, if an event listener is an async function
or returns a <code>Promise</code>, and the returned <code>Promise</code> rejects, the rejection
is automatically captured and handled the same way as a listener that
throws synchronously (see <a href="#all_events_eventtarget-error-handling"><code>EventTarget</code> error handling</a> for details).</li>
</ol>
<h4><code>NodeEventTarget</code> vs. <code>EventEmitter</code><span><a class="mark" href="#all_events_nodeeventtarget-vs-eventemitter" id="all_events_nodeeventtarget-vs-eventemitter">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_vs_eventemitter"></a></h4>
<p>The <code>NodeEventTarget</code> object implements a modified subset of the
<code>EventEmitter</code> API that allows it to closely <em>emulate</em> an <code>EventEmitter</code> in
certain situations. A <code>NodeEventTarget</code> is <em>not</em> an instance of <code>EventEmitter</code>
and cannot be used in place of an <code>EventEmitter</code> in most cases.</p>
<ol>
<li>Unlike <code>EventEmitter</code>, any given <code>listener</code> can be registered at most once
per event <code>type</code>. Attempts to register a <code>listener</code> multiple times are
ignored.</li>
<li>The <code>NodeEventTarget</code> does not emulate the full <code>EventEmitter</code> API.
Specifically the <code>prependListener()</code>, <code>prependOnceListener()</code>,
<code>rawListeners()</code>, and <code>errorMonitor</code> APIs are not emulated.
The <code>'newListener'</code> and <code>'removeListener'</code> events will also not be emitted.</li>
<li>The <code>NodeEventTarget</code> does not implement any special default behavior
for events with type <code>'error'</code>.</li>
<li>The <code>NodeEventTarget</code> supports <code>EventListener</code> objects as well as
functions as handlers for all event types.</li>
</ol>
<h4>Event listener<span><a class="mark" href="#all_events_event-listener" id="all_events_event-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_event_listener"></a></h4>
<p>Event listeners registered for an event <code>type</code> may either be JavaScript
functions or objects with a <code>handleEvent</code> property whose value is a function.</p>
<p>In either case, the handler function is invoked with the <code>event</code> argument
passed to the <code>eventTarget.dispatchEvent()</code> function.</p>
<p>Async functions may be used as event listeners. If an async handler function
rejects, the rejection is captured and handled as described in
<a href="#all_events_eventtarget-error-handling"><code>EventTarget</code> error handling</a>.</p>
<p>An error thrown by one handler function does not prevent the other handlers
from being invoked.</p>
<p>The return value of a handler function is ignored.</p>
<p>Handlers are always invoked in the order they were added.</p>
<p>Handler functions may mutate the <code>event</code> object.</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">handler1</span>(<span class="hljs-params">event</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>); <span class="hljs-comment">// Prints 'foo'</span>
event.<span class="hljs-property">a</span> = <span class="hljs-number">1</span>;
}
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">handler2</span>(<span class="hljs-params">event</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>); <span class="hljs-comment">// Prints 'foo'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">a</span>); <span class="hljs-comment">// Prints 1</span>
}
<span class="hljs-keyword">const</span> handler3 = {
<span class="hljs-title function_">handleEvent</span>(<span class="hljs-params">event</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>); <span class="hljs-comment">// Prints 'foo'</span>
},
};
<span class="hljs-keyword">const</span> handler4 = {
<span class="hljs-keyword">async</span> <span class="hljs-title function_">handleEvent</span>(<span class="hljs-params">event</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>); <span class="hljs-comment">// Prints 'foo'</span>
},
};
<span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler1);
target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler2);
target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler3);
target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler4, { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span> });</code> <button class="copy-button">copy</button></pre>
<h4><code>EventTarget</code> error handling<span><a class="mark" href="#all_events_eventtarget-error-handling" id="all_events_eventtarget-error-handling">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_error_handling"></a></h4>
<p>When a registered event listener throws (or returns a Promise that rejects),
by default the error is treated as an uncaught exception on
<code>process.nextTick()</code>. This means uncaught exceptions in <code>EventTarget</code>s will
terminate the Node.js process by default.</p>
<p>Throwing within an event listener will <em>not</em> stop the other registered handlers
from being invoked.</p>
<p>The <code>EventTarget</code> does not implement any special default handling for <code>'error'</code>
type events like <code>EventEmitter</code>.</p>
<p>Currently errors are first forwarded to the <code>process.on('error')</code> event
before reaching <code>process.on('uncaughtException')</code>. This behavior is
deprecated and will change in a future release to align <code>EventTarget</code> with
other Node.js APIs. Any code relying on the <code>process.on('error')</code> event should
be aligned with the new behavior.</p>
<h4>Class: <code>Event</code><span><a class="mark" href="#all_events_class-event" id="all_events_class-event">#</a></span><a aria-hidden="true" class="legacy" id="events_class_event"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>Event</code> class is now available through the global object.</p></td></tr>
<tr><td>v14.5.0</td>
<td><p><span>Added in: v14.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>Event</code> object is an adaptation of the <a href="https://dom.spec.whatwg.org/#event"><code>Event</code> Web API</a>. Instances
are created internally by Node.js.</p>
<h5><code>event.bubbles</code><span><a class="mark" href="#all_events_eventbubbles" id="all_events_eventbubbles">#</a></span><a aria-hidden="true" class="legacy" id="events_event_bubbles"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Always returns <code>false</code>.</li>
</ul>
<p>This is not used in Node.js and is provided purely for completeness.</p>
<h5><code>event.cancelBubble</code><span><a class="mark" href="#all_events_eventcancelbubble" id="all_events_eventcancelbubble">#</a></span><a aria-hidden="true" class="legacy" id="events_event_cancelbubble"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_events_eventstoppropagation"><code>event.stopPropagation()</code></a> instead.</div><p></p>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Alias for <code>event.stopPropagation()</code> if set to <code>true</code>. This is not used
in Node.js and is provided purely for completeness.</p>
<h5><code>event.cancelable</code><span><a class="mark" href="#all_events_eventcancelable" id="all_events_eventcancelable">#</a></span><a aria-hidden="true" class="legacy" id="events_event_cancelable"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> True if the event was created with the <code>cancelable</code> option.</li>
</ul>
<h5><code>event.composed</code><span><a class="mark" href="#all_events_eventcomposed" id="all_events_eventcomposed">#</a></span><a aria-hidden="true" class="legacy" id="events_event_composed"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Always returns <code>false</code>.</li>
</ul>
<p>This is not used in Node.js and is provided purely for completeness.</p>
<h5><code>event.composedPath()</code><span><a class="mark" href="#all_events_eventcomposedpath" id="all_events_eventcomposedpath">#</a></span><a aria-hidden="true" class="legacy" id="events_event_composedpath"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p>Returns an array containing the current <code>EventTarget</code> as the only entry or
empty if the event is not being dispatched. This is not used in
Node.js and is provided purely for completeness.</p>
<h5><code>event.currentTarget</code><span><a class="mark" href="#all_events_eventcurrenttarget" id="all_events_eventcurrenttarget">#</a></span><a aria-hidden="true" class="legacy" id="events_event_currenttarget"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="#all_events_class-eventtarget" class="type"><EventTarget></a> The <code>EventTarget</code> dispatching the event.</li>
</ul>
<p>Alias for <code>event.target</code>.</p>
<h5><code>event.defaultPrevented</code><span><a class="mark" href="#all_events_eventdefaultprevented" id="all_events_eventdefaultprevented">#</a></span><a aria-hidden="true" class="legacy" id="events_event_defaultprevented"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <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 <code>cancelable</code> is <code>true</code> and <code>event.preventDefault()</code> has been
called.</p>
<h5><code>event.eventPhase</code><span><a class="mark" href="#all_events_eventeventphase" id="all_events_eventeventphase">#</a></span><a aria-hidden="true" class="legacy" id="events_event_eventphase"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Returns <code>0</code> while an event is not being dispatched, <code>2</code> while
it is being dispatched.</li>
</ul>
<p>This is not used in Node.js and is provided purely for completeness.</p>
<h5><code>event.initEvent(type[, bubbles[, cancelable]])</code><span><a class="mark" href="#all_events_eventiniteventtype-bubbles-cancelable" id="all_events_eventiniteventtype-bubbles-cancelable">#</a></span><a aria-hidden="true" class="legacy" id="events_event_initevent_type_bubbles_cancelable"></a></h5>
<div class="api_metadata">
<span>Added in: v19.5.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: The WHATWG spec considers it deprecated and users
shouldn't use it at all.</div><p></p>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>bubbles</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>cancelable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Redundant with event constructors and incapable of setting <code>composed</code>.
This is not used in Node.js and is provided purely for completeness.</p>
<h5><code>event.isTrusted</code><span><a class="mark" href="#all_events_eventistrusted" id="all_events_eventistrusted">#</a></span><a aria-hidden="true" class="legacy" id="events_event_istrusted"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>The <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> <code>"abort"</code> event is emitted with <code>isTrusted</code> set to <code>true</code>. The
value is <code>false</code> in all other cases.</p>
<h5><code>event.preventDefault()</code><span><a class="mark" href="#all_events_eventpreventdefault" id="all_events_eventpreventdefault">#</a></span><a aria-hidden="true" class="legacy" id="events_event_preventdefault"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p>Sets the <code>defaultPrevented</code> property to <code>true</code> if <code>cancelable</code> is <code>true</code>.</p>
<h5><code>event.returnValue</code><span><a class="mark" href="#all_events_eventreturnvalue" id="all_events_eventreturnvalue">#</a></span><a aria-hidden="true" class="legacy" id="events_event_returnvalue"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_events_eventdefaultprevented"><code>event.defaultPrevented</code></a> instead.</div><p></p>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> True if the event has not been canceled.</li>
</ul>
<p>The value of <code>event.returnValue</code> is always the opposite of <code>event.defaultPrevented</code>.
This is not used in Node.js and is provided purely for completeness.</p>
<h5><code>event.srcElement</code><span><a class="mark" href="#all_events_eventsrcelement" id="all_events_eventsrcelement">#</a></span><a aria-hidden="true" class="legacy" id="events_event_srcelement"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_events_eventtarget"><code>event.target</code></a> instead.</div><p></p>
<ul>
<li>Type: <a href="#all_events_class-eventtarget" class="type"><EventTarget></a> The <code>EventTarget</code> dispatching the event.</li>
</ul>
<p>Alias for <code>event.target</code>.</p>
<h5><code>event.stopImmediatePropagation()</code><span><a class="mark" href="#all_events_eventstopimmediatepropagation" id="all_events_eventstopimmediatepropagation">#</a></span><a aria-hidden="true" class="legacy" id="events_event_stopimmediatepropagation"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p>Stops the invocation of event listeners after the current one completes.</p>
<h5><code>event.stopPropagation()</code><span><a class="mark" href="#all_events_eventstoppropagation" id="all_events_eventstoppropagation">#</a></span><a aria-hidden="true" class="legacy" id="events_event_stoppropagation"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p>This is not used in Node.js and is provided purely for completeness.</p>
<h5><code>event.target</code><span><a class="mark" href="#all_events_eventtarget" id="all_events_eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="events_event_target"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="#all_events_class-eventtarget" class="type"><EventTarget></a> The <code>EventTarget</code> dispatching the event.</li>
</ul>
<h5><code>event.timeStamp</code><span><a class="mark" href="#all_events_eventtimestamp" id="all_events_eventtimestamp">#</a></span><a aria-hidden="true" class="legacy" id="events_event_timestamp"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The millisecond timestamp when the <code>Event</code> object was created.</p>
<h5><code>event.type</code><span><a class="mark" href="#all_events_eventtype" id="all_events_eventtype">#</a></span><a aria-hidden="true" class="legacy" id="events_event_type"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The event type identifier.</p>
<h4>Class: <code>EventTarget</code><span><a class="mark" href="#all_events_class-eventtarget" id="all_events_class-eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="events_class_eventtarget"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>EventTarget</code> class is now available through the global object.</p></td></tr>
<tr><td>v14.5.0</td>
<td><p><span>Added in: v14.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>eventTarget.addEventListener(type, listener[, options])</code><span><a class="mark" href="#all_events_eventtargetaddeventlistenertype-listener-options" id="all_events_eventtargetaddeventlistenertype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_addeventlistener_type_listener_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>v15.4.0</td>
<td><p>add support for <code>signal</code> option.</p></td></tr>
<tr><td>v14.5.0</td>
<td><p><span>Added in: v14.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_events_event-listener" class="type"><EventListener></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>once</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the listener is automatically removed
when it is first invoked. <strong>Default:</strong> <code>false</code>.</li>
<li><code>passive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, serves as a hint that the listener will
not call the <code>Event</code> object's <code>preventDefault()</code> method.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>capture</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Not directly used by Node.js. Added for API
completeness. <strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> The listener will be removed when the given
AbortSignal object's <code>abort()</code> method is called.</li>
</ul>
</li>
</ul>
<p>Adds a new handler for the <code>type</code> event. Any given <code>listener</code> is added
only once per <code>type</code> and per <code>capture</code> option value.</p>
<p>If the <code>once</code> option is <code>true</code>, the <code>listener</code> is removed after the
next time a <code>type</code> event is dispatched.</p>
<p>The <code>capture</code> option is not used by Node.js in any functional way other than
tracking registered event listeners per the <code>EventTarget</code> specification.
Specifically, the <code>capture</code> option is used as part of the key when registering
a <code>listener</code>. Any individual <code>listener</code> may be added once with
<code>capture = false</code>, and once with <code>capture = true</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">handler</span>(<span class="hljs-params">event</span>) {}
<span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler, { <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span> }); <span class="hljs-comment">// first</span>
target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler, { <span class="hljs-attr">capture</span>: <span class="hljs-literal">false</span> }); <span class="hljs-comment">// second</span>
<span class="hljs-comment">// Removes the second instance of handler</span>
target.<span class="hljs-title function_">removeEventListener</span>(<span class="hljs-string">'foo'</span>, handler);
<span class="hljs-comment">// Removes the first instance of handler</span>
target.<span class="hljs-title function_">removeEventListener</span>(<span class="hljs-string">'foo'</span>, handler, { <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span> });</code> <button class="copy-button">copy</button></pre>
<h5><code>eventTarget.dispatchEvent(event)</code><span><a class="mark" href="#all_events_eventtargetdispatcheventevent" id="all_events_eventtargetdispatcheventevent">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_dispatchevent_event"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li><code>event</code> <a href="#all_events_class-event" class="type"><Event></a></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 either event's <code>cancelable</code> attribute value is
false or its <code>preventDefault()</code> method was not invoked, otherwise <code>false</code>.</li>
</ul>
<p>Dispatches the <code>event</code> to the list of handlers for <code>event.type</code>.</p>
<p>The registered event listeners is synchronously invoked in the order they
were registered.</p>
<h5><code>eventTarget.removeEventListener(type, listener[, options])</code><span><a class="mark" href="#all_events_eventtargetremoveeventlistenertype-listener-options" id="all_events_eventtargetremoveeventlistenertype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_removeeventlistener_type_listener_options"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_events_event-listener" class="type"><EventListener></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>capture</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
</li>
</ul>
<p>Removes the <code>listener</code> from the list of handlers for event <code>type</code>.</p>
<h4>Class: <code>CustomEvent</code><span><a class="mark" href="#all_events_class-customevent" id="all_events_class-customevent">#</a></span><a aria-hidden="true" class="legacy" id="events_class_customevent"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>CustomEvent is now stable.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p><span>Added in: v18.7.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<ul>
<li>Extends: <a href="#all_events_class-event" class="type"><Event></a></li>
</ul>
<p>The <code>CustomEvent</code> object is an adaptation of the <a href="https://dom.spec.whatwg.org/#customevent"><code>CustomEvent</code> Web API</a>.
Instances are created internally by Node.js.</p>
<h5><code>event.detail</code><span><a class="mark" href="#all_events_eventdetail" id="all_events_eventdetail">#</a></span><a aria-hidden="true" class="legacy" id="events_event_detail"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>CustomEvent is now stable.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p><span>Added in: v18.7.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Returns custom data passed when initializing.</li>
</ul>
<p>Read-only.</p>
<h4>Class: <code>NodeEventTarget</code><span><a class="mark" href="#all_events_class-nodeeventtarget" id="all_events_class-nodeeventtarget">#</a></span><a aria-hidden="true" class="legacy" id="events_class_nodeeventtarget"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventtarget" class="type"><EventTarget></a></li>
</ul>
<p>The <code>NodeEventTarget</code> is a Node.js-specific extension to <code>EventTarget</code>
that emulates a subset of the <code>EventEmitter</code> API.</p>
<h5><code>nodeEventTarget.addListener(type, listener)</code><span><a class="mark" href="#all_events_nodeeventtargetaddlistenertype-listener" id="all_events_nodeeventtargetaddlistenertype-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_addlistener_type_listener"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p>
</li>
<li>
<p><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_events_event-listener" class="type"><EventListener></a></p>
</li>
<li>
<p>Returns: <a href="#all_events_class-eventtarget" class="type"><EventTarget></a> this</p>
</li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that emulates the
equivalent <code>EventEmitter</code> API. The only difference between <code>addListener()</code> and
<code>addEventListener()</code> is that <code>addListener()</code> will return a reference to the
<code>EventTarget</code>.</p>
<h5><code>nodeEventTarget.emit(type, arg)</code><span><a class="mark" href="#all_events_nodeeventtargetemittype-arg" id="all_events_nodeeventtargetemittype-arg">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_emit_type_arg"></a></h5>
<div class="api_metadata">
<span>Added in: v15.2.0</span>
</div>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>arg</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#Boolean_type" class="type"><boolean></a> <code>true</code> if event listeners registered for the <code>type</code> exist,
otherwise <code>false</code>.</li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that dispatches the
<code>arg</code> to the list of handlers for <code>type</code>.</p>
<h5><code>nodeEventTarget.eventNames()</code><span><a class="mark" href="#all_events_nodeeventtargeteventnames" id="all_events_nodeeventtargeteventnames">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_eventnames"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that returns an array
of event <code>type</code> names for which event listeners are registered.</p>
<h5><code>nodeEventTarget.listenerCount(type)</code><span><a class="mark" href="#all_events_nodeeventtargetlistenercounttype" id="all_events_nodeeventtargetlistenercounttype">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_listenercount_type"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></p>
</li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that returns the number
of event listeners registered for the <code>type</code>.</p>
<h5><code>nodeEventTarget.setMaxListeners(n)</code><span><a class="mark" href="#all_events_nodeeventtargetsetmaxlistenersn" id="all_events_nodeeventtargetsetmaxlistenersn">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_setmaxlisteners_n"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li><code>n</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that sets the number
of max event listeners as <code>n</code>.</p>
<h5><code>nodeEventTarget.getMaxListeners()</code><span><a class="mark" href="#all_events_nodeeventtargetgetmaxlisteners" id="all_events_nodeeventtargetgetmaxlisteners">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_getmaxlisteners"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that returns the number
of max event listeners.</p>
<h5><code>nodeEventTarget.off(type, listener[, options])</code><span><a class="mark" href="#all_events_nodeeventtargetofftype-listener-options" id="all_events_nodeeventtargetofftype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_off_type_listener_options"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p>
</li>
<li>
<p><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_events_event-listener" class="type"><EventListener></a></p>
</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p>
<ul>
<li><code>capture</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
</li>
<li>
<p>Returns: <a href="#all_events_class-eventtarget" class="type"><EventTarget></a> this</p>
</li>
</ul>
<p>Node.js-specific alias for <code>eventTarget.removeEventListener()</code>.</p>
<h5><code>nodeEventTarget.on(type, listener)</code><span><a class="mark" href="#all_events_nodeeventtargetontype-listener" id="all_events_nodeeventtargetontype-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_on_type_listener"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p>
</li>
<li>
<p><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_events_event-listener" class="type"><EventListener></a></p>
</li>
<li>
<p>Returns: <a href="#all_events_class-eventtarget" class="type"><EventTarget></a> this</p>
</li>
</ul>
<p>Node.js-specific alias for <code>eventTarget.addEventListener()</code>.</p>
<h5><code>nodeEventTarget.once(type, listener)</code><span><a class="mark" href="#all_events_nodeeventtargetoncetype-listener" id="all_events_nodeeventtargetoncetype-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_once_type_listener"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p>
</li>
<li>
<p><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_events_event-listener" class="type"><EventListener></a></p>
</li>
<li>
<p>Returns: <a href="#all_events_class-eventtarget" class="type"><EventTarget></a> this</p>
</li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that adds a <code>once</code>
listener for the given event <code>type</code>. This is equivalent to calling <code>on</code>
with the <code>once</code> option set to <code>true</code>.</p>
<h5><code>nodeEventTarget.removeAllListeners([type])</code><span><a class="mark" href="#all_events_nodeeventtargetremovealllistenerstype" id="all_events_nodeeventtargetremovealllistenerstype">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_removealllisteners_type"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p>
</li>
<li>
<p>Returns: <a href="#all_events_class-eventtarget" class="type"><EventTarget></a> this</p>
</li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class. If <code>type</code> is specified,
removes all registered listeners for <code>type</code>, otherwise removes all registered
listeners.</p>
<h5><code>nodeEventTarget.removeListener(type, listener[, options])</code><span><a class="mark" href="#all_events_nodeeventtargetremovelistenertype-listener-options" id="all_events_nodeeventtargetremovelistenertype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_removelistener_type_listener_options"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p>
</li>
<li>
<p><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_events_event-listener" class="type"><EventListener></a></p>
</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p>
<ul>
<li><code>capture</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
</li>
<li>
<p>Returns: <a href="#all_events_class-eventtarget" class="type"><EventTarget></a> this</p>
</li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that removes the
<code>listener</code> for the given <code>type</code>. The only difference between <code>removeListener()</code>
and <code>removeEventListener()</code> is that <code>removeListener()</code> will return a reference
to the <code>EventTarget</code>.</p></section>
</section>
<section><h2>File system<span><a class="mark" href="#all_fs_file-system" id="all_fs_file-system">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_system"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/fs.js">lib/fs.js</a></p>
<p>The <code>node:fs</code> module enables interacting with the file system in a
way modeled on standard POSIX functions.</p>
<p>To use the promise-based APIs:</p>
<pre class="with-39-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-keyword">as</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);</code><button class="copy-button">copy</button></pre>
<p>To use the callback and sync APIs:</p>
<pre class="with-30-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-keyword">as</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);</code><button class="copy-button">copy</button></pre>
<p>All file system operations have synchronous, callback, and promise-based
forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).</p>
<section><h3>Promise example<span><a class="mark" href="#all_fs_promise-example" id="all_fs_promise-example">#</a></span><a aria-hidden="true" class="legacy" id="fs_promise_example"></a></h3>
<p>Promise-based operations return a promise that is fulfilled when the
asynchronous operation is complete.</p>
<pre class="with-47-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> { unlink } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">unlink</span>(<span class="hljs-string">'/tmp/hello'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'successfully deleted /tmp/hello'</span>);
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'there was an error:'</span>, error.<span class="hljs-property">message</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { unlink } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);
(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params">path</span>) {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">unlink</span>(path);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`successfully deleted <span class="hljs-subst">${path}</span>`</span>);
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'there was an error:'</span>, error.<span class="hljs-property">message</span>);
}
})(<span class="hljs-string">'/tmp/hello'</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Callback example<span><a class="mark" href="#all_fs_callback-example" id="all_fs_callback-example">#</a></span><a aria-hidden="true" class="legacy" id="fs_callback_example"></a></h3>
<p>The callback form takes a completion callback function as its last
argument and invokes the operation asynchronously. The arguments passed to
the completion callback depend on the method, but the first argument is always
reserved for an exception. If the operation is completed successfully, then
the first argument is <code>null</code> or <code>undefined</code>.</p>
<pre class="with-38-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> { unlink } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">unlink</span>(<span class="hljs-string">'/tmp/hello'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'successfully deleted /tmp/hello'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { unlink } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-title function_">unlink</span>(<span class="hljs-string">'/tmp/hello'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'successfully deleted /tmp/hello'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>The callback-based versions of the <code>node:fs</code> module APIs are preferable over
the use of the promise APIs when maximal performance (both in terms of
execution time and memory allocation) is required.</p>
</section><section><h3>Synchronous example<span><a class="mark" href="#all_fs_synchronous-example" id="all_fs_synchronous-example">#</a></span><a aria-hidden="true" class="legacy" id="fs_synchronous_example"></a></h3>
<p>The synchronous APIs block the Node.js event loop and further JavaScript
execution until the operation is complete. Exceptions are thrown immediately
and can be handled using <code>try…catch</code>, or can be allowed to bubble up.</p>
<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> { unlinkSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">unlinkSync</span>(<span class="hljs-string">'/tmp/hello'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'successfully deleted /tmp/hello'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-comment">// handle the error</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { unlinkSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">unlinkSync</span>(<span class="hljs-string">'/tmp/hello'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'successfully deleted /tmp/hello'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-comment">// handle the error</span>
}</code><button class="copy-button">copy</button></pre>
</section><section><h3>Promises API<span><a class="mark" href="#all_fs_promises-api" id="all_fs_promises-api">#</a></span><a aria-hidden="true" class="legacy" id="fs_promises_api"></a></h3>
<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>Exposed as <code>require('fs/promises')</code>.</p></td></tr>
<tr><td>v11.14.0, v10.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v10.1.0</td>
<td><p>The API is accessible via <code>require('fs').promises</code> only.</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>
<p>The <code>fs/promises</code> API provides asynchronous file system methods that return
promises.</p>
<p>The promise APIs use the underlying Node.js threadpool to perform file
system operations off the event loop thread. These operations are not
synchronized or threadsafe. Care must be taken when performing multiple
concurrent modifications on the same file or data corruption may occur.</p>
<h4>Class: <code>FileHandle</code><span><a class="mark" href="#all_fs_class-filehandle" id="all_fs_class-filehandle">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_filehandle"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>A <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> object is an object wrapper for a numeric file descriptor.</p>
<p>Instances of the <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> object are created by the <code>fsPromises.open()</code>
method.</p>
<p>All <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> objects are <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a>s.</p>
<p>If a <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> is not closed using the <code>filehandle.close()</code> method, it will
try to automatically close the file descriptor and emit a process warning,
helping to prevent memory leaks. Please do not rely on this behavior because
it can be unreliable and the file may not be closed. Instead, always explicitly
close <a href="#all_fs_class-filehandle" class="type"><FileHandle></a>s. Node.js may change this behavior in the future.</p>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_fs_event-close" id="all_fs_event-close">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_close"></a></h5>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<p>The <code>'close'</code> event is emitted when the <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> has been closed and can no
longer be used.</p>
<h5><code>filehandle.appendFile(data[, options])</code><span><a class="mark" href="#all_fs_filehandleappendfiledata-options" id="all_fs_filehandleappendfiledata-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_appendfile_data_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>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v15.14.0, v14.18.0</td>
<td><p>The <code>data</code> argument supports <code>AsyncIterable</code>, <code>Iterable</code>, and <code>Stream</code>.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>data</code> parameter won't coerce unsupported input to strings anymore.</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>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="#all_stream_stream" class="type"><Stream></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the underlying file descriptor is flushed
prior to closing it. <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 with <code>undefined</code> upon success.</li>
</ul>
<p>Alias of <a href="#all_fs_filehandlewritefiledata-options"><code>filehandle.writeFile()</code></a>.</p>
<p>When operating on file handles, the mode cannot be changed from what it was set
to with <a href="#all_fs_fspromisesopenpath-flags-mode"><code>fsPromises.open()</code></a>. Therefore, this is equivalent to
<a href="#all_fs_filehandlewritefiledata-options"><code>filehandle.writeFile()</code></a>.</p>
<h5><code>filehandle.chmod(mode)</code><span><a class="mark" href="#all_fs_filehandlechmodmode" id="all_fs_filehandlechmodmode">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_chmod_mode"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> the file mode bit mask.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Modifies the permissions on the file. See <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a>.</p>
<h5><code>filehandle.chown(uid, gid)</code><span><a class="mark" href="#all_fs_filehandlechownuid-gid" id="all_fs_filehandlechownuid-gid">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_chown_uid_gid"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The file's new owner's user id.</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The file's new group's group id.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Changes the ownership of the file. A wrapper for <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a>.</p>
<h5><code>filehandle.close()</code><span><a class="mark" href="#all_fs_filehandleclose" id="all_fs_filehandleclose">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_close"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Closes the file handle after waiting for any pending operation on the handle to
complete.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">let</span> filehandle;
<span class="hljs-keyword">try</span> {
filehandle = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'thefile.txt'</span>, <span class="hljs-string">'r'</span>);
} <span class="hljs-keyword">finally</span> {
<span class="hljs-keyword">await</span> filehandle?.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<h5><code>filehandle.createReadStream([options])</code><span><a class="mark" href="#all_fs_filehandlecreatereadstreamoptions" id="all_fs_filehandlecreatereadstreamoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_createreadstream_options"></a></h5>
<div class="api_metadata">
<span>Added in: v16.11.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>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>null</code></li>
<li><code>autoClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</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> <strong>Default:</strong> <code>true</code></li>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>Infinity</code></li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>64 * 1024</code></li>
<li><code>signal</code> <a href="#all_globals_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> <strong>Default:</strong> <code>undefined</code></li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsreadstream" class="type"><fs.ReadStream></a></li>
</ul>
<p><code>options</code> can include <code>start</code> and <code>end</code> values to read a range of bytes from
the file instead of the entire file. Both <code>start</code> and <code>end</code> are inclusive and
start counting at 0, allowed values are in the
[0, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER"><code>Number.MAX_SAFE_INTEGER</code></a>] range. If <code>start</code> is
omitted or <code>undefined</code>, <code>filehandle.createReadStream()</code> reads sequentially from
the current file position. The <code>encoding</code> can be any one of those accepted by
<a href="#all_buffer_class-buffer" class="type"><Buffer></a>.</p>
<p>If the <code>FileHandle</code> points to a character device that only supports blocking
reads (such as keyboard or sound card), read operations do not finish until data
is available. This can prevent the process from exiting and the stream from
closing naturally.</p>
<p>By default, the stream will emit a <code>'close'</code> event after it has been
destroyed. Set the <code>emitClose</code> option to <code>false</code> to change this behavior.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">const</span> fd = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'/dev/input/event0'</span>);
<span class="hljs-comment">// Create a stream from some character device.</span>
<span class="hljs-keyword">const</span> stream = fd.<span class="hljs-title function_">createReadStream</span>();
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">close</span>(); <span class="hljs-comment">// This may not close the stream.</span>
<span class="hljs-comment">// Artificially marking end-of-stream, as if the underlying resource had</span>
<span class="hljs-comment">// indicated end-of-file by itself, allows the stream to close.</span>
<span class="hljs-comment">// This does not cancel pending read operations, and if there is such an</span>
<span class="hljs-comment">// operation, the process may still not be able to exit successfully</span>
<span class="hljs-comment">// until it finishes.</span>
stream.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>);
stream.<span class="hljs-title function_">read</span>(<span class="hljs-number">0</span>);
}, <span class="hljs-number">100</span>);</code> <button class="copy-button">copy</button></pre>
<p>If <code>autoClose</code> is false, then the file descriptor won't be closed, even if
there's an error. It is the application's responsibility to close it and make
sure there's no file descriptor leak. If <code>autoClose</code> is set to true (default
behavior), on <code>'error'</code> or <code>'end'</code> the file descriptor will be closed
automatically.</p>
<p>An example to read the last 10 bytes of a file which is 100 bytes long:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">const</span> fd = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'sample.txt'</span>);
fd.<span class="hljs-title function_">createReadStream</span>({ <span class="hljs-attr">start</span>: <span class="hljs-number">90</span>, <span class="hljs-attr">end</span>: <span class="hljs-number">99</span> });</code> <button class="copy-button">copy</button></pre>
<h5><code>filehandle.createWriteStream([options])</code><span><a class="mark" href="#all_fs_filehandlecreatewritestreamoptions" id="all_fs_filehandlecreatewritestreamoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_createwritestream_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>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v16.11.0</td>
<td><p><span>Added in: v16.11.0</span></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>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>autoClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</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> <strong>Default:</strong> <code>true</code></li>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></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> <strong>Default:</strong> <code>16384</code></li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the underlying file descriptor is flushed
prior to closing it. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fswritestream" class="type"><fs.WriteStream></a></li>
</ul>
<p><code>options</code> may also include a <code>start</code> option to allow writing data at some
position past the beginning of the file, allowed values are in the
[0, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER"><code>Number.MAX_SAFE_INTEGER</code></a>] range. Modifying a file rather than
replacing it may require the <code>flags</code> <code>open</code> option to be set to <code>r+</code> rather than
the default <code>r</code>. The <code>encoding</code> can be any one of those accepted by <a href="#all_buffer_class-buffer" class="type"><Buffer></a>.</p>
<p>If <code>autoClose</code> is set to true (default behavior) on <code>'error'</code> or <code>'finish'</code>
the file descriptor will be closed automatically. If <code>autoClose</code> is false,
then the file descriptor won't be closed, even if there's an error.
It is the application's responsibility to close it and make sure there's no
file descriptor leak.</p>
<p>By default, the stream will emit a <code>'close'</code> event after it has been
destroyed. Set the <code>emitClose</code> option to <code>false</code> to change this behavior.</p>
<h5><code>filehandle.datasync()</code><span><a class="mark" href="#all_fs_filehandledatasync" id="all_fs_filehandledatasync">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_datasync"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Forces all currently queued I/O operations associated with the file to the
operating system's synchronized I/O completion state. Refer to the POSIX
<a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html"><code>fdatasync(2)</code></a> documentation for details.</p>
<p>Unlike <code>filehandle.sync</code> this method does not flush modified metadata.</p>
<h5><code>filehandle.fd</code><span><a class="mark" href="#all_fs_filehandlefd" id="all_fs_filehandlefd">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_fd"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The numeric file descriptor managed by the <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> object.</li>
</ul>
<h5><code>filehandle.read(buffer, offset, length, position)</code><span><a class="mark" href="#all_fs_filehandlereadbuffer-offset-length-position" id="all_fs_filehandlereadbuffer-offset-length-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_read_buffer_offset_length_position"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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 buffer that will be filled with the
file data read.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The location in the buffer at which to start filling.
<strong>Default:</strong> <code>0</code></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of bytes to read. <strong>Default:</strong>
<code>buffer.byteLength - offset</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The location where to begin reading data
from the file. If <code>null</code> or <code>-1</code>, data will be read from the current file
position, and the position will be updated. If <code>position</code> is a non-negative
integer, the current file position will remain unchanged.
<strong>Default:</strong>: <code>null</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills upon success with an object with two properties:
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of bytes read</li>
<li><code>buffer</code> <a href="#all_buffer_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 reference to the passed in <code>buffer</code>
argument.</li>
</ul>
</li>
</ul>
<p>Reads data from the file and stores that in the given buffer.</p>
<p>If the file is not modified concurrently, the end-of-file is reached when the
number of bytes read is zero.</p>
<h5><code>filehandle.read([options])</code><span><a class="mark" href="#all_fs_filehandlereadoptions" id="all_fs_filehandlereadoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_read_options"></a></h5>
<div class="api_metadata">
<span>Added in: v13.11.0, v12.17.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>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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 buffer that will be filled with the
file data read. <strong>Default:</strong> <code>Buffer.alloc(16384)</code></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The location in the buffer at which to start filling.
<strong>Default:</strong> <code>0</code></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of bytes to read. <strong>Default:</strong>
<code>buffer.byteLength - offset</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The location where to begin reading data from the
file. If <code>null</code>, data will be read from the current file position, and
the position will be updated. If <code>position</code> is an integer, the current
file position will remain unchanged. <strong>Default:</strong>: <code>null</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 upon success with an object with two properties:
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of bytes read</li>
<li><code>buffer</code> <a href="#all_buffer_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 reference to the passed in <code>buffer</code>
argument.</li>
</ul>
</li>
</ul>
<p>Reads data from the file and stores that in the given buffer.</p>
<p>If the file is not modified concurrently, the end-of-file is reached when the
number of bytes read is zero.</p>
<h5><code>filehandle.read(buffer[, options])</code><span><a class="mark" href="#all_fs_filehandlereadbuffer-options" id="all_fs_filehandlereadbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_read_buffer_options"></a></h5>
<div class="api_metadata">
<span>Added in: v18.2.0, v16.17.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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 buffer that will be filled with the
file data read.</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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The location in the buffer at which to start filling.
<strong>Default:</strong> <code>0</code></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of bytes to read. <strong>Default:</strong>
<code>buffer.byteLength - offset</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The location where to begin reading data from the
file. If <code>null</code>, data will be read from the current file position, and
the position will be updated. If <code>position</code> is an integer, the current
file position will remain unchanged. <strong>Default:</strong>: <code>null</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 upon success with an object with two properties:
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of bytes read</li>
<li><code>buffer</code> <a href="#all_buffer_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 reference to the passed in <code>buffer</code>
argument.</li>
</ul>
</li>
</ul>
<p>Reads data from the file and stores that in the given buffer.</p>
<p>If the file is not modified concurrently, the end-of-file is reached when the
number of bytes read is zero.</p>
<h5><code>filehandle.readableWebStream([options])</code><span><a class="mark" href="#all_fs_filehandlereadablewebstreamoptions" id="all_fs_filehandlereadablewebstreamoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_readablewebstream_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>v20.0.0</td>
<td><p>Added option to create a 'bytes' stream.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p><span>Added in: v17.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p>
<ul>
<li><code>type</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#Undefined_type" class="type"><undefined></a> Whether to open a normal or a <code>'bytes'</code> stream.
<strong>Default:</strong> <code>undefined</code></li>
</ul>
</li>
<li>
<p>Returns: <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a></p>
</li>
</ul>
<p>Returns a <code>ReadableStream</code> that may be used to read the files data.</p>
<p>An error will be thrown if this method is called more than once or is called
after the <code>FileHandle</code> is closed or closing.</p>
<pre class="with-8-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> {
open,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">const</span> file = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'./some/file/to/read'</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> file.<span class="hljs-title function_">readableWebStream</span>())
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
<span class="hljs-keyword">await</span> file.<span class="hljs-title function_">close</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
open,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">const</span> file = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'./some/file/to/read'</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> file.<span class="hljs-title function_">readableWebStream</span>())
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
<span class="hljs-keyword">await</span> file.<span class="hljs-title function_">close</span>();
})();</code><button class="copy-button">copy</button></pre>
<p>While the <code>ReadableStream</code> will read the file to completion, it will not
close the <code>FileHandle</code> automatically. User code must still call the
<code>fileHandle.close()</code> method.</p>
<h5><code>filehandle.readFile(options)</code><span><a class="mark" href="#all_fs_filehandlereadfileoptions" id="all_fs_filehandlereadfileoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_readfile_options"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.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 href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows aborting an in-progress readFile</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 upon a successful read with the contents of the
file. If no encoding is specified (using <code>options.encoding</code>), the data is
returned as a <a href="#all_buffer_class-buffer" class="type"><Buffer></a> object. Otherwise, the data will be a string.</li>
</ul>
<p>Asynchronously reads the entire contents of a file.</p>
<p>If <code>options</code> is a string, then it specifies the <code>encoding</code>.</p>
<p>The <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> has to support reading.</p>
<p>If one or more <code>filehandle.read()</code> calls are made on a file handle and then a
<code>filehandle.readFile()</code> call is made, the data will be read from the current
position till the end of the file. It doesn't always read from the beginning
of the file.</p>
<h5><code>filehandle.readLines([options])</code><span><a class="mark" href="#all_fs_filehandlereadlinesoptions" id="all_fs_filehandlereadlinesoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_readlines_options"></a></h5>
<div class="api_metadata">
<span>Added in: v18.11.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>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>null</code></li>
<li><code>autoClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</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> <strong>Default:</strong> <code>true</code></li>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>Infinity</code></li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>64 * 1024</code></li>
</ul>
</li>
<li>Returns: <a href="#all_readline_class-interfaceconstructor" class="type"><readline.InterfaceConstructor></a></li>
</ul>
<p>Convenience method to create a <code>readline</code> interface and stream over the file.
See <a href="#all_fs_filehandlecreatereadstreamoptions"><code>filehandle.createReadStream()</code></a> for the options.</p>
<pre class="with-45-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> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">const</span> file = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'./some/file/to/read'</span>);
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> line <span class="hljs-keyword">of</span> file.<span class="hljs-title function_">readLines</span>()) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(line);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { open } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">const</span> file = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'./some/file/to/read'</span>);
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> line <span class="hljs-keyword">of</span> file.<span class="hljs-title function_">readLines</span>()) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(line);
}
})();</code><button class="copy-button">copy</button></pre>
<h5><code>filehandle.readv(buffers[, position])</code><span><a class="mark" href="#all_fs_filehandlereadvbuffers-position" id="all_fs_filehandlereadvbuffers-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_readv_buffers_position"></a></h5>
<div class="api_metadata">
<span>Added in: v13.13.0, v12.17.0</span>
</div>
<ul>
<li><code>buffers</code> <a href="#all_buffer_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></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The offset from the beginning of the file where
the data should be read from. If <code>position</code> is not a <code>number</code>, the data will
be read from the current position. <strong>Default:</strong> <code>null</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills upon success an object containing two properties:
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> the number of bytes read</li>
<li><code>buffers</code> <a href="#all_buffer_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> property containing
a reference to the <code>buffers</code> input.</li>
</ul>
</li>
</ul>
<p>Read from a file and write to an array of <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type"><ArrayBufferView></a>s</p>
<h5><code>filehandle.stat([options])</code><span><a class="mark" href="#all_fs_filehandlestatoptions" id="all_fs_filehandlestatoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_stat_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>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned
<a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object should be <code>bigint</code>. <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 with an <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> for the file.</li>
</ul>
<h5><code>filehandle.sync()</code><span><a class="mark" href="#all_fs_filehandlesync" id="all_fs_filehandlesync">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_sync"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Request that all data for the open file descriptor is flushed to the storage
device. The specific implementation is operating system and device specific.
Refer to the POSIX <a href="http://man7.org/linux/man-pages/man2/fsync.2.html"><code>fsync(2)</code></a> documentation for more detail.</p>
<h5><code>filehandle.truncate(len)</code><span><a class="mark" href="#all_fs_filehandletruncatelen" id="all_fs_filehandletruncatelen">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_truncate_len"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Truncates the file.</p>
<p>If the file was larger than <code>len</code> bytes, only the first <code>len</code> bytes will be
retained in the file.</p>
<p>The following example retains only the first four bytes of the file:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">let</span> filehandle = <span class="hljs-literal">null</span>;
<span class="hljs-keyword">try</span> {
filehandle = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'temp.txt'</span>, <span class="hljs-string">'r+'</span>);
<span class="hljs-keyword">await</span> filehandle.<span class="hljs-title function_">truncate</span>(<span class="hljs-number">4</span>);
} <span class="hljs-keyword">finally</span> {
<span class="hljs-keyword">await</span> filehandle?.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<p>If the file previously was shorter than <code>len</code> bytes, it is extended, and the
extended part is filled with null bytes (<code>'\0'</code>):</p>
<p>If <code>len</code> is negative then <code>0</code> will be used.</p>
<h5><code>filehandle.utimes(atime, mtime)</code><span><a class="mark" href="#all_fs_filehandleutimesatime-mtime" id="all_fs_filehandleutimesatime-mtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_utimes_atime_mtime"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Change the file system timestamps of the object referenced by the <a href="#all_fs_class-filehandle" class="type"><FileHandle></a>
then fulfills the promise with no arguments upon success.</p>
<h5><code>filehandle.write(buffer, offset[, length[, position]])</code><span><a class="mark" href="#all_fs_filehandlewritebuffer-offset-length-position" id="all_fs_filehandlewritebuffer-offset-length-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_write_buffer_offset_length_position"></a></h5>
<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>The <code>buffer</code> parameter won't coerce unsupported input to buffers anymore.</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>buffer</code> <a href="#all_buffer_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></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The start position from within <code>buffer</code> where the data
to write begins.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of bytes from <code>buffer</code> to write. <strong>Default:</strong>
<code>buffer.byteLength - offset</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The offset from the beginning of the file where the
data from <code>buffer</code> should be written. If <code>position</code> is not a <code>number</code>,
the data will be written at the current position. See the POSIX <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>
documentation for more detail. <strong>Default:</strong> <code>null</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Write <code>buffer</code> to the file.</p>
<p>The promise is fulfilled with an object containing two properties:</p>
<ul>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> the number of bytes written</li>
<li><code>buffer</code> <a href="#all_buffer_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 reference to the
<code>buffer</code> written.</li>
</ul>
<p>It is unsafe to use <code>filehandle.write()</code> multiple times on the same file
without waiting for the promise to be fulfilled (or rejected). For this
scenario, use <a href="#all_fs_filehandlecreatewritestreamoptions"><code>filehandle.createWriteStream()</code></a>.</p>
<p>On Linux, positional writes do not work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.</p>
<h5><code>filehandle.write(buffer[, options])</code><span><a class="mark" href="#all_fs_filehandlewritebuffer-options" id="all_fs_filehandlewritebuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_write_buffer_options"></a></h5>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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></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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>buffer.byteLength - offset</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>null</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></li>
</ul>
<p>Write <code>buffer</code> to the file.</p>
<p>Similar to the above <code>filehandle.write</code> function, this version takes an
optional <code>options</code> object. If no <code>options</code> object is specified, it will
default with the above values.</p>
<h5><code>filehandle.write(string[, position[, encoding]])</code><span><a class="mark" href="#all_fs_filehandlewritestring-position-encoding" id="all_fs_filehandlewritestring-position-encoding">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_write_string_position_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>v14.0.0</td>
<td><p>The <code>string</code> parameter won't coerce unsupported input to strings anymore.</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>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The offset from the beginning of the file where the
data from <code>string</code> should be written. If <code>position</code> is not a <code>number</code> the
data will be written at the current position. See the POSIX <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>
documentation for more detail. <strong>Default:</strong> <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 expected string encoding. <strong>Default:</strong> <code>'utf8'</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Write <code>string</code> to the file. If <code>string</code> is not a string, the promise is
rejected with an error.</p>
<p>The promise is fulfilled with an object containing two properties:</p>
<ul>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> the number of bytes written</li>
<li><code>buffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> a reference to the <code>string</code> written.</li>
</ul>
<p>It is unsafe to use <code>filehandle.write()</code> multiple times on the same file
without waiting for the promise to be fulfilled (or rejected). For this
scenario, use <a href="#all_fs_filehandlecreatewritestreamoptions"><code>filehandle.createWriteStream()</code></a>.</p>
<p>On Linux, positional writes do not work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.</p>
<h5><code>filehandle.writeFile(data, options)</code><span><a class="mark" href="#all_fs_filehandlewritefiledata-options" id="all_fs_filehandlewritefiledata-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_writefile_data_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>v15.14.0, v14.18.0</td>
<td><p>The <code>data</code> argument supports <code>AsyncIterable</code>, <code>Iterable</code>, and <code>Stream</code>.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>data</code> parameter won't coerce unsupported input to strings anymore.</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>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="#all_stream_stream" class="type"><Stream></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The expected character encoding when <code>data</code> is a
string. <strong>Default:</strong> <code>'utf8'</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></li>
</ul>
<p>Asynchronously writes data to a file, replacing the file if it already exists.
<code>data</code> can be a string, a buffer, an <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a>, or an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> object.
The promise is fulfilled with no arguments upon success.</p>
<p>If <code>options</code> is a string, then it specifies the <code>encoding</code>.</p>
<p>The <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> has to support writing.</p>
<p>It is unsafe to use <code>filehandle.writeFile()</code> multiple times on the same file
without waiting for the promise to be fulfilled (or rejected).</p>
<p>If one or more <code>filehandle.write()</code> calls are made on a file handle and then a
<code>filehandle.writeFile()</code> call is made, the data will be written from the
current position till the end of the file. It doesn't always write from the
beginning of the file.</p>
<h5><code>filehandle.writev(buffers[, position])</code><span><a class="mark" href="#all_fs_filehandlewritevbuffers-position" id="all_fs_filehandlewritevbuffers-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_writev_buffers_position"></a></h5>
<div class="api_metadata">
<span>Added in: v12.9.0</span>
</div>
<ul>
<li><code>buffers</code> <a href="#all_buffer_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></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The offset from the beginning of the file where the
data from <code>buffers</code> should be written. If <code>position</code> is not a <code>number</code>,
the data will be written at the current position. <strong>Default:</strong> <code>null</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Write an array of <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type"><ArrayBufferView></a>s to the file.</p>
<p>The promise is fulfilled with an object containing a two properties:</p>
<ul>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> the number of bytes written</li>
<li><code>buffers</code> <a href="#all_buffer_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 reference to the <code>buffers</code>
input.</li>
</ul>
<p>It is unsafe to call <code>writev()</code> multiple times on the same file without waiting
for the promise to be fulfilled (or rejected).</p>
<p>On Linux, positional writes don't work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.</p>
<h5><code>filehandle[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_fs_filehandlesymbolasyncdispose" id="all_fs_filehandlesymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_symbol_asyncdispose"></a></h5>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>An alias for <code>filehandle.close()</code>.</p>
<h4><code>fsPromises.access(path[, mode])</code><span><a class="mark" href="#all_fs_fspromisesaccesspath-mode" id="all_fs_fspromisesaccesspath-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_access_path_mode"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>fs.constants.F_OK</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Tests a user's permissions for the file or directory specified by <code>path</code>.
The <code>mode</code> argument is an optional integer that specifies the accessibility
checks to be performed. <code>mode</code> should be either the value <code>fs.constants.F_OK</code>
or a mask consisting of the bitwise OR of any of <code>fs.constants.R_OK</code>,
<code>fs.constants.W_OK</code>, and <code>fs.constants.X_OK</code> (e.g.
<code>fs.constants.W_OK | fs.constants.R_OK</code>). Check <a href="#all_fs_file-access-constants">File access constants</a> for
possible values of <code>mode</code>.</p>
<p>If the accessibility check is successful, the promise is fulfilled with no
value. If any of the accessibility checks fail, the promise is rejected
with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> object. The following example checks if the file
<code>/etc/passwd</code> can be read and written by the current process.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { access, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">access</span>(<span class="hljs-string">'/etc/passwd'</span>, constants.<span class="hljs-property">R_OK</span> | constants.<span class="hljs-property">W_OK</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'can access'</span>);
} <span class="hljs-keyword">catch</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'cannot access'</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>Using <code>fsPromises.access()</code> to check for the accessibility of a file before
calling <code>fsPromises.open()</code> is not recommended. Doing so introduces a race
condition, since other processes may change the file's state between the two
calls. Instead, user code should open/read/write the file directly and handle
the error raised if the file is not accessible.</p>
<h4><code>fsPromises.appendFile(path, data[, options])</code><span><a class="mark" href="#all_fs_fspromisesappendfilepath-data-options" id="all_fs_fspromisesappendfilepath-data-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_appendfile_path_data_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>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</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>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> filename or <a href="#all_fs_class-filehandle" class="type"><FileHandle></a></li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the underlying file descriptor is flushed
prior to closing it. <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 with <code>undefined</code> upon success.</li>
</ul>
<p>Asynchronously append data to a file, creating the file if it does not yet
exist. <code>data</code> can be a string or a <a href="#all_buffer_class-buffer" class="type"><Buffer></a>.</p>
<p>If <code>options</code> is a string, then it specifies the <code>encoding</code>.</p>
<p>The <code>mode</code> option only affects the newly created file. See <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>
for more details.</p>
<p>The <code>path</code> may be specified as a <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> that has been opened
for appending (using <code>fsPromises.open()</code>).</p>
<h4><code>fsPromises.chmod(path, mode)</code><span><a class="mark" href="#all_fs_fspromiseschmodpath-mode" id="all_fs_fspromiseschmodpath-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_chmod_path_mode"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>mode</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#Number_type" class="type"><integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Changes the permissions of a file.</p>
<h4><code>fsPromises.chown(path, uid, gid)</code><span><a class="mark" href="#all_fs_fspromiseschownpath-uid-gid" id="all_fs_fspromiseschownpath-uid-gid">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_chown_path_uid_gid"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Changes the ownership of a file.</p>
<h4><code>fsPromises.copyFile(src, dest[, mode])</code><span><a class="mark" href="#all_fs_fspromisescopyfilesrc-dest-mode" id="all_fs_fspromisescopyfilesrc-dest-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_copyfile_src_dest_mode"></a></h4>
<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>Changed <code>flags</code> argument to <code>mode</code> and imposed stricter type validation.</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>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> source filename to copy</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> destination filename of the copy operation</li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Optional modifiers that specify the behavior of the copy
operation. It is possible to create a mask consisting of the bitwise OR of
two or more values (e.g.
<code>fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE</code>)
<strong>Default:</strong> <code>0</code>.
<ul>
<li><code>fs.constants.COPYFILE_EXCL</code>: The copy operation will fail if <code>dest</code>
already exists.</li>
<li><code>fs.constants.COPYFILE_FICLONE</code>: The copy operation will attempt to create
a copy-on-write reflink. If the platform does not support copy-on-write,
then a fallback copy mechanism is used.</li>
<li><code>fs.constants.COPYFILE_FICLONE_FORCE</code>: The copy operation will attempt to
create a copy-on-write reflink. If the platform does not support
copy-on-write, then the operation will fail.</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 with <code>undefined</code> upon success.</li>
</ul>
<p>Asynchronously copies <code>src</code> to <code>dest</code>. By default, <code>dest</code> is overwritten if it
already exists.</p>
<p>No guarantees are made about the atomicity of the copy operation. If an
error occurs after the destination file has been opened for writing, an attempt
will be made to remove the destination.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { copyFile, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">copyFile</span>(<span class="hljs-string">'source.txt'</span>, <span class="hljs-string">'destination.txt'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'source.txt was copied to destination.txt'</span>);
} <span class="hljs-keyword">catch</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'The file could not be copied'</span>);
}
<span class="hljs-comment">// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.</span>
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">copyFile</span>(<span class="hljs-string">'source.txt'</span>, <span class="hljs-string">'destination.txt'</span>, constants.<span class="hljs-property">COPYFILE_EXCL</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'source.txt was copied to destination.txt'</span>);
} <span class="hljs-keyword">catch</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'The file could not be copied'</span>);
}</code> <button class="copy-button">copy</button></pre>
<h4><code>fsPromises.cp(src, dest[, options])</code><span><a class="mark" href="#all_fs_fspromisescpsrc-dest-options" id="all_fs_fspromisescpsrc-dest-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_cp_src_dest_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>v20.1.0</td>
<td><p>Accept an additional <code>mode</code> option to specify the copy behavior as the <code>mode</code> argument of <code>fs.copyFile()</code>.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p>Accepts an additional <code>verbatimSymlinks</code> option to specify whether to perform path resolution for symlinks.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> source path to copy.</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> destination path to copy to.</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>dereference</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> dereference symlinks. <strong>Default:</strong> <code>false</code>.</li>
<li><code>errorOnExist</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> when <code>force</code> is <code>false</code>, and the destination
exists, throw an error. <strong>Default:</strong> <code>false</code>.</li>
<li><code>filter</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Function to filter copied files/directories. Return
<code>true</code> to copy the item, <code>false</code> to ignore it. When ignoring a directory,
all of its contents will be skipped as well. Can also return a <code>Promise</code>
that resolves to <code>true</code> or <code>false</code> <strong>Default:</strong> <code>undefined</code>.
<ul>
<li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> source path to copy.</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> destination path to copy to.</li>
<li>Returns: <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/Reference/Global_Objects/Promise" class="type"><Promise></a> A value that is coercible to <code>boolean</code> or
a <code>Promise</code> that fulfils with such value.</li>
</ul>
</li>
<li><code>force</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> overwrite existing file or directory. The copy
operation will ignore errors if you set this to false and the destination
exists. Use the <code>errorOnExist</code> option to change this behavior.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> modifiers for copy operation. <strong>Default:</strong> <code>0</code>.
See <code>mode</code> flag of <a href="#all_fs_fspromisescopyfilesrc-dest-mode"><code>fsPromises.copyFile()</code></a>.</li>
<li><code>preserveTimestamps</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> timestamps from <code>src</code> will
be preserved. <strong>Default:</strong> <code>false</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> copy directories recursively <strong>Default:</strong> <code>false</code></li>
<li><code>verbatimSymlinks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, path resolution for symlinks will
be skipped. <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 with <code>undefined</code> upon success.</li>
</ul>
<p>Asynchronously copies the entire directory structure from <code>src</code> to <code>dest</code>,
including subdirectories and files.</p>
<p>When copying a directory to another directory, globs are not supported and
behavior is similar to <code>cp dir1/ dir2/</code>.</p>
<h4><code>fsPromises.lchmod(path, mode)</code><span><a class="mark" href="#all_fs_fspromiseslchmodpath-mode" id="all_fs_fspromiseslchmodpath-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_lchmod_path_mode"></a></h4>
<div class="api_metadata">
<span>Deprecated since: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Changes the permissions on a symbolic link.</p>
<p>This method is only implemented on macOS.</p>
<h4><code>fsPromises.lchown(path, uid, gid)</code><span><a class="mark" href="#all_fs_fspromiseslchownpath-uid-gid" id="all_fs_fspromiseslchownpath-uid-gid">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_lchown_path_uid_gid"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.6.0</td>
<td><p>This API is no longer deprecated.</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>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Changes the ownership on a symbolic link.</p>
<h4><code>fsPromises.lutimes(path, atime, mtime)</code><span><a class="mark" href="#all_fs_fspromiseslutimespath-atime-mtime" id="all_fs_fspromiseslutimespath-atime-mtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_lutimes_path_atime_mtime"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Changes the access and modification times of a file in the same way as
<a href="#all_fs_fspromisesutimespath-atime-mtime"><code>fsPromises.utimes()</code></a>, with the difference that if the path refers to a
symbolic link, then the link is not dereferenced: instead, the timestamps of
the symbolic link itself are changed.</p>
<h4><code>fsPromises.link(existingPath, newPath)</code><span><a class="mark" href="#all_fs_fspromiseslinkexistingpath-newpath" id="all_fs_fspromiseslinkexistingpath-newpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_link_existingpath_newpath"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>existingPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Creates a new link from the <code>existingPath</code> to the <code>newPath</code>. See the POSIX
<a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a> documentation for more detail.</p>
<h4><code>fsPromises.lstat(path[, options])</code><span><a class="mark" href="#all_fs_fspromiseslstatpath-options" id="all_fs_fspromiseslstatpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_lstat_path_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>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</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>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned
<a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object should be <code>bigint</code>. <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 with the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object for the given
symbolic link <code>path</code>.</li>
</ul>
<p>Equivalent to <a href="#all_fs_fspromisesstatpath-options"><code>fsPromises.stat()</code></a> unless <code>path</code> refers to a symbolic link,
in which case the link itself is stat-ed, not the file that it refers to.
Refer to the POSIX <a href="http://man7.org/linux/man-pages/man2/lstat.2.html"><code>lstat(2)</code></a> document for more detail.</p>
<h4><code>fsPromises.mkdir(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesmkdirpath-options" id="all_fs_fspromisesmkdirpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_mkdir_path_options"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a>
<ul>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>mode</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#Number_type" class="type"><integer></a> Not supported on Windows. <strong>Default:</strong> <code>0o777</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> Upon success, fulfills with <code>undefined</code> if <code>recursive</code>
is <code>false</code>, or the first directory path created if <code>recursive</code> is <code>true</code>.</li>
</ul>
<p>Asynchronously creates a directory.</p>
<p>The optional <code>options</code> argument can be an integer specifying <code>mode</code> (permission
and sticky bits), or an object with a <code>mode</code> property and a <code>recursive</code>
property indicating whether parent directories should be created. Calling
<code>fsPromises.mkdir()</code> when <code>path</code> is a directory that exists results in a
rejection only when <code>recursive</code> is false.</p>
<pre class="with-46-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> { mkdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> projectFolder = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'./test/project/'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
<span class="hljs-keyword">const</span> createDir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">mkdir</span>(projectFolder, { <span class="hljs-attr">recursive</span>: <span class="hljs-literal">true</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`created <span class="hljs-subst">${createDir}</span>`</span>);
} <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-property">message</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { mkdir } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);
<span class="hljs-keyword">const</span> { join } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">makeDirectory</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> projectFolder = <span class="hljs-title function_">join</span>(__dirname, <span class="hljs-string">'test'</span>, <span class="hljs-string">'project'</span>);
<span class="hljs-keyword">const</span> dirCreation = <span class="hljs-keyword">await</span> <span class="hljs-title function_">mkdir</span>(projectFolder, { <span class="hljs-attr">recursive</span>: <span class="hljs-literal">true</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(dirCreation);
<span class="hljs-keyword">return</span> dirCreation;
}
<span class="hljs-title function_">makeDirectory</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>
<h4><code>fsPromises.mkdtemp(prefix[, options])</code><span><a class="mark" href="#all_fs_fspromisesmkdtempprefix-options" id="all_fs_fspromisesmkdtempprefix-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_mkdtemp_prefix_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>v20.6.0</td>
<td><p>The <code>prefix</code> parameter now accepts buffers and URL.</p></td></tr>
<tr><td>v16.5.0, v14.18.0</td>
<td><p>The <code>prefix</code> parameter now accepts an empty string.</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>prefix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</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 with a string containing the file system path
of the newly created temporary directory.</li>
</ul>
<p>Creates a unique temporary directory. A unique directory name is generated by
appending six random characters to the end of the provided <code>prefix</code>. Due to
platform inconsistencies, avoid trailing <code>X</code> characters in <code>prefix</code>. Some
platforms, notably the BSDs, can return more than six random characters, and
replace trailing <code>X</code> characters in <code>prefix</code> with random characters.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { mkdtemp } <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">import</span> { tmpdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">mkdtemp</span>(<span class="hljs-title function_">join</span>(<span class="hljs-title function_">tmpdir</span>(), <span class="hljs-string">'foo-'</span>));
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}</code> <button class="copy-button">copy</button></pre>
<p>The <code>fsPromises.mkdtemp()</code> method will append the six randomly selected
characters directly to the <code>prefix</code> string. For instance, given a directory
<code>/tmp</code>, if the intention is to create a temporary directory <em>within</em> <code>/tmp</code>, the
<code>prefix</code> must end with a trailing platform-specific path separator
(<code>require('node:path').sep</code>).</p>
<h4><code>fsPromises.open(path, flags[, mode])</code><span><a class="mark" href="#all_fs_fspromisesopenpath-flags-mode" id="all_fs_fspromisesopenpath-flags-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_open_path_flags_mode"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.1.0</td>
<td><p>The <code>flags</code> argument is now optional and defaults to <code>'r'</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>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>flags</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#Number_type" class="type"><number></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>.
<strong>Default:</strong> <code>'r'</code>.</li>
<li><code>mode</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#Number_type" class="type"><integer></a> Sets the file mode (permission and sticky bits)
if the file is created. <strong>Default:</strong> <code>0o666</code> (readable and writable)</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with a <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> object.</li>
</ul>
<p>Opens a <a href="#all_fs_class-filehandle" class="type"><FileHandle></a>.</p>
<p>Refer to the POSIX <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a> documentation for more detail.</p>
<p>Some characters (<code>< > : " / \ | ? *</code>) are reserved under Windows as documented
by <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file">Naming Files, Paths, and Namespaces</a>. Under NTFS, if the filename contains
a colon, Node.js will open a file system stream, as described by
<a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams">this MSDN page</a>.</p>
<h4><code>fsPromises.opendir(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesopendirpath-options" id="all_fs_fspromisesopendirpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_opendir_path_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>v20.1.0</td>
<td><p>Added <code>recursive</code> option.</p></td></tr>
<tr><td>v13.1.0, v12.16.0</td>
<td><p>The <code>bufferSize</code> option was introduced.</p></td></tr>
<tr><td>v12.12.0</td>
<td><p><span>Added in: v12.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>bufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of directory entries that are buffered
internally when reading from the directory. Higher values lead to better
performance but higher memory usage. <strong>Default:</strong> <code>32</code></li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Resolved <code>Dir</code> will be an <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a>
containing all sub files and directories. <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 with an <a href="#all_fs_class-fsdir" class="type"><fs.Dir></a>.</li>
</ul>
<p>Asynchronously open a directory for iterative scanning. See the POSIX
<a href="http://man7.org/linux/man-pages/man3/opendir.3.html"><code>opendir(3)</code></a> documentation for more detail.</p>
<p>Creates an <a href="#all_fs_class-fsdir" class="type"><fs.Dir></a>, which contains all further functions for reading from
and cleaning up the directory.</p>
<p>The <code>encoding</code> option sets the encoding for the <code>path</code> while opening the
directory and subsequent read operations.</p>
<p>Example using async iteration:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { opendir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> dir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">opendir</span>(<span class="hljs-string">'./'</span>);
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> dirent <span class="hljs-keyword">of</span> dir)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(dirent.<span class="hljs-property">name</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}</code> <button class="copy-button">copy</button></pre>
<p>When using the async iterator, the <a href="#all_fs_class-fsdir" class="type"><fs.Dir></a> object will be automatically
closed after the iterator exits.</p>
<h4><code>fsPromises.readdir(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesreaddirpath-options" id="all_fs_fspromisesreaddirpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_readdir_path_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>v20.1.0</td>
<td><p>Added <code>recursive</code> option.</p></td></tr>
<tr><td>v10.11.0</td>
<td><p>New option <code>withFileTypes</code> was added.</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>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>withFileTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, reads the contents of a directory
recursively. In recursive mode, it will list all files, sub files, and
directories. <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 with an array of the names of the files in
the directory excluding <code>'.'</code> and <code>'..'</code>.</li>
</ul>
<p>Reads the contents of a directory.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the filenames. If the <code>encoding</code> is set to <code>'buffer'</code>, the filenames returned
will be passed as <a href="#all_buffer_class-buffer" class="type"><Buffer></a> objects.</p>
<p>If <code>options.withFileTypes</code> is set to <code>true</code>, the returned array will contain
<a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> objects.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> files = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readdir</span>(path);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> file <span class="hljs-keyword">of</span> files)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(file);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}</code> <button class="copy-button">copy</button></pre>
<h4><code>fsPromises.readFile(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesreadfilepath-options" id="all_fs_fspromisesreadfilepath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_readfile_path_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>v15.2.0, v14.17.0</td>
<td><p>The options argument may include an AbortSignal to abort an ongoing readFile request.</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>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> filename or <code>FileHandle</code></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows aborting an in-progress readFile</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 with the contents of the file.</li>
</ul>
<p>Asynchronously reads the entire contents of a file.</p>
<p>If no encoding is specified (using <code>options.encoding</code>), the data is returned
as a <a href="#all_buffer_class-buffer" class="type"><Buffer></a> object. Otherwise, the data will be a string.</p>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<p>When the <code>path</code> is a directory, the behavior of <code>fsPromises.readFile()</code> is
platform-specific. On macOS, Linux, and Windows, the promise will be rejected
with an error. On FreeBSD, a representation of the directory's contents will be
returned.</p>
<p>An example of reading a <code>package.json</code> file located in the same directory of the
running code:</p>
<pre class="with-49-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> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> filePath = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'./package.json'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
<span class="hljs-keyword">const</span> contents = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(filePath, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contents);
} <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-property">message</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { readFile } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);
<span class="hljs-keyword">const</span> { resolve } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">logFile</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> filePath = <span class="hljs-title function_">resolve</span>(<span class="hljs-string">'./package.json'</span>);
<span class="hljs-keyword">const</span> contents = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(filePath, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contents);
} <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-property">message</span>);
}
}
<span class="hljs-title function_">logFile</span>();</code><button class="copy-button">copy</button></pre>
<p>It is possible to abort an ongoing <code>readFile</code> using an <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a>. If a
request is aborted the promise returned is rejected with an <code>AbortError</code>:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">try</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> { signal } = controller;
<span class="hljs-keyword">const</span> promise = <span class="hljs-title function_">readFile</span>(fileName, { signal });
<span class="hljs-comment">// Abort the request before the promise settles.</span>
controller.<span class="hljs-title function_">abort</span>();
<span class="hljs-keyword">await</span> promise;
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-comment">// When a request is aborted - err is an AbortError</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}</code> <button class="copy-button">copy</button></pre>
<p>Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering <code>fs.readFile</code> performs.</p>
<p>Any specified <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> has to support reading.</p>
<h4><code>fsPromises.readlink(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesreadlinkpath-options" id="all_fs_fspromisesreadlinkpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_readlink_path_options"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</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 with the <code>linkString</code> upon success.</li>
</ul>
<p>Reads the contents of the symbolic link referred to by <code>path</code>. See the POSIX
<a href="http://man7.org/linux/man-pages/man2/readlink.2.html"><code>readlink(2)</code></a> documentation for more detail. The promise is fulfilled with the
<code>linkString</code> upon success.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the link path returned. If the <code>encoding</code> is set to <code>'buffer'</code>, the link path
returned will be passed as a <a href="#all_buffer_class-buffer" class="type"><Buffer></a> object.</p>
<h4><code>fsPromises.realpath(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesrealpathpath-options" id="all_fs_fspromisesrealpathpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_realpath_path_options"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</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 with the resolved path upon success.</li>
</ul>
<p>Determines the actual location of <code>path</code> using the same semantics as the
<code>fs.realpath.native()</code> function.</p>
<p>Only paths that can be converted to UTF8 strings are supported.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the path. If the <code>encoding</code> is set to <code>'buffer'</code>, the path returned will be
passed as a <a href="#all_buffer_class-buffer" class="type"><Buffer></a> object.</p>
<p>On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on <code>/proc</code> in order for this function to work. Glibc does not have
this restriction.</p>
<h4><code>fsPromises.rename(oldPath, newPath)</code><span><a class="mark" href="#all_fs_fspromisesrenameoldpath-newpath" id="all_fs_fspromisesrenameoldpath-newpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_rename_oldpath_newpath"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>oldPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Renames <code>oldPath</code> to <code>newPath</code>.</p>
<h4><code>fsPromises.rmdir(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesrmdirpath-options" id="all_fs_fspromisesrmdirpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_rmdir_path_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>v16.0.0</td>
<td><p>Using <code>fsPromises.rmdir(path, { recursive: true })</code> on a <code>path</code> that is a file is no longer permitted and results in an <code>ENOENT</code> error on Windows and an <code>ENOTDIR</code> error on POSIX.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Using <code>fsPromises.rmdir(path, { recursive: true })</code> on a <code>path</code> that does not exist is no longer permitted and results in a <code>ENOENT</code> error.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>The <code>recursive</code> option is deprecated, using it triggers a deprecation warning.</p></td></tr>
<tr><td>v14.14.0</td>
<td><p>The <code>recursive</code> option is deprecated, use <code>fsPromises.rm</code> instead.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p>The <code>maxBusyTries</code> option is renamed to <code>maxRetries</code>, and its default is 0. The <code>emfileWait</code> option has been removed, and <code>EMFILE</code> errors use the same retry logic as other errors. The <code>retryDelay</code> option is now supported. <code>ENFILE</code> errors are now retried.</p></td></tr>
<tr><td>v12.10.0</td>
<td><p>The <code>recursive</code>, <code>maxBusyTries</code>, and <code>emfileWait</code> options are now supported.</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>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>maxRetries</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> If an <code>EBUSY</code>, <code>EMFILE</code>, <code>ENFILE</code>, <code>ENOTEMPTY</code>, or
<code>EPERM</code> error is encountered, Node.js retries the operation with a linear
backoff wait of <code>retryDelay</code> milliseconds longer on each try. This option
represents the number of retries. This option is ignored if the <code>recursive</code>
option is not <code>true</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, perform a recursive directory removal. In
recursive mode, operations are retried on failure. <strong>Default:</strong> <code>false</code>.
<strong>Deprecated.</strong></li>
<li><code>retryDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The amount of time in milliseconds to wait between
retries. This option is ignored if the <code>recursive</code> option is not <code>true</code>.
<strong>Default:</strong> <code>100</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 with <code>undefined</code> upon success.</li>
</ul>
<p>Removes the directory identified by <code>path</code>.</p>
<p>Using <code>fsPromises.rmdir()</code> on a file (not a directory) results in the
promise being rejected with an <code>ENOENT</code> error on Windows and an <code>ENOTDIR</code>
error on POSIX.</p>
<p>To get a behavior similar to the <code>rm -rf</code> Unix command, use
<a href="#all_fs_fspromisesrmpath-options"><code>fsPromises.rm()</code></a> with options <code>{ recursive: true, force: true }</code>.</p>
<h4><code>fsPromises.rm(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesrmpath-options" id="all_fs_fspromisesrmpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_rm_path_options"></a></h4>
<div class="api_metadata">
<span>Added in: v14.14.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>force</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, exceptions will be ignored if <code>path</code> does
not exist. <strong>Default:</strong> <code>false</code>.</li>
<li><code>maxRetries</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> If an <code>EBUSY</code>, <code>EMFILE</code>, <code>ENFILE</code>, <code>ENOTEMPTY</code>, or
<code>EPERM</code> error is encountered, Node.js will retry the operation with a linear
backoff wait of <code>retryDelay</code> milliseconds longer on each try. This option
represents the number of retries. This option is ignored if the <code>recursive</code>
option is not <code>true</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, perform a recursive directory removal. In
recursive mode operations are retried on failure. <strong>Default:</strong> <code>false</code>.</li>
<li><code>retryDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The amount of time in milliseconds to wait between
retries. This option is ignored if the <code>recursive</code> option is not <code>true</code>.
<strong>Default:</strong> <code>100</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 with <code>undefined</code> upon success.</li>
</ul>
<p>Removes files and directories (modeled on the standard POSIX <code>rm</code> utility).</p>
<h4><code>fsPromises.stat(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesstatpath-options" id="all_fs_fspromisesstatpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_stat_path_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>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</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>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned
<a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object should be <code>bigint</code>. <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 with the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object for the
given <code>path</code>.</li>
</ul>
<h4><code>fsPromises.statfs(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesstatfspath-options" id="all_fs_fspromisesstatfspath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_statfs_path_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned
<a href="#all_fs_class-fsstatfs" class="type"><fs.StatFs></a> object should be <code>bigint</code>. <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 with the <a href="#all_fs_class-fsstatfs" class="type"><fs.StatFs></a> object for the
given <code>path</code>.</li>
</ul>
<h4><code>fsPromises.symlink(target, path[, type])</code><span><a class="mark" href="#all_fs_fspromisessymlinktarget-path-type" id="all_fs_fspromisessymlinktarget-path-type">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_symlink_target_path_type"></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.0.0</td>
<td><p>If the <code>type</code> argument is <code>null</code> or omitted, Node.js will autodetect <code>target</code> type and automatically select <code>dir</code> or <code>file</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>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>type</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> <strong>Default:</strong> <code>null</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Creates a symbolic link.</p>
<p>The <code>type</code> argument is only used on Windows platforms and can be one of <code>'dir'</code>,
<code>'file'</code>, or <code>'junction'</code>. If the <code>type</code> argument is not a string, Node.js will
autodetect <code>target</code> type and use <code>'file'</code> or <code>'dir'</code>. If the <code>target</code> does not
exist, <code>'file'</code> will be used. Windows junction points require the destination
path to be absolute. When using <code>'junction'</code>, the <code>target</code> argument will
automatically be normalized to absolute path. Junction points on NTFS volumes
can only point to directories.</p>
<h4><code>fsPromises.truncate(path[, len])</code><span><a class="mark" href="#all_fs_fspromisestruncatepath-len" id="all_fs_fspromisestruncatepath-len">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_truncate_path_len"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Truncates (shortens or extends the length) of the content at <code>path</code> to <code>len</code>
bytes.</p>
<h4><code>fsPromises.unlink(path)</code><span><a class="mark" href="#all_fs_fspromisesunlinkpath" id="all_fs_fspromisesunlinkpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_unlink_path"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>If <code>path</code> refers to a symbolic link, then the link is removed without affecting
the file or directory to which that link refers. If the <code>path</code> refers to a file
path that is not a symbolic link, the file is deleted. See the POSIX <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a>
documentation for more detail.</p>
<h4><code>fsPromises.utimes(path, atime, mtime)</code><span><a class="mark" href="#all_fs_fspromisesutimespath-atime-mtime" id="all_fs_fspromisesutimespath-atime-mtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_utimes_path_atime_mtime"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Change the file system timestamps of the object referenced by <code>path</code>.</p>
<p>The <code>atime</code> and <code>mtime</code> arguments follow these rules:</p>
<ul>
<li>Values can be either numbers representing Unix epoch time, <code>Date</code>s, or a
numeric string like <code>'123456789.0'</code>.</li>
<li>If the value can not be converted to a number, or is <code>NaN</code>, <code>Infinity</code>, or
<code>-Infinity</code>, an <code>Error</code> will be thrown.</li>
</ul>
<h4><code>fsPromises.watch(filename[, options])</code><span><a class="mark" href="#all_fs_fspromiseswatchfilename-options" id="all_fs_fspromiseswatchfilename-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_watch_filename_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0, v14.18.0</span>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>persistent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether the process should continue to run
as long as files are being watched. <strong>Default:</strong> <code>true</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether all subdirectories should be
watched, or only the current directory. This applies when a directory is
specified, and only on supported platforms (See <a href="#all_fs_caveats">caveats</a>). <strong>Default:</strong>
<code>false</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> Specifies the character encoding to be used for the
filename passed to the listener. <strong>Default:</strong> <code>'utf8'</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> An <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> used to signal when the watcher
should stop.</li>
</ul>
</li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a> of objects with the properties:
<ul>
<li><code>eventType</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The type of change</li>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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> The name of the file changed.</li>
</ul>
</li>
</ul>
<p>Returns an async iterator that watches for changes on <code>filename</code>, where <code>filename</code>
is either a file or a directory.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { watch } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</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-built_in">setTimeout</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>(), <span class="hljs-number">10000</span>);
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> watcher = <span class="hljs-title function_">watch</span>(__filename, { signal });
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> watcher)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>)
<span class="hljs-keyword">return</span>;
<span class="hljs-keyword">throw</span> err;
}
})();</code> <button class="copy-button">copy</button></pre>
<p>On most platforms, <code>'rename'</code> is emitted whenever a filename appears or
disappears in the directory.</p>
<p>All the <a href="#all_fs_caveats">caveats</a> for <code>fs.watch()</code> also apply to <code>fsPromises.watch()</code>.</p>
<h4><code>fsPromises.writeFile(file, data[, options])</code><span><a class="mark" href="#all_fs_fspromiseswritefilefile-data-options" id="all_fs_fspromiseswritefilefile-data-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_writefile_file_data_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>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v15.14.0, v14.18.0</td>
<td><p>The <code>data</code> argument supports <code>AsyncIterable</code>, <code>Iterable</code>, and <code>Stream</code>.</p></td></tr>
<tr><td>v15.2.0, v14.17.0</td>
<td><p>The options argument may include an AbortSignal to abort an ongoing writeFile request.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>data</code> parameter won't coerce unsupported input to strings anymore.</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>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> filename or <code>FileHandle</code></li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="#all_stream_stream" class="type"><Stream></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If all data is successfully written to the file, and
<code>flush</code> is <code>true</code>, <code>filehandle.sync()</code> is used to flush the data.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows aborting an in-progress writeFile</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 with <code>undefined</code> upon success.</li>
</ul>
<p>Asynchronously writes data to a file, replacing the file if it already exists.
<code>data</code> can be a string, a buffer, an <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a>, or an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> object.</p>
<p>The <code>encoding</code> option is ignored if <code>data</code> is a buffer.</p>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<p>The <code>mode</code> option only affects the newly created file. See <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>
for more details.</p>
<p>Any specified <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> has to support writing.</p>
<p>It is unsafe to use <code>fsPromises.writeFile()</code> multiple times on the same file
without waiting for the promise to be settled.</p>
<p>Similarly to <code>fsPromises.readFile</code> - <code>fsPromises.writeFile</code> is a convenience
method that performs multiple <code>write</code> calls internally to write the buffer
passed to it. For performance sensitive code consider using
<a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a> or <a href="#all_fs_filehandlecreatewritestreamoptions"><code>filehandle.createWriteStream()</code></a>.</p>
<p>It is possible to use an <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> to cancel an <code>fsPromises.writeFile()</code>.
Cancelation is "best effort", and some amount of data is likely still
to be written.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { writeFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">try</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> { signal } = controller;
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello Node.js'</span>));
<span class="hljs-keyword">const</span> promise = <span class="hljs-title function_">writeFile</span>(<span class="hljs-string">'message.txt'</span>, data, { signal });
<span class="hljs-comment">// Abort the request before the promise settles.</span>
controller.<span class="hljs-title function_">abort</span>();
<span class="hljs-keyword">await</span> promise;
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-comment">// When a request is aborted - err is an AbortError</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}</code> <button class="copy-button">copy</button></pre>
<p>Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering <code>fs.writeFile</code> performs.</p>
<h4><code>fsPromises.constants</code><span><a class="mark" href="#all_fs_fspromisesconstants" id="all_fs_fspromisesconstants">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_constants"></a></h4>
<div class="api_metadata">
<span>Added in: v18.4.0, v16.17.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns an object containing commonly used constants for file system
operations. The object is the same as <code>fs.constants</code>. See <a href="#all_fs_fs-constants">FS constants</a>
for more details.</p>
</section><section><h3>Callback API<span><a class="mark" href="#all_fs_callback-api" id="all_fs_callback-api">#</a></span><a aria-hidden="true" class="legacy" id="fs_callback_api"></a></h3>
<p>The callback APIs perform all operations asynchronously, without blocking the
event loop, then invoke a callback function upon completion or error.</p>
<p>The callback APIs use the underlying Node.js threadpool to perform file
system operations off the event loop thread. These operations are not
synchronized or threadsafe. Care must be taken when performing multiple
concurrent modifications on the same file or data corruption may occur.</p>
<h4><code>fs.access(path[, mode], callback)</code><span><a class="mark" href="#all_fs_fsaccesspath-mode-callback" id="all_fs_fsaccesspath-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_access_path_mode_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>v20.8.0</td>
<td><p>The constants <code>fs.F_OK</code>, <code>fs.R_OK</code>, <code>fs.W_OK</code> and <code>fs.X_OK</code> which were present directly on <code>fs</code> are deprecated.</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>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The constants like <code>fs.R_OK</code>, etc which were present directly on <code>fs</code> were moved into <code>fs.constants</code> as a soft deprecation. Thus for Node.js <code>< v6.3.0</code> use <code>fs</code> to access those constants, or do something like <code>(fs.constants || fs).R_OK</code> to work with all versions.</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>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>fs.constants.F_OK</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>
<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>
</ul>
</li>
</ul>
<p>Tests a user's permissions for the file or directory specified by <code>path</code>.
The <code>mode</code> argument is an optional integer that specifies the accessibility
checks to be performed. <code>mode</code> should be either the value <code>fs.constants.F_OK</code>
or a mask consisting of the bitwise OR of any of <code>fs.constants.R_OK</code>,
<code>fs.constants.W_OK</code>, and <code>fs.constants.X_OK</code> (e.g.
<code>fs.constants.W_OK | fs.constants.R_OK</code>). Check <a href="#all_fs_file-access-constants">File access constants</a> for
possible values of <code>mode</code>.</p>
<p>The final argument, <code>callback</code>, is a callback function that is invoked with
a possible error argument. If any of the accessibility checks fail, the error
argument will be an <code>Error</code> object. The following examples check if
<code>package.json</code> exists, and if it is readable or writable.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { access, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> file = <span class="hljs-string">'package.json'</span>;
<span class="hljs-comment">// Check if the file exists in the current directory.</span>
<span class="hljs-title function_">access</span>(file, constants.<span class="hljs-property">F_OK</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${file}</span> <span class="hljs-subst">${err ? <span class="hljs-string">'does not exist'</span> : <span class="hljs-string">'exists'</span>}</span>`</span>);
});
<span class="hljs-comment">// Check if the file is readable.</span>
<span class="hljs-title function_">access</span>(file, constants.<span class="hljs-property">R_OK</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${file}</span> <span class="hljs-subst">${err ? <span class="hljs-string">'is not readable'</span> : <span class="hljs-string">'is readable'</span>}</span>`</span>);
});
<span class="hljs-comment">// Check if the file is writable.</span>
<span class="hljs-title function_">access</span>(file, constants.<span class="hljs-property">W_OK</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${file}</span> <span class="hljs-subst">${err ? <span class="hljs-string">'is not writable'</span> : <span class="hljs-string">'is writable'</span>}</span>`</span>);
});
<span class="hljs-comment">// Check if the file is readable and writable.</span>
<span class="hljs-title function_">access</span>(file, constants.<span class="hljs-property">R_OK</span> | constants.<span class="hljs-property">W_OK</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${file}</span> <span class="hljs-subst">${err ? <span class="hljs-string">'is not'</span> : <span class="hljs-string">'is'</span>}</span> readable and writable`</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Do not use <code>fs.access()</code> to check for the accessibility of a file before calling
<code>fs.open()</code>, <code>fs.readFile()</code>, or <code>fs.writeFile()</code>. Doing
so introduces a race condition, since other processes may change the file's
state between the two calls. Instead, user code should open/read/write the
file directly and handle the error raised if the file is not accessible.</p>
<p><strong>write (NOT RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { access, open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">access</span>(<span class="hljs-string">'myfile'</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">'myfile already exists'</span>);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'wx'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">writeMyData</span>(fd);
} <span class="hljs-keyword">finally</span> {
<span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
}
});
});</code> <button class="copy-button">copy</button></pre>
<p><strong>write (RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'wx'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'EEXIST'</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile already exists'</span>);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-keyword">throw</span> err;
}
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">writeMyData</span>(fd);
} <span class="hljs-keyword">finally</span> {
<span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
}
});</code> <button class="copy-button">copy</button></pre>
<p><strong>read (NOT RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { access, open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">access</span>(<span class="hljs-string">'myfile'</span>, <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">code</span> === <span class="hljs-string">'ENOENT'</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile does not exist'</span>);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-keyword">throw</span> err;
}
<span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">readMyData</span>(fd);
} <span class="hljs-keyword">finally</span> {
<span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
}
});
});</code> <button class="copy-button">copy</button></pre>
<p><strong>read (RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'ENOENT'</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile does not exist'</span>);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-keyword">throw</span> err;
}
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">readMyData</span>(fd);
} <span class="hljs-keyword">finally</span> {
<span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
}
});</code> <button class="copy-button">copy</button></pre>
<p>The "not recommended" examples above check for accessibility and then use the
file; the "recommended" examples are better because they use the file directly
and handle the error, if any.</p>
<p>In general, check for the accessibility of a file only if the file will not be
used directly, for example when its accessibility is a signal from another
process.</p>
<p>On Windows, access-control policies (ACLs) on a directory may limit access to
a file or directory. The <code>fs.access()</code> function, however, does not check the
ACL and therefore may report that a path is accessible even if the ACL restricts
the user from reading or writing to it.</p>
<h4><code>fs.appendFile(path, data[, options], callback)</code><span><a class="mark" href="#all_fs_fsappendfilepath-data-options-callback" id="all_fs_fsappendfilepath-data-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_appendfile_path_data_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>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The passed <code>options</code> object will never be modified.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>file</code> parameter can be a file descriptor now.</p></td></tr>
<tr><td>v0.6.7</td>
<td><p><span>Added in: v0.6.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> filename or file descriptor</li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the underlying file descriptor is flushed
prior to closing it. <strong>Default:</strong> <code>false</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>
<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>
</ul>
</li>
</ul>
<p>Asynchronously append data to a file, creating the file if it does not yet
exist. <code>data</code> can be a string or a <a href="#all_buffer_class-buffer" class="type"><Buffer></a>.</p>
<p>The <code>mode</code> option only affects the newly created file. See <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>
for more details.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { appendFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">appendFile</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'data to append'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The "data to append" was appended to file!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>If <code>options</code> is a string, then it specifies the encoding:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { appendFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">appendFile</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'data to append'</span>, <span class="hljs-string">'utf8'</span>, callback);</code> <button class="copy-button">copy</button></pre>
<p>The <code>path</code> may be specified as a numeric file descriptor that has been opened
for appending (using <code>fs.open()</code> or <code>fs.openSync()</code>). The file descriptor will
not be closed automatically.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close, appendFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">closeFd</span>(<span class="hljs-params">fd</span>) {
<span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
}
<span class="hljs-title function_">open</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">appendFile</span>(fd, <span class="hljs-string">'data to append'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-title function_">closeFd</span>(fd);
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-title function_">closeFd</span>(fd);
<span class="hljs-keyword">throw</span> err;
}
});</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.chmod(path, mode, callback)</code><span><a class="mark" href="#all_fs_fschmodpath-mode-callback" id="all_fs_fschmodpath-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_chmod_path_mode_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.30</td>
<td><p><span>Added in: v0.1.30</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>mode</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#Number_type" class="type"><integer></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Asynchronously changes the permissions of a file. No arguments other than a
possible exception are given to the completion callback.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a> documentation for more detail.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { chmod } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">chmod</span>(<span class="hljs-string">'my_file.txt'</span>, <span class="hljs-number">0o775</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The permissions for file "my_file.txt" have been changed!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h5>File modes<span><a class="mark" href="#all_fs_file-modes" id="all_fs_file-modes">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_modes"></a></h5>
<p>The <code>mode</code> argument used in both the <code>fs.chmod()</code> and <code>fs.chmodSync()</code>
methods is a numeric bitmask created using a logical OR of the following
constants:</p>
<table><thead><tr><th>Constant</th><th>Octal</th><th>Description</th></tr></thead><tbody><tr><td><code>fs.constants.S_IRUSR</code></td><td><code>0o400</code></td><td>read by owner</td></tr><tr><td><code>fs.constants.S_IWUSR</code></td><td><code>0o200</code></td><td>write by owner</td></tr><tr><td><code>fs.constants.S_IXUSR</code></td><td><code>0o100</code></td><td>execute/search by owner</td></tr><tr><td><code>fs.constants.S_IRGRP</code></td><td><code>0o40</code></td><td>read by group</td></tr><tr><td><code>fs.constants.S_IWGRP</code></td><td><code>0o20</code></td><td>write by group</td></tr><tr><td><code>fs.constants.S_IXGRP</code></td><td><code>0o10</code></td><td>execute/search by group</td></tr><tr><td><code>fs.constants.S_IROTH</code></td><td><code>0o4</code></td><td>read by others</td></tr><tr><td><code>fs.constants.S_IWOTH</code></td><td><code>0o2</code></td><td>write by others</td></tr><tr><td><code>fs.constants.S_IXOTH</code></td><td><code>0o1</code></td><td>execute/search by others</td></tr></tbody></table>
<p>An easier method of constructing the <code>mode</code> is to use a sequence of three
octal digits (e.g. <code>765</code>). The left-most digit (<code>7</code> in the example), specifies
the permissions for the file owner. The middle digit (<code>6</code> in the example),
specifies permissions for the group. The right-most digit (<code>5</code> in the example),
specifies the permissions for others.</p>
<table><thead><tr><th>Number</th><th>Description</th></tr></thead><tbody><tr><td><code>7</code></td><td>read, write, and execute</td></tr><tr><td><code>6</code></td><td>read and write</td></tr><tr><td><code>5</code></td><td>read and execute</td></tr><tr><td><code>4</code></td><td>read only</td></tr><tr><td><code>3</code></td><td>write and execute</td></tr><tr><td><code>2</code></td><td>write only</td></tr><tr><td><code>1</code></td><td>execute only</td></tr><tr><td><code>0</code></td><td>no permission</td></tr></tbody></table>
<p>For example, the octal value <code>0o765</code> means:</p>
<ul>
<li>The owner may read, write, and execute the file.</li>
<li>The group may read and write the file.</li>
<li>Others may read and execute the file.</li>
</ul>
<p>When using raw numbers where file modes are expected, any value larger than
<code>0o777</code> may result in platform-specific behaviors that are not supported to work
consistently. Therefore constants like <code>S_ISVTX</code>, <code>S_ISGID</code>, or <code>S_ISUID</code> are
not exposed in <code>fs.constants</code>.</p>
<p>Caveats: on Windows only the write permission can be changed, and the
distinction among the permissions of group, owner, or others is not
implemented.</p>
<h4><code>fs.chown(path, uid, gid, callback)</code><span><a class="mark" href="#all_fs_fschownpath-uid-gid-callback" id="all_fs_fschownpath-uid-gid-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_chown_path_uid_gid_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.97</td>
<td><p><span>Added in: v0.1.97</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Asynchronously changes owner and group of a file. No arguments other than a
possible exception are given to the completion callback.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a> documentation for more detail.</p>
<h4><code>fs.close(fd[, callback])</code><span><a class="mark" href="#all_fs_fsclosefd-callback" id="all_fs_fsclosefd-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_close_fd_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>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>v15.9.0, v14.17.0</td>
<td><p>A default callback is now used if one is not provided.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Closes the file descriptor. No arguments other than a possible exception are
given to the completion callback.</p>
<p>Calling <code>fs.close()</code> on any file descriptor (<code>fd</code>) that is currently in use
through any other <code>fs</code> operation may lead to undefined behavior.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/close.2.html"><code>close(2)</code></a> documentation for more detail.</p>
<h4><code>fs.copyFile(src, dest[, mode], callback)</code><span><a class="mark" href="#all_fs_fscopyfilesrc-dest-mode-callback" id="all_fs_fscopyfilesrc-dest-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_copyfile_src_dest_mode_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>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>Changed <code>flags</code> argument to <code>mode</code> and imposed stricter type validation.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> source filename to copy</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> destination filename of the copy operation</li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> modifiers for copy operation. <strong>Default:</strong> <code>0</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>
<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>
</ul>
</li>
</ul>
<p>Asynchronously copies <code>src</code> to <code>dest</code>. By default, <code>dest</code> is overwritten if it
already exists. No arguments other than a possible exception are given to the
callback function. Node.js makes no guarantees about the atomicity of the copy
operation. If an error occurs after the destination file has been opened for
writing, Node.js will attempt to remove the destination.</p>
<p><code>mode</code> is an optional integer that specifies the behavior
of the copy operation. It is possible to create a mask consisting of the bitwise
OR of two or more values (e.g.
<code>fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE</code>).</p>
<ul>
<li><code>fs.constants.COPYFILE_EXCL</code>: The copy operation will fail if <code>dest</code> already
exists.</li>
<li><code>fs.constants.COPYFILE_FICLONE</code>: The copy operation will attempt to create a
copy-on-write reflink. If the platform does not support copy-on-write, then a
fallback copy mechanism is used.</li>
<li><code>fs.constants.COPYFILE_FICLONE_FORCE</code>: The copy operation will attempt to
create a copy-on-write reflink. If the platform does not support
copy-on-write, then the operation will fail.</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { copyFile, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">callback</span>(<span class="hljs-params">err</span>) {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'source.txt was copied to destination.txt'</span>);
}
<span class="hljs-comment">// destination.txt will be created or overwritten by default.</span>
<span class="hljs-title function_">copyFile</span>(<span class="hljs-string">'source.txt'</span>, <span class="hljs-string">'destination.txt'</span>, callback);
<span class="hljs-comment">// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.</span>
<span class="hljs-title function_">copyFile</span>(<span class="hljs-string">'source.txt'</span>, <span class="hljs-string">'destination.txt'</span>, constants.<span class="hljs-property">COPYFILE_EXCL</span>, callback);</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.cp(src, dest[, options], callback)</code><span><a class="mark" href="#all_fs_fscpsrc-dest-options-callback" id="all_fs_fscpsrc-dest-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_cp_src_dest_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>v20.1.0</td>
<td><p>Accept an additional <code>mode</code> option to specify the copy behavior as the <code>mode</code> argument of <code>fs.copyFile()</code>.</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>v17.6.0, v16.15.0</td>
<td><p>Accepts an additional <code>verbatimSymlinks</code> option to specify whether to perform path resolution for symlinks.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> source path to copy.</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> destination path to copy to.</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>dereference</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> dereference symlinks. <strong>Default:</strong> <code>false</code>.</li>
<li><code>errorOnExist</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> when <code>force</code> is <code>false</code>, and the destination
exists, throw an error. <strong>Default:</strong> <code>false</code>.</li>
<li><code>filter</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Function to filter copied files/directories. Return
<code>true</code> to copy the item, <code>false</code> to ignore it. When ignoring a directory,
all of its contents will be skipped as well. Can also return a <code>Promise</code>
that resolves to <code>true</code> or <code>false</code> <strong>Default:</strong> <code>undefined</code>.
<ul>
<li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> source path to copy.</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> destination path to copy to.</li>
<li>Returns: <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/Reference/Global_Objects/Promise" class="type"><Promise></a> A value that is coercible to <code>boolean</code> or
a <code>Promise</code> that fulfils with such value.</li>
</ul>
</li>
<li><code>force</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> overwrite existing file or directory. The copy
operation will ignore errors if you set this to false and the destination
exists. Use the <code>errorOnExist</code> option to change this behavior.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> modifiers for copy operation. <strong>Default:</strong> <code>0</code>.
See <code>mode</code> flag of <a href="#all_fs_fscopyfilesrc-dest-mode-callback"><code>fs.copyFile()</code></a>.</li>
<li><code>preserveTimestamps</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> timestamps from <code>src</code> will
be preserved. <strong>Default:</strong> <code>false</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> copy directories recursively <strong>Default:</strong> <code>false</code></li>
<li><code>verbatimSymlinks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, path resolution for symlinks will
be skipped. <strong>Default:</strong> <code>false</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>
<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>
</ul>
</li>
</ul>
<p>Asynchronously copies the entire directory structure from <code>src</code> to <code>dest</code>,
including subdirectories and files.</p>
<p>When copying a directory to another directory, globs are not supported and
behavior is similar to <code>cp dir1/ dir2/</code>.</p>
<h4><code>fs.createReadStream(path[, options])</code><span><a class="mark" href="#all_fs_fscreatereadstreampath-options" id="all_fs_fscreatereadstreampath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_createreadstream_path_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>v16.10.0</td>
<td><p>The <code>fs</code> option does not need <code>open</code> method if an <code>fd</code> was provided.</p></td></tr>
<tr><td>v16.10.0</td>
<td><p>The <code>fs</code> option does not need <code>close</code> method if <code>autoClose</code> is <code>false</code>.</p></td></tr>
<tr><td>v15.5.0</td>
<td><p>Add support for <code>AbortSignal</code>.</p></td></tr>
<tr><td>v15.4.0</td>
<td><p>The <code>fd</code> option accepts FileHandle arguments.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Change <code>emitClose</code> default to <code>true</code>.</p></td></tr>
<tr><td>v13.6.0, v12.17.0</td>
<td><p>The <code>fs</code> options allow overriding the used <code>fs</code> implementation.</p></td></tr>
<tr><td>v12.10.0</td>
<td><p>Enable <code>emitClose</code> option.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Impose new restrictions on <code>start</code> and <code>end</code>, throwing more appropriate errors in cases when we cannot reasonably handle the input values.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The passed <code>options</code> object will never be modified.</p></td></tr>
<tr><td>v2.3.0</td>
<td><p>The passed <code>options</code> object can be a string now.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong>
<code>'r'</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> <strong>Default:</strong> <code>null</code></li>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> <strong>Default:</strong> <code>null</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li>
<li><code>autoClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</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> <strong>Default:</strong> <code>true</code></li>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>Infinity</code></li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>64 * 1024</code></li>
<li><code>fs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsreadstream" class="type"><fs.ReadStream></a></li>
</ul>
<p><code>options</code> can include <code>start</code> and <code>end</code> values to read a range of bytes from
the file instead of the entire file. Both <code>start</code> and <code>end</code> are inclusive and
start counting at 0, allowed values are in the
[0, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER"><code>Number.MAX_SAFE_INTEGER</code></a>] range. If <code>fd</code> is specified and <code>start</code> is
omitted or <code>undefined</code>, <code>fs.createReadStream()</code> reads sequentially from the
current file position. The <code>encoding</code> can be any one of those accepted by
<a href="#all_buffer_class-buffer" class="type"><Buffer></a>.</p>
<p>If <code>fd</code> is specified, <code>ReadStream</code> will ignore the <code>path</code> argument and will use
the specified file descriptor. This means that no <code>'open'</code> event will be
emitted. <code>fd</code> should be blocking; non-blocking <code>fd</code>s should be passed to
<a href="#all_net_class-netsocket" class="type"><net.Socket></a>.</p>
<p>If <code>fd</code> points to a character device that only supports blocking reads
(such as keyboard or sound card), read operations do not finish until data is
available. This can prevent the process from exiting and the stream from
closing naturally.</p>
<p>By default, the stream will emit a <code>'close'</code> event after it has been
destroyed. Set the <code>emitClose</code> option to <code>false</code> to change this behavior.</p>
<p>By providing the <code>fs</code> option, it is possible to override the corresponding <code>fs</code>
implementations for <code>open</code>, <code>read</code>, and <code>close</code>. When providing the <code>fs</code> option,
an override for <code>read</code> is required. If no <code>fd</code> is provided, an override for
<code>open</code> is also required. If <code>autoClose</code> is <code>true</code>, an override for <code>close</code> is
also required.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// Create a stream from some character device.</span>
<span class="hljs-keyword">const</span> stream = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'/dev/input/event0'</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">close</span>(); <span class="hljs-comment">// This may not close the stream.</span>
<span class="hljs-comment">// Artificially marking end-of-stream, as if the underlying resource had</span>
<span class="hljs-comment">// indicated end-of-file by itself, allows the stream to close.</span>
<span class="hljs-comment">// This does not cancel pending read operations, and if there is such an</span>
<span class="hljs-comment">// operation, the process may still not be able to exit successfully</span>
<span class="hljs-comment">// until it finishes.</span>
stream.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>);
stream.<span class="hljs-title function_">read</span>(<span class="hljs-number">0</span>);
}, <span class="hljs-number">100</span>);</code> <button class="copy-button">copy</button></pre>
<p>If <code>autoClose</code> is false, then the file descriptor won't be closed, even if
there's an error. It is the application's responsibility to close it and make
sure there's no file descriptor leak. If <code>autoClose</code> is set to true (default
behavior), on <code>'error'</code> or <code>'end'</code> the file descriptor will be closed
automatically.</p>
<p><code>mode</code> sets the file mode (permission and sticky bits), but only if the
file was created.</p>
<p>An example to read the last 10 bytes of a file which is 100 bytes long:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'sample.txt'</span>, { <span class="hljs-attr">start</span>: <span class="hljs-number">90</span>, <span class="hljs-attr">end</span>: <span class="hljs-number">99</span> });</code> <button class="copy-button">copy</button></pre>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<h4><code>fs.createWriteStream(path[, options])</code><span><a class="mark" href="#all_fs_fscreatewritestreampath-options" id="all_fs_fscreatewritestreampath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_createwritestream_path_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>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v16.10.0</td>
<td><p>The <code>fs</code> option does not need <code>open</code> method if an <code>fd</code> was provided.</p></td></tr>
<tr><td>v16.10.0</td>
<td><p>The <code>fs</code> option does not need <code>close</code> method if <code>autoClose</code> is <code>false</code>.</p></td></tr>
<tr><td>v15.5.0</td>
<td><p>Add support for <code>AbortSignal</code>.</p></td></tr>
<tr><td>v15.4.0</td>
<td><p>The <code>fd</code> option accepts FileHandle arguments.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Change <code>emitClose</code> default to <code>true</code>.</p></td></tr>
<tr><td>v13.6.0, v12.17.0</td>
<td><p>The <code>fs</code> options allow overriding the used <code>fs</code> implementation.</p></td></tr>
<tr><td>v12.10.0</td>
<td><p>Enable <code>emitClose</code> option.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The passed <code>options</code> object will never be modified.</p></td></tr>
<tr><td>v5.5.0</td>
<td><p>The <code>autoClose</code> option is supported now.</p></td></tr>
<tr><td>v2.3.0</td>
<td><p>The passed <code>options</code> object can be a string now.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong>
<code>'w'</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> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> <strong>Default:</strong> <code>null</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li>
<li><code>autoClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</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> <strong>Default:</strong> <code>true</code></li>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>fs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</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> <strong>Default:</strong> <code>16384</code></li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the underlying file descriptor is flushed
prior to closing it. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fswritestream" class="type"><fs.WriteStream></a></li>
</ul>
<p><code>options</code> may also include a <code>start</code> option to allow writing data at some
position past the beginning of the file, allowed values are in the
[0, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER"><code>Number.MAX_SAFE_INTEGER</code></a>] range. Modifying a file rather than
replacing it may require the <code>flags</code> option to be set to <code>r+</code> rather than the
default <code>w</code>. The <code>encoding</code> can be any one of those accepted by <a href="#all_buffer_class-buffer" class="type"><Buffer></a>.</p>
<p>If <code>autoClose</code> is set to true (default behavior) on <code>'error'</code> or <code>'finish'</code>
the file descriptor will be closed automatically. If <code>autoClose</code> is false,
then the file descriptor won't be closed, even if there's an error.
It is the application's responsibility to close it and make sure there's no
file descriptor leak.</p>
<p>By default, the stream will emit a <code>'close'</code> event after it has been
destroyed. Set the <code>emitClose</code> option to <code>false</code> to change this behavior.</p>
<p>By providing the <code>fs</code> option it is possible to override the corresponding <code>fs</code>
implementations for <code>open</code>, <code>write</code>, <code>writev</code>, and <code>close</code>. Overriding <code>write()</code>
without <code>writev()</code> can reduce performance as some optimizations (<code>_writev()</code>)
will be disabled. When providing the <code>fs</code> option, overrides for at least one of
<code>write</code> and <code>writev</code> are required. If no <code>fd</code> option is supplied, an override
for <code>open</code> is also required. If <code>autoClose</code> is <code>true</code>, an override for <code>close</code>
is also required.</p>
<p>Like <a href="#all_fs_class-fsreadstream" class="type"><fs.ReadStream></a>, if <code>fd</code> is specified, <a href="#all_fs_class-fswritestream" class="type"><fs.WriteStream></a> will ignore the
<code>path</code> argument and will use the specified file descriptor. This means that no
<code>'open'</code> event will be emitted. <code>fd</code> should be blocking; non-blocking <code>fd</code>s
should be passed to <a href="#all_net_class-netsocket" class="type"><net.Socket></a>.</p>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<h4><code>fs.exists(path, callback)</code><span><a class="mark" href="#all_fs_fsexistspath-callback" id="all_fs_fsexistspath-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_exists_path_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>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>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v1.0.0</td>
<td><p><span>Deprecated since: v1.0.0</span></p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_fs_fsstatpath-options-callback"><code>fs.stat()</code></a> or <a href="#all_fs_fsaccesspath-mode-callback"><code>fs.access()</code></a> instead.</div><p></p>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<ul>
<li><code>exists</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
</li>
</ul>
<p>Test whether or not the element at the given <code>path</code> exists by checking with the file system.
Then call the <code>callback</code> argument with either true or false:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { exists } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">exists</span>(<span class="hljs-string">'/etc/passwd'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e ? <span class="hljs-string">'it exists'</span> : <span class="hljs-string">'no passwd!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p><strong>The parameters for this callback are not consistent with other Node.js
callbacks.</strong> Normally, the first parameter to a Node.js callback is an <code>err</code>
parameter, optionally followed by other parameters. The <code>fs.exists()</code> callback
has only one boolean parameter. This is one reason <code>fs.access()</code> is recommended
instead of <code>fs.exists()</code>.</p>
<p>If <code>path</code> is a symbolic link, it is followed. Thus, if <code>path</code> exists but points
to a non-existent element, the callback will receive the value <code>false</code>.</p>
<p>Using <code>fs.exists()</code> to check for the existence of a file before calling
<code>fs.open()</code>, <code>fs.readFile()</code>, or <code>fs.writeFile()</code> is not recommended. Doing
so introduces a race condition, since other processes may change the file's
state between the two calls. Instead, user code should open/read/write the
file directly and handle the error raised if the file does not exist.</p>
<p><strong>write (NOT RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { exists, open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">exists</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-keyword">if</span> (e) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile already exists'</span>);
} <span class="hljs-keyword">else</span> {
<span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'wx'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">writeMyData</span>(fd);
} <span class="hljs-keyword">finally</span> {
<span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
}
});
}
});</code> <button class="copy-button">copy</button></pre>
<p><strong>write (RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'wx'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'EEXIST'</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile already exists'</span>);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-keyword">throw</span> err;
}
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">writeMyData</span>(fd);
} <span class="hljs-keyword">finally</span> {
<span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
}
});</code> <button class="copy-button">copy</button></pre>
<p><strong>read (NOT RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close, exists } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">exists</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-keyword">if</span> (e) {
<span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">readMyData</span>(fd);
} <span class="hljs-keyword">finally</span> {
<span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
}
});
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile does not exist'</span>);
}
});</code> <button class="copy-button">copy</button></pre>
<p><strong>read (RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'ENOENT'</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile does not exist'</span>);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-keyword">throw</span> err;
}
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">readMyData</span>(fd);
} <span class="hljs-keyword">finally</span> {
<span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
}
});</code> <button class="copy-button">copy</button></pre>
<p>The "not recommended" examples above check for existence and then use the
file; the "recommended" examples are better because they use the file directly
and handle the error, if any.</p>
<p>In general, check for the existence of a file only if the file won't be
used directly, for example when its existence is a signal from another
process.</p>
<h4><code>fs.fchmod(fd, mode, callback)</code><span><a class="mark" href="#all_fs_fsfchmodfd-mode-callback" id="all_fs_fsfchmodfd-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fchmod_fd_mode_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p><span>Added in: v0.4.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>mode</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#Number_type" class="type"><integer></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Sets the permissions on the file. No arguments other than a possible exception
are given to the completion callback.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/fchmod.2.html"><code>fchmod(2)</code></a> documentation for more detail.</p>
<h4><code>fs.fchown(fd, uid, gid, callback)</code><span><a class="mark" href="#all_fs_fsfchownfd-uid-gid-callback" id="all_fs_fsfchownfd-uid-gid-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fchown_fd_uid_gid_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p><span>Added in: v0.4.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Sets the owner of the file. No arguments other than a possible exception are
given to the completion callback.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/fchown.2.html"><code>fchown(2)</code></a> documentation for more detail.</p>
<h4><code>fs.fdatasync(fd, callback)</code><span><a class="mark" href="#all_fs_fsfdatasyncfd-callback" id="all_fs_fsfdatasyncfd-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fdatasync_fd_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.96</td>
<td><p><span>Added in: v0.1.96</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Forces all currently queued I/O operations associated with the file to the
operating system's synchronized I/O completion state. Refer to the POSIX
<a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html"><code>fdatasync(2)</code></a> documentation for details. No arguments other than a possible
exception are given to the completion callback.</p>
<h4><code>fs.fstat(fd[, options], callback)</code><span><a class="mark" href="#all_fs_fsfstatfd-options-callback" id="all_fs_fsfstatfd-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fstat_fd_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>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>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.95</td>
<td><p><span>Added in: v0.1.95</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></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>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned
<a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</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>
<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>stats</code> <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a></li>
</ul>
</li>
</ul>
<p>Invokes the callback with the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> for the file descriptor.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/fstat.2.html"><code>fstat(2)</code></a> documentation for more detail.</p>
<h4><code>fs.fsync(fd, callback)</code><span><a class="mark" href="#all_fs_fsfsyncfd-callback" id="all_fs_fsfsyncfd-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fsync_fd_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.96</td>
<td><p><span>Added in: v0.1.96</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Request that all data for the open file descriptor is flushed to the storage
device. The specific implementation is operating system and device specific.
Refer to the POSIX <a href="http://man7.org/linux/man-pages/man2/fsync.2.html"><code>fsync(2)</code></a> documentation for more detail. No arguments other
than a possible exception are given to the completion callback.</p>
<h4><code>fs.ftruncate(fd[, len], callback)</code><span><a class="mark" href="#all_fs_fsftruncatefd-len-callback" id="all_fs_fsftruncatefd-len-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_ftruncate_fd_len_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.8.6</td>
<td><p><span>Added in: v0.8.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</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>
<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>
</ul>
</li>
</ul>
<p>Truncates the file descriptor. No arguments other than a possible exception are
given to the completion callback.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/ftruncate.2.html"><code>ftruncate(2)</code></a> documentation for more detail.</p>
<p>If the file referred to by the file descriptor was larger than <code>len</code> bytes, only
the first <code>len</code> bytes will be retained in the file.</p>
<p>For example, the following program retains only the first four bytes of the
file:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close, ftruncate } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">closeFd</span>(<span class="hljs-params">fd</span>) {
<span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
}
<span class="hljs-title function_">open</span>(<span class="hljs-string">'temp.txt'</span>, <span class="hljs-string">'r+'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">ftruncate</span>(fd, <span class="hljs-number">4</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-title function_">closeFd</span>(fd);
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-title function_">closeFd</span>(fd);
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
}
});</code> <button class="copy-button">copy</button></pre>
<p>If the file previously was shorter than <code>len</code> bytes, it is extended, and the
extended part is filled with null bytes (<code>'\0'</code>):</p>
<p>If <code>len</code> is negative then <code>0</code> will be used.</p>
<h4><code>fs.futimes(fd, atime, mtime, callback)</code><span><a class="mark" href="#all_fs_fsfutimesfd-atime-mtime-callback" id="all_fs_fsfutimesfd-atime-mtime-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_futimes_fd_atime_mtime_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v4.1.0</td>
<td><p>Numeric strings, <code>NaN</code>, and <code>Infinity</code> are now allowed time specifiers.</p></td></tr>
<tr><td>v0.4.2</td>
<td><p><span>Added in: v0.4.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Change the file system timestamps of the object referenced by the supplied file
descriptor. See <a href="#all_fs_fsutimespath-atime-mtime-callback"><code>fs.utimes()</code></a>.</p>
<h4><code>fs.lchmod(path, mode, callback)</code><span><a class="mark" href="#all_fs_fslchmodpath-mode-callback" id="all_fs_fslchmodpath-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lchmod_path_mode_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>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>v16.0.0</td>
<td><p>The error returned may be an <code>AggregateError</code> if more than one error is returned.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p><span>Deprecated since: v0.4.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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 href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError" class="type"><AggregateError></a></li>
</ul>
</li>
</ul>
<p>Changes the permissions on a symbolic link. No arguments other than a possible
exception are given to the completion callback.</p>
<p>This method is only implemented on macOS.</p>
<p>See the POSIX <a href="https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2"><code>lchmod(2)</code></a> documentation for more detail.</p>
<h4><code>fs.lchown(path, uid, gid, callback)</code><span><a class="mark" href="#all_fs_fslchownpath-uid-gid-callback" id="all_fs_fslchownpath-uid-gid-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lchown_path_uid_gid_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>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>v10.6.0</td>
<td><p>This API is no longer deprecated.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Set the owner of the symbolic link. No arguments other than a possible
exception are given to the completion callback.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/lchown.2.html"><code>lchown(2)</code></a> documentation for more detail.</p>
<h4><code>fs.lutimes(path, atime, mtime, callback)</code><span><a class="mark" href="#all_fs_fslutimespath-atime-mtime-callback" id="all_fs_fslutimespath-atime-mtime-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lutimes_path_atime_mtime_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>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.5.0, v12.19.0</td>
<td><p><span>Added in: v14.5.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Changes the access and modification times of a file in the same way as
<a href="#all_fs_fsutimespath-atime-mtime-callback"><code>fs.utimes()</code></a>, with the difference that if the path refers to a symbolic
link, then the link is not dereferenced: instead, the timestamps of the
symbolic link itself are changed.</p>
<p>No arguments other than a possible exception are given to the completion
callback.</p>
<h4><code>fs.link(existingPath, newPath, callback)</code><span><a class="mark" href="#all_fs_fslinkexistingpath-newpath-callback" id="all_fs_fslinkexistingpath-newpath-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_link_existingpath_newpath_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>existingPath</code> and <code>newPath</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>existingPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Creates a new link from the <code>existingPath</code> to the <code>newPath</code>. See the POSIX
<a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a> documentation for more detail. No arguments other than a possible
exception are given to the completion callback.</p>
<h4><code>fs.lstat(path[, options], callback)</code><span><a class="mark" href="#all_fs_fslstatpath-options-callback" id="all_fs_fslstatpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lstat_path_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>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>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.30</td>
<td><p><span>Added in: v0.1.30</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned
<a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</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>
<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>stats</code> <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a></li>
</ul>
</li>
</ul>
<p>Retrieves the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> for the symbolic link referred to by the path.
The callback gets two arguments <code>(err, stats)</code> where <code>stats</code> is a <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a>
object. <code>lstat()</code> is identical to <code>stat()</code>, except that if <code>path</code> is a symbolic
link, then the link itself is stat-ed, not the file that it refers to.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/lstat.2.html"><code>lstat(2)</code></a> documentation for more details.</p>
<h4><code>fs.mkdir(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsmkdirpath-options-callback" id="all_fs_fsmkdirpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_mkdir_path_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>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>v13.11.0, v12.17.0</td>
<td><p>In <code>recursive</code> mode, the callback now receives the first created path as an argument.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p>The second argument can now be an <code>options</code> object with <code>recursive</code> and <code>mode</code> properties.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.8</td>
<td><p><span>Added in: v0.1.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a>
<ul>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>mode</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#Number_type" class="type"><integer></a> Not supported on Windows. <strong>Default:</strong> <code>0o777</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>
<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>path</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#Undefined_type" class="type"><undefined></a> Present only if a directory is created with
<code>recursive</code> set to <code>true</code>.</li>
</ul>
</li>
</ul>
<p>Asynchronously creates a directory.</p>
<p>The callback is given a possible exception and, if <code>recursive</code> is <code>true</code>, the
first directory path created, <code>(err[, path])</code>.
<code>path</code> can still be <code>undefined</code> when <code>recursive</code> is <code>true</code>, if no directory was
created (for instance, if it was previously created).</p>
<p>The optional <code>options</code> argument can be an integer specifying <code>mode</code> (permission
and sticky bits), or an object with a <code>mode</code> property and a <code>recursive</code>
property indicating whether parent directories should be created. Calling
<code>fs.mkdir()</code> when <code>path</code> is a directory that exists results in an error only
when <code>recursive</code> is false. If <code>recursive</code> is false and the directory exists,
an <code>EEXIST</code> error occurs.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { mkdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist.</span>
<span class="hljs-title function_">mkdir</span>(<span class="hljs-string">'./tmp/a/apple'</span>, { <span class="hljs-attr">recursive</span>: <span class="hljs-literal">true</span> }, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});</code> <button class="copy-button">copy</button></pre>
<p>On Windows, using <code>fs.mkdir()</code> on the root directory even with recursion will
result in an error:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { mkdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">mkdir</span>(<span class="hljs-string">'/'</span>, { <span class="hljs-attr">recursive</span>: <span class="hljs-literal">true</span> }, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-comment">// => [Error: EPERM: operation not permitted, mkdir 'C:\']</span>
});</code> <button class="copy-button">copy</button></pre>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html"><code>mkdir(2)</code></a> documentation for more details.</p>
<h4><code>fs.mkdtemp(prefix[, options], callback)</code><span><a class="mark" href="#all_fs_fsmkdtempprefix-options-callback" id="all_fs_fsmkdtempprefix-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_mkdtemp_prefix_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>v20.6.0</td>
<td><p>The <code>prefix</code> parameter now accepts buffers and URL.</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>v16.5.0, v14.18.0</td>
<td><p>The <code>prefix</code> parameter now accepts an empty string.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v6.2.1</td>
<td><p>The <code>callback</code> parameter is optional now.</p></td></tr>
<tr><td>v5.10.0</td>
<td><p><span>Added in: v5.10.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>prefix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</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>
<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>directory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</li>
</ul>
<p>Creates a unique temporary directory.</p>
<p>Generates six random characters to be appended behind a required
<code>prefix</code> to create a unique temporary directory. Due to platform
inconsistencies, avoid trailing <code>X</code> characters in <code>prefix</code>. Some platforms,
notably the BSDs, can return more than six random characters, and replace
trailing <code>X</code> characters in <code>prefix</code> with random characters.</p>
<p>The created directory path is passed as a string to the callback's second
parameter.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { mkdtemp } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</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">import</span> { tmpdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-title function_">mkdtemp</span>(<span class="hljs-title function_">join</span>(<span class="hljs-title function_">tmpdir</span>(), <span class="hljs-string">'foo-'</span>), <span class="hljs-function">(<span class="hljs-params">err, directory</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(directory);
<span class="hljs-comment">// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2</span>
});</code> <button class="copy-button">copy</button></pre>
<p>The <code>fs.mkdtemp()</code> method will append the six randomly selected characters
directly to the <code>prefix</code> string. For instance, given a directory <code>/tmp</code>, if the
intention is to create a temporary directory <em>within</em> <code>/tmp</code>, the <code>prefix</code>
must end with a trailing platform-specific path separator
(<code>require('node:path').sep</code>).</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { tmpdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-keyword">import</span> { mkdtemp } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// The parent directory for the new temporary directory</span>
<span class="hljs-keyword">const</span> tmpDir = <span class="hljs-title function_">tmpdir</span>();
<span class="hljs-comment">// This method is *INCORRECT*:</span>
<span class="hljs-title function_">mkdtemp</span>(tmpDir, <span class="hljs-function">(<span class="hljs-params">err, directory</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(directory);
<span class="hljs-comment">// Will print something similar to `/tmpabc123`.</span>
<span class="hljs-comment">// A new temporary directory is created at the file system root</span>
<span class="hljs-comment">// rather than *within* the /tmp directory.</span>
});
<span class="hljs-comment">// This method is *CORRECT*:</span>
<span class="hljs-keyword">import</span> { sep } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-title function_">mkdtemp</span>(<span class="hljs-string">`<span class="hljs-subst">${tmpDir}</span><span class="hljs-subst">${sep}</span>`</span>, <span class="hljs-function">(<span class="hljs-params">err, directory</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(directory);
<span class="hljs-comment">// Will print something similar to `/tmp/abc123`.</span>
<span class="hljs-comment">// A new temporary directory is created within</span>
<span class="hljs-comment">// the /tmp directory.</span>
});</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.open(path[, flags[, mode]], callback)</code><span><a class="mark" href="#all_fs_fsopenpath-flags-mode-callback" id="all_fs_fsopenpath-flags-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_open_path_flags_mode_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>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>v11.1.0</td>
<td><p>The <code>flags</code> argument is now optional and defaults to <code>'r'</code>.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>The <code>as</code> and <code>as+</code> flags are supported now.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>flags</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#Number_type" class="type"><number></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>.
<strong>Default:</strong> <code>'r'</code>.</li>
<li><code>mode</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#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code> (readable and writable)</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
</li>
</ul>
<p>Asynchronous file open. See the POSIX <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a> documentation for more details.</p>
<p><code>mode</code> sets the file mode (permission and sticky bits), but only if the file was
created. On Windows, only the write permission can be manipulated; see
<a href="#all_fs_fschmodpath-mode-callback"><code>fs.chmod()</code></a>.</p>
<p>The callback gets two arguments <code>(err, fd)</code>.</p>
<p>Some characters (<code>< > : " / \ | ? *</code>) are reserved under Windows as documented
by <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file">Naming Files, Paths, and Namespaces</a>. Under NTFS, if the filename contains
a colon, Node.js will open a file system stream, as described by
<a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams">this MSDN page</a>.</p>
<p>Functions based on <code>fs.open()</code> exhibit this behavior as well:
<code>fs.writeFile()</code>, <code>fs.readFile()</code>, etc.</p>
<h4><code>fs.openAsBlob(path[, options])</code><span><a class="mark" href="#all_fs_fsopenasblobpath-options" id="all_fs_fsopenasblobpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_openasblob_path_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> An optional mime type for the blob.</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 with a <a href="#all_buffer_class-blob" class="type"><Blob></a> upon success.</li>
</ul>
<p>Returns a <a href="#all_buffer_class-blob" class="type"><Blob></a> whose data is backed by the given file.</p>
<p>The file must not be modified after the <a href="#all_buffer_class-blob" class="type"><Blob></a> is created. Any modifications
will cause reading the <a href="#all_buffer_class-blob" class="type"><Blob></a> data to fail with a <code>DOMException</code> error.
Synchronous stat operations on the file when the <code>Blob</code> is created, and before
each read in order to detect whether the file data has been modified on disk.</p>
<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> { openAsBlob } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">await</span> <span class="hljs-title function_">openAsBlob</span>(<span class="hljs-string">'the.file.txt'</span>);
<span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">await</span> blob.<span class="hljs-title function_">arrayBuffer</span>();
blob.<span class="hljs-title function_">stream</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { openAsBlob } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">await</span> <span class="hljs-title function_">openAsBlob</span>(<span class="hljs-string">'the.file.txt'</span>);
<span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">await</span> blob.<span class="hljs-title function_">arrayBuffer</span>();
blob.<span class="hljs-title function_">stream</span>();
})();</code><button class="copy-button">copy</button></pre>
<h4><code>fs.opendir(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsopendirpath-options-callback" id="all_fs_fsopendirpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_opendir_path_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>v20.1.0</td>
<td><p>Added <code>recursive</code> option.</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>v13.1.0, v12.16.0</td>
<td><p>The <code>bufferSize</code> option was introduced.</p></td></tr>
<tr><td>v12.12.0</td>
<td><p><span>Added in: v12.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>bufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of directory entries that are buffered
internally when reading from the directory. Higher values lead to better
performance but higher memory usage. <strong>Default:</strong> <code>32</code></li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</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>
<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>dir</code> <a href="#all_fs_class-fsdir" class="type"><fs.Dir></a></li>
</ul>
</li>
</ul>
<p>Asynchronously open a directory. See the POSIX <a href="http://man7.org/linux/man-pages/man3/opendir.3.html"><code>opendir(3)</code></a> documentation for
more details.</p>
<p>Creates an <a href="#all_fs_class-fsdir" class="type"><fs.Dir></a>, which contains all further functions for reading from
and cleaning up the directory.</p>
<p>The <code>encoding</code> option sets the encoding for the <code>path</code> while opening the
directory and subsequent read operations.</p>
<h4><code>fs.read(fd, buffer, offset, length, position, callback)</code><span><a class="mark" href="#all_fs_fsreadfd-buffer-offset-length-position-callback" id="all_fs_fsreadfd-buffer-offset-length-position-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_read_fd_buffer_offset_length_position_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>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>v10.10.0</td>
<td><p>The <code>buffer</code> parameter can now be any <code>TypedArray</code>, or a <code>DataView</code>.</p></td></tr>
<tr><td>v7.4.0</td>
<td><p>The <code>buffer</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>length</code> parameter can now be <code>0</code>.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_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> The buffer that the data will be
written to.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The position in <code>buffer</code> to write the data to.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of bytes to read.</li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> Specifies where to begin reading from in the
file. If <code>position</code> is <code>null</code> or <code>-1 </code>, data will be read from the current
file position, and the file position will be updated. If <code>position</code> is an
integer, the file position will be unchanged.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
</ul>
<p>Read data from the file specified by <code>fd</code>.</p>
<p>The callback is given the three arguments, <code>(err, bytesRead, buffer)</code>.</p>
<p>If the file is not modified concurrently, the end-of-file is reached when the
number of bytes read is zero.</p>
<p>If this method is invoked as its <a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed version, it returns
a promise for an <code>Object</code> with <code>bytesRead</code> and <code>buffer</code> properties.</p>
<p>The <code>fs.read()</code> method reads data from the file specified
by the file descriptor (<code>fd</code>).
The <code>length</code> argument indicates the maximum number
of bytes that Node.js
will attempt to read from the kernel.
However, the actual number of bytes read (<code>bytesRead</code>) can be lower
than the specified <code>length</code> for various reasons.</p>
<p>For example:</p>
<ul>
<li>If the file is shorter than the specified <code>length</code>, <code>bytesRead</code>
will be set to the actual number of bytes read.</li>
<li>If the file encounters EOF (End of File) before the buffer could
be filled, Node.js will read all available bytes until EOF is encountered,
and the <code>bytesRead</code> parameter in the callback will indicate
the actual number of bytes read, which may be less than the specified <code>length</code>.</li>
<li>If the file is on a slow network <code>filesystem</code>
or encounters any other issue during reading,
<code>bytesRead</code> can be lower than the specified <code>length</code>.</li>
</ul>
<p>Therefore, when using <code>fs.read()</code>, it's important to
check the <code>bytesRead</code> value to
determine how many bytes were actually read from the file.
Depending on your application
logic, you may need to handle cases where <code>bytesRead</code>
is lower than the specified <code>length</code>,
such as by wrapping the read call in a loop if you require
a minimum amount of bytes.</p>
<p>This behavior is similar to the POSIX <code>preadv2</code> function.</p>
<h4><code>fs.read(fd[, options], callback)</code><span><a class="mark" href="#all_fs_fsreadfd-options-callback" id="all_fs_fsreadfd-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_read_fd_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>v13.11.0, v12.17.0</td>
<td><p>Options object can be passed in to make buffer, offset, length, and position optional.</p></td></tr>
<tr><td>v13.11.0, v12.17.0</td>
<td><p><span>Added in: v13.11.0, v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></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>buffer</code> <a href="#all_buffer_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> <strong>Default:</strong> <code>Buffer.alloc(16384)</code></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>buffer.byteLength - offset</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</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>
<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>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
</ul>
<p>Similar to the <a href="#all_fs_fsreadfd-buffer-offset-length-position-callback"><code>fs.read()</code></a> function, this version takes an optional
<code>options</code> object. If no <code>options</code> object is specified, it will default with the
above values.</p>
<h4><code>fs.read(fd, buffer[, options], callback)</code><span><a class="mark" href="#all_fs_fsreadfd-buffer-options-callback" id="all_fs_fsreadfd-buffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_read_fd_buffer_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v18.2.0, v16.17.0</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_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> The buffer that the data will be
written to.</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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>buffer.byteLength - offset</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> <strong>Default:</strong> <code>null</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>
<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>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
</ul>
<p>Similar to the <a href="#all_fs_fsreadfd-buffer-offset-length-position-callback"><code>fs.read()</code></a> function, this version takes an optional
<code>options</code> object. If no <code>options</code> object is specified, it will default with the
above values.</p>
<h4><code>fs.readdir(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsreaddirpath-options-callback" id="all_fs_fsreaddirpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readdir_path_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>v20.1.0</td>
<td><p>Added <code>recursive</code> option.</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>v10.10.0</td>
<td><p>New option <code>withFileTypes</code> was added.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>options</code> parameter was added.</p></td></tr>
<tr><td>v0.1.8</td>
<td><p><span>Added in: v0.1.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>withFileTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, reads the contents of a directory
recursively. In recursive mode, it will list all files, sub files and
directories. <strong>Default:</strong> <code>false</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>
<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>files</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer[]></a> | <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent[]></a></li>
</ul>
</li>
</ul>
<p>Reads the contents of a directory. The callback gets two arguments <code>(err, files)</code>
where <code>files</code> is an array of the names of the files in the directory excluding
<code>'.'</code> and <code>'..'</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> documentation for more details.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the filenames passed to the callback. If the <code>encoding</code> is set to <code>'buffer'</code>,
the filenames returned will be passed as <a href="#all_buffer_class-buffer" class="type"><Buffer></a> objects.</p>
<p>If <code>options.withFileTypes</code> is set to <code>true</code>, the <code>files</code> array will contain
<a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> objects.</p>
<h4><code>fs.readFile(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsreadfilepath-options-callback" id="all_fs_fsreadfilepath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readfile_path_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>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>v16.0.0</td>
<td><p>The error returned may be an <code>AggregateError</code> if more than one error is returned.</p></td></tr>
<tr><td>v15.2.0, v14.17.0</td>
<td><p>The options argument may include an AbortSignal to abort an ongoing readFile request.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v5.1.0</td>
<td><p>The <code>callback</code> will always be called with <code>null</code> as the <code>error</code> parameter in case of success.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>path</code> parameter can be a file descriptor now.</p></td></tr>
<tr><td>v0.1.29</td>
<td><p><span>Added in: v0.1.29</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> filename or file descriptor</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows aborting an in-progress readFile</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>
<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 href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError" class="type"><AggregateError></a></li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
</ul>
<p>Asynchronously reads the entire contents of a file.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'/etc/passwd'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
});</code> <button class="copy-button">copy</button></pre>
<p>The callback is passed two arguments <code>(err, data)</code>, where <code>data</code> is the
contents of the file.</p>
<p>If no encoding is specified, then the raw buffer is returned.</p>
<p>If <code>options</code> is a string, then it specifies the encoding:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'/etc/passwd'</span>, <span class="hljs-string">'utf8'</span>, callback);</code> <button class="copy-button">copy</button></pre>
<p>When the path is a directory, the behavior of <code>fs.readFile()</code> and
<a href="#all_fs_fsreadfilesyncpath-options"><code>fs.readFileSync()</code></a> is platform-specific. On macOS, Linux, and Windows, an
error will be returned. On FreeBSD, a representation of the directory's contents
will be returned.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// macOS, Linux, and Windows</span>
<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'<directory>'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =></span> {
<span class="hljs-comment">// => [Error: EISDIR: illegal operation on a directory, read <directory>]</span>
});
<span class="hljs-comment">// FreeBSD</span>
<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'<directory>'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =></span> {
<span class="hljs-comment">// => null, <data></span>
});</code> <button class="copy-button">copy</button></pre>
<p>It is possible to abort an ongoing request using an <code>AbortSignal</code>. If a
request is aborted the callback is called with an <code>AbortError</code>:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</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> signal = controller.<span class="hljs-property">signal</span>;
<span class="hljs-title function_">readFile</span>(fileInfo[<span class="hljs-number">0</span>].<span class="hljs-property">name</span>, { signal }, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
<span class="hljs-comment">// ...</span>
});
<span class="hljs-comment">// When you want to abort the request</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<p>The <code>fs.readFile()</code> function buffers the entire file. To minimize memory costs,
when possible prefer streaming via <code>fs.createReadStream()</code>.</p>
<p>Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering <code>fs.readFile</code> performs.</p>
<h5>File descriptors<span><a class="mark" href="#all_fs_file-descriptors" id="all_fs_file-descriptors">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_descriptors"></a></h5>
<ol>
<li>Any specified file descriptor has to support reading.</li>
<li>If a file descriptor is specified as the <code>path</code>, it will not be closed
automatically.</li>
<li>The reading will begin at the current position. For example, if the file
already had <code>'Hello World'</code> and six bytes are read with the file descriptor,
the call to <code>fs.readFile()</code> with the same file descriptor, would give
<code>'World'</code>, rather than <code>'Hello World'</code>.</li>
</ol>
<h5>Performance Considerations<span><a class="mark" href="#all_fs_performance-considerations" id="all_fs_performance-considerations">#</a></span><a aria-hidden="true" class="legacy" id="fs_performance_considerations"></a></h5>
<p>The <code>fs.readFile()</code> method asynchronously reads the contents of a file into
memory one chunk at a time, allowing the event loop to turn between each chunk.
This allows the read operation to have less impact on other activity that may
be using the underlying libuv thread pool but means that it will take longer
to read a complete file into memory.</p>
<p>The additional read overhead can vary broadly on different systems and depends
on the type of file being read. If the file type is not a regular file (a pipe
for instance) and Node.js is unable to determine an actual file size, each read
operation will load on 64 KiB of data. For regular files, each read will process
512 KiB of data.</p>
<p>For applications that require as-fast-as-possible reading of file contents, it
is better to use <code>fs.read()</code> directly and for application code to manage
reading the full contents of the file itself.</p>
<p>The Node.js GitHub issue <a href="https://github.com/nodejs/node/issues/25741">#25741</a> provides more information and a detailed
analysis on the performance of <code>fs.readFile()</code> for multiple file sizes in
different Node.js versions.</p>
<h4><code>fs.readlink(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsreadlinkpath-options-callback" id="all_fs_fsreadlinkpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readlink_path_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</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>
<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>linkString</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
</ul>
<p>Reads the contents of the symbolic link referred to by <code>path</code>. The callback gets
two arguments <code>(err, linkString)</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/readlink.2.html"><code>readlink(2)</code></a> documentation for more details.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the link path passed to the callback. If the <code>encoding</code> is set to <code>'buffer'</code>,
the link path returned will be passed as a <a href="#all_buffer_class-buffer" class="type"><Buffer></a> object.</p>
<h4><code>fs.readv(fd, buffers[, position], callback)</code><span><a class="mark" href="#all_fs_fsreadvfd-buffers-position-callback" id="all_fs_fsreadvfd-buffers-position-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readv_fd_buffers_position_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>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>v13.13.0, v12.17.0</td>
<td><p><span>Added in: v13.13.0, v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type"><ArrayBufferView[]></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</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>
<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>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type"><ArrayBufferView[]></a></li>
</ul>
</li>
</ul>
<p>Read from a file specified by <code>fd</code> and write to an array of <code>ArrayBufferView</code>s
using <code>readv()</code>.</p>
<p><code>position</code> is the offset from the beginning of the file from where data
should be read. If <code>typeof position !== 'number'</code>, the data will be read
from the current position.</p>
<p>The callback will be given three arguments: <code>err</code>, <code>bytesRead</code>, and
<code>buffers</code>. <code>bytesRead</code> is how many bytes were read from the file.</p>
<p>If this method is invoked as its <a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed version, it returns
a promise for an <code>Object</code> with <code>bytesRead</code> and <code>buffers</code> properties.</p>
<h4><code>fs.realpath(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsrealpathpath-options-callback" id="all_fs_fsrealpathpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_realpath_path_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Pipe/Socket resolve support was added.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v6.4.0</td>
<td><p>Calling <code>realpath</code> now works again for various edge cases on Windows.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>cache</code> parameter was removed.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</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>
<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>resolvedPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
</ul>
<p>Asynchronously computes the canonical pathname by resolving <code>.</code>, <code>..</code>, and
symbolic links.</p>
<p>A canonical pathname is not necessarily unique. Hard links and bind mounts can
expose a file system entity through many pathnames.</p>
<p>This function behaves like <a href="http://man7.org/linux/man-pages/man3/realpath.3.html"><code>realpath(3)</code></a>, with some exceptions:</p>
<ol>
<li>
<p>No case conversion is performed on case-insensitive file systems.</p>
</li>
<li>
<p>The maximum number of symbolic links is platform-independent and generally
(much) higher than what the native <a href="http://man7.org/linux/man-pages/man3/realpath.3.html"><code>realpath(3)</code></a> implementation supports.</p>
</li>
</ol>
<p>The <code>callback</code> gets two arguments <code>(err, resolvedPath)</code>. May use <code>process.cwd</code>
to resolve relative paths.</p>
<p>Only paths that can be converted to UTF8 strings are supported.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the path passed to the callback. If the <code>encoding</code> is set to <code>'buffer'</code>,
the path returned will be passed as a <a href="#all_buffer_class-buffer" class="type"><Buffer></a> object.</p>
<p>If <code>path</code> resolves to a socket or a pipe, the function will return a system
dependent name for that object.</p>
<p>A path that does not exist results in an ENOENT error.
<code>error.path</code> is the absolute file path.</p>
<h4><code>fs.realpath.native(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsrealpathnativepath-options-callback" id="all_fs_fsrealpathnativepath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_realpath_native_path_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>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>v9.2.0</td>
<td><p><span>Added in: v9.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</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>
<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>resolvedPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man3/realpath.3.html"><code>realpath(3)</code></a>.</p>
<p>The <code>callback</code> gets two arguments <code>(err, resolvedPath)</code>.</p>
<p>Only paths that can be converted to UTF8 strings are supported.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the path passed to the callback. If the <code>encoding</code> is set to <code>'buffer'</code>,
the path returned will be passed as a <a href="#all_buffer_class-buffer" class="type"><Buffer></a> object.</p>
<p>On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on <code>/proc</code> in order for this function to work. Glibc does not have
this restriction.</p>
<h4><code>fs.rename(oldPath, newPath, callback)</code><span><a class="mark" href="#all_fs_fsrenameoldpath-newpath-callback" id="all_fs_fsrenameoldpath-newpath-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_rename_oldpath_newpath_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>oldPath</code> and <code>newPath</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>oldPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Asynchronously rename file at <code>oldPath</code> to the pathname provided
as <code>newPath</code>. In the case that <code>newPath</code> already exists, it will
be overwritten. If there is a directory at <code>newPath</code>, an error will
be raised instead. No arguments other than a possible exception are
given to the completion callback.</p>
<p>See also: <a href="http://man7.org/linux/man-pages/man2/rename.2.html"><code>rename(2)</code></a>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { rename } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">rename</span>(<span class="hljs-string">'oldFile.txt'</span>, <span class="hljs-string">'newFile.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Rename complete!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.rmdir(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsrmdirpath-options-callback" id="all_fs_fsrmdirpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_rmdir_path_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>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>v16.0.0</td>
<td><p>Using <code>fs.rmdir(path, { recursive: true })</code> on a <code>path</code> that is a file is no longer permitted and results in an <code>ENOENT</code> error on Windows and an <code>ENOTDIR</code> error on POSIX.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Using <code>fs.rmdir(path, { recursive: true })</code> on a <code>path</code> that does not exist is no longer permitted and results in a <code>ENOENT</code> error.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>The <code>recursive</code> option is deprecated, using it triggers a deprecation warning.</p></td></tr>
<tr><td>v14.14.0</td>
<td><p>The <code>recursive</code> option is deprecated, use <code>fs.rm</code> instead.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p>The <code>maxBusyTries</code> option is renamed to <code>maxRetries</code>, and its default is 0. The <code>emfileWait</code> option has been removed, and <code>EMFILE</code> errors use the same retry logic as other errors. The <code>retryDelay</code> option is now supported. <code>ENFILE</code> errors are now retried.</p></td></tr>
<tr><td>v12.10.0</td>
<td><p>The <code>recursive</code>, <code>maxBusyTries</code>, and <code>emfileWait</code> options are now supported.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameters can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>maxRetries</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> If an <code>EBUSY</code>, <code>EMFILE</code>, <code>ENFILE</code>, <code>ENOTEMPTY</code>, or
<code>EPERM</code> error is encountered, Node.js retries the operation with a linear
backoff wait of <code>retryDelay</code> milliseconds longer on each try. This option
represents the number of retries. This option is ignored if the <code>recursive</code>
option is not <code>true</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, perform a recursive directory removal. In
recursive mode, operations are retried on failure. <strong>Default:</strong> <code>false</code>.
<strong>Deprecated.</strong></li>
<li><code>retryDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The amount of time in milliseconds to wait between
retries. This option is ignored if the <code>recursive</code> option is not <code>true</code>.
<strong>Default:</strong> <code>100</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>
<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>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/rmdir.2.html"><code>rmdir(2)</code></a>. No arguments other than a possible exception are given
to the completion callback.</p>
<p>Using <code>fs.rmdir()</code> on a file (not a directory) results in an <code>ENOENT</code> error on
Windows and an <code>ENOTDIR</code> error on POSIX.</p>
<p>To get a behavior similar to the <code>rm -rf</code> Unix command, use <a href="#all_fs_fsrmpath-options-callback"><code>fs.rm()</code></a>
with options <code>{ recursive: true, force: true }</code>.</p>
<h4><code>fs.rm(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsrmpath-options-callback" id="all_fs_fsrmpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_rm_path_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>v17.3.0, v16.14.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v14.14.0</td>
<td><p><span>Added in: v14.14.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>force</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, exceptions will be ignored if <code>path</code> does
not exist. <strong>Default:</strong> <code>false</code>.</li>
<li><code>maxRetries</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> If an <code>EBUSY</code>, <code>EMFILE</code>, <code>ENFILE</code>, <code>ENOTEMPTY</code>, or
<code>EPERM</code> error is encountered, Node.js will retry the operation with a linear
backoff wait of <code>retryDelay</code> milliseconds longer on each try. This option
represents the number of retries. This option is ignored if the <code>recursive</code>
option is not <code>true</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, perform a recursive removal. In
recursive mode operations are retried on failure. <strong>Default:</strong> <code>false</code>.</li>
<li><code>retryDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The amount of time in milliseconds to wait between
retries. This option is ignored if the <code>recursive</code> option is not <code>true</code>.
<strong>Default:</strong> <code>100</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>
<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>
</ul>
</li>
</ul>
<p>Asynchronously removes files and directories (modeled on the standard POSIX <code>rm</code>
utility). No arguments other than a possible exception are given to the
completion callback.</p>
<h4><code>fs.stat(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsstatpath-options-callback" id="all_fs_fsstatpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_stat_path_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>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>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned
<a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</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>
<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>stats</code> <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/stat.2.html"><code>stat(2)</code></a>. The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is an <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object.</p>
<p>In case of an error, the <code>err.code</code> will be one of <a href="#all_errors_common-system-errors">Common System Errors</a>.</p>
<p><a href="#all_fs_fsstatpath-options-callback"><code>fs.stat()</code></a> follows symbolic links. Use <a href="#all_fs_fslstatpath-options-callback"><code>fs.lstat()</code></a> to look at the
links themselves.</p>
<p>Using <code>fs.stat()</code> to check for the existence of a file before calling
<code>fs.open()</code>, <code>fs.readFile()</code>, or <code>fs.writeFile()</code> is not recommended.
Instead, user code should open/read/write the file directly and handle the
error raised if the file is not available.</p>
<p>To check if a file exists without manipulating it afterwards, <a href="#all_fs_fsaccesspath-mode-callback"><code>fs.access()</code></a>
is recommended.</p>
<p>For example, given the following directory structure:</p>
<pre><code class="language-text">- txtDir
-- file.txt
- app.js</code> <button class="copy-button">copy</button></pre>
<p>The next program will check for the stats of the given paths:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> pathsToCheck = [<span class="hljs-string">'./txtDir'</span>, <span class="hljs-string">'./txtDir/file.txt'</span>];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < pathsToCheck.<span class="hljs-property">length</span>; i++) {
<span class="hljs-title function_">stat</span>(pathsToCheck[i], <span class="hljs-function">(<span class="hljs-params">err, stats</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stats.<span class="hljs-title function_">isDirectory</span>());
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stats);
});
}</code> <button class="copy-button">copy</button></pre>
<p>The resulting output will resemble:</p>
<pre><code class="language-console">true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.statfs(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsstatfspath-options-callback" id="all_fs_fsstatfspath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_statfs_path_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned
<a href="#all_fs_class-fsstatfs" class="type"><fs.StatFs></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</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>
<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>stats</code> <a href="#all_fs_class-fsstatfs" class="type"><fs.StatFs></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/statfs.2.html"><code>statfs(2)</code></a>. Returns information about the mounted file system which
contains <code>path</code>. The callback gets two arguments <code>(err, stats)</code> where <code>stats</code>
is an <a href="#all_fs_class-fsstatfs" class="type"><fs.StatFs></a> object.</p>
<p>In case of an error, the <code>err.code</code> will be one of <a href="#all_errors_common-system-errors">Common System Errors</a>.</p>
<h4><code>fs.symlink(target, path[, type], callback)</code><span><a class="mark" href="#all_fs_fssymlinktarget-path-type-callback" id="all_fs_fssymlinktarget-path-type-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_symlink_target_path_type_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>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>v12.0.0</td>
<td><p>If the <code>type</code> argument is left undefined, Node will autodetect <code>target</code> type and automatically select <code>dir</code> or <code>file</code>.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>target</code> and <code>path</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>type</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> <strong>Default:</strong> <code>null</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>
<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>
</ul>
</li>
</ul>
<p>Creates the link called <code>path</code> pointing to <code>target</code>. No arguments other than a
possible exception are given to the completion callback.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/symlink.2.html"><code>symlink(2)</code></a> documentation for more details.</p>
<p>The <code>type</code> argument is only available on Windows and ignored on other platforms.
It can be set to <code>'dir'</code>, <code>'file'</code>, or <code>'junction'</code>. If the <code>type</code> argument is
not a string, Node.js will autodetect <code>target</code> type and use <code>'file'</code> or <code>'dir'</code>.
If the <code>target</code> does not exist, <code>'file'</code> will be used. Windows junction points
require the destination path to be absolute. When using <code>'junction'</code>, the
<code>target</code> argument will automatically be normalized to absolute path. Junction
points on NTFS volumes can only point to directories.</p>
<p>Relative targets are relative to the link's parent directory.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { symlink } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">symlink</span>(<span class="hljs-string">'./mew'</span>, <span class="hljs-string">'./mewtwo'</span>, callback);</code> <button class="copy-button">copy</button></pre>
<p>The above example creates a symbolic link <code>mewtwo</code> which points to <code>mew</code> in the
same directory:</p>
<pre><code class="language-bash">$ tree .
.
├── mew
└── mewtwo -> ./mew</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.truncate(path[, len], callback)</code><span><a class="mark" href="#all_fs_fstruncatepath-len-callback" id="all_fs_fstruncatepath-len-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_truncate_path_len_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>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>v16.0.0</td>
<td><p>The error returned may be an <code>AggregateError</code> if more than one error is returned.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.8.6</td>
<td><p><span>Added in: v0.8.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</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>
<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 href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError" class="type"><AggregateError></a></li>
</ul>
</li>
</ul>
<p>Truncates the file. No arguments other than a possible exception are
given to the completion callback. A file descriptor can also be passed as the
first argument. In this case, <code>fs.ftruncate()</code> is called.</p>
<pre class="with-51-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> { truncate } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// Assuming that 'path/file.txt' is a regular file.</span>
<span class="hljs-title function_">truncate</span>(<span class="hljs-string">'path/file.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'path/file.txt was truncated'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { truncate } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-comment">// Assuming that 'path/file.txt' is a regular file.</span>
<span class="hljs-title function_">truncate</span>(<span class="hljs-string">'path/file.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'path/file.txt was truncated'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Passing a file descriptor is deprecated and may result in an error being thrown
in the future.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/truncate.2.html"><code>truncate(2)</code></a> documentation for more details.</p>
<h4><code>fs.unlink(path, callback)</code><span><a class="mark" href="#all_fs_fsunlinkpath-callback" id="all_fs_fsunlinkpath-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_unlink_path_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Asynchronously removes a file or symbolic link. No arguments other than a
possible exception are given to the completion callback.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { unlink } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// Assuming that 'path/file.txt' is a regular file.</span>
<span class="hljs-title function_">unlink</span>(<span class="hljs-string">'path/file.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'path/file.txt was deleted'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p><code>fs.unlink()</code> will not work on a directory, empty or otherwise. To remove a
directory, use <a href="#all_fs_fsrmdirpath-options-callback"><code>fs.rmdir()</code></a>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a> documentation for more details.</p>
<h4><code>fs.unwatchFile(filename[, listener])</code><span><a class="mark" href="#all_fs_fsunwatchfilefilename-listener" id="all_fs_fsunwatchfilefilename-listener">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_unwatchfile_filename_listener"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Optional, a listener previously attached using
<code>fs.watchFile()</code></li>
</ul>
<p>Stop watching for changes on <code>filename</code>. If <code>listener</code> is specified, only that
particular listener is removed. Otherwise, <em>all</em> listeners are removed,
effectively stopping watching of <code>filename</code>.</p>
<p>Calling <code>fs.unwatchFile()</code> with a filename that is not being watched is a
no-op, not an error.</p>
<p>Using <a href="#all_fs_fswatchfilename-options-listener"><code>fs.watch()</code></a> is more efficient than <code>fs.watchFile()</code> and
<code>fs.unwatchFile()</code>. <code>fs.watch()</code> should be used instead of <code>fs.watchFile()</code>
and <code>fs.unwatchFile()</code> when possible.</p>
<h4><code>fs.utimes(path, atime, mtime, callback)</code><span><a class="mark" href="#all_fs_fsutimespath-atime-mtime-callback" id="all_fs_fsutimespath-atime-mtime-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_utimes_path_atime_mtime_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>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>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p><code>NaN</code>, <code>Infinity</code>, and <code>-Infinity</code> are no longer valid time specifiers.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v4.1.0</td>
<td><p>Numeric strings, <code>NaN</code>, and <code>Infinity</code> are now allowed time specifiers.</p></td></tr>
<tr><td>v0.4.2</td>
<td><p><span>Added in: v0.4.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
</ul>
</li>
</ul>
<p>Change the file system timestamps of the object referenced by <code>path</code>.</p>
<p>The <code>atime</code> and <code>mtime</code> arguments follow these rules:</p>
<ul>
<li>Values can be either numbers representing Unix epoch time in seconds,
<code>Date</code>s, or a numeric string like <code>'123456789.0'</code>.</li>
<li>If the value can not be converted to a number, or is <code>NaN</code>, <code>Infinity</code>, or
<code>-Infinity</code>, an <code>Error</code> will be thrown.</li>
</ul>
<h4><code>fs.watch(filename[, options][, listener])</code><span><a class="mark" href="#all_fs_fswatchfilename-options-listener" id="all_fs_fswatchfilename-options-listener">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_watch_filename_options_listener"></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.1.0</td>
<td><p>Added recursive support for Linux, AIX and IBMi.</p></td></tr>
<tr><td>v15.9.0, v14.17.0</td>
<td><p>Added support for closing the watcher with an AbortSignal.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The passed <code>options</code> object will never be modified.</p></td></tr>
<tr><td>v0.5.10</td>
<td><p><span>Added in: v0.5.10</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>persistent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether the process should continue to run
as long as files are being watched. <strong>Default:</strong> <code>true</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether all subdirectories should be
watched, or only the current directory. This applies when a directory is
specified, and only on supported platforms (See <a href="#all_fs_caveats">caveats</a>). <strong>Default:</strong>
<code>false</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> Specifies the character encoding to be used for the
filename passed to the listener. <strong>Default:</strong> <code>'utf8'</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows closing the watcher with an AbortSignal.</li>
</ul>
</li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> <strong>Default:</strong> <code>undefined</code>
<ul>
<li><code>eventType</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a></li>
</ul>
<p>Watch for changes on <code>filename</code>, where <code>filename</code> is either a file or a
directory.</p>
<p>The second argument is optional. If <code>options</code> is provided as a string, it
specifies the <code>encoding</code>. Otherwise <code>options</code> should be passed as an object.</p>
<p>The listener callback gets two arguments <code>(eventType, filename)</code>. <code>eventType</code>
is either <code>'rename'</code> or <code>'change'</code>, and <code>filename</code> is the name of the file
which triggered the event.</p>
<p>On most platforms, <code>'rename'</code> is emitted whenever a filename appears or
disappears in the directory.</p>
<p>The listener callback is attached to the <code>'change'</code> event fired by
<a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a>, but it is not the same thing as the <code>'change'</code> value of
<code>eventType</code>.</p>
<p>If a <code>signal</code> is passed, aborting the corresponding AbortController will close
the returned <a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a>.</p>
<h5>Caveats<span><a class="mark" href="#all_fs_caveats" id="all_fs_caveats">#</a></span><a aria-hidden="true" class="legacy" id="fs_caveats"></a></h5>
<p>The <code>fs.watch</code> API is not 100% consistent across platforms, and is
unavailable in some situations.</p>
<p>On Windows, no events will be emitted if the watched directory is moved or
renamed. An <code>EPERM</code> error is reported when the watched directory is deleted.</p>
<h6>Availability<span><a class="mark" href="#all_fs_availability" id="all_fs_availability">#</a></span><a aria-hidden="true" class="legacy" id="fs_availability"></a></h6>
<p>This feature depends on the underlying operating system providing a way
to be notified of file system changes.</p>
<ul>
<li>On Linux systems, this uses <a href="https://man7.org/linux/man-pages/man7/inotify.7.html"><code>inotify(7)</code></a>.</li>
<li>On BSD systems, this uses <a href="https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2"><code>kqueue(2)</code></a>.</li>
<li>On macOS, this uses <a href="https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2"><code>kqueue(2)</code></a> for files and <a href="https://developer.apple.com/documentation/coreservices/file_system_events"><code>FSEvents</code></a> for
directories.</li>
<li>On SunOS systems (including Solaris and SmartOS), this uses <a href="https://illumos.org/man/port_create"><code>event ports</code></a>.</li>
<li>On Windows systems, this feature depends on <a href="https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-readdirectorychangesw"><code>ReadDirectoryChangesW</code></a>.</li>
<li>On AIX systems, this feature depends on <a href="https://developer.ibm.com/articles/au-aix_event_infrastructure/"><code>AHAFS</code></a>, which must be enabled.</li>
<li>On IBM i systems, this feature is not supported.</li>
</ul>
<p>If the underlying functionality is not available for some reason, then
<code>fs.watch()</code> will not be able to function and may throw an exception.
For example, watching files or directories can be unreliable, and in some
cases impossible, on network file systems (NFS, SMB, etc) or host file systems
when using virtualization software such as Vagrant or Docker.</p>
<p>It is still possible to use <code>fs.watchFile()</code>, which uses stat polling, but
this method is slower and less reliable.</p>
<h6>Inodes<span><a class="mark" href="#all_fs_inodes" id="all_fs_inodes">#</a></span><a aria-hidden="true" class="legacy" id="fs_inodes"></a></h6>
<p>On Linux and macOS systems, <code>fs.watch()</code> resolves the path to an <a href="https://en.wikipedia.org/wiki/Inode">inode</a> and
watches the inode. If the watched path is deleted and recreated, it is assigned
a new inode. The watch will emit an event for the delete but will continue
watching the <em>original</em> inode. Events for the new inode will not be emitted.
This is expected behavior.</p>
<p>AIX files retain the same inode for the lifetime of a file. Saving and closing a
watched file on AIX will result in two notifications (one for adding new
content, and one for truncation).</p>
<h6>Filename argument<span><a class="mark" href="#all_fs_filename-argument" id="all_fs_filename-argument">#</a></span><a aria-hidden="true" class="legacy" id="fs_filename_argument"></a></h6>
<p>Providing <code>filename</code> argument in the callback is only supported on Linux,
macOS, Windows, and AIX. Even on supported platforms, <code>filename</code> is not always
guaranteed to be provided. Therefore, don't assume that <code>filename</code> argument is
always provided in the callback, and have some fallback logic if it is <code>null</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { watch } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">watch</span>(<span class="hljs-string">'somedir'</span>, <span class="hljs-function">(<span class="hljs-params">eventType, filename</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`event type is: <span class="hljs-subst">${eventType}</span>`</span>);
<span class="hljs-keyword">if</span> (filename) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`filename provided: <span class="hljs-subst">${filename}</span>`</span>);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'filename not provided'</span>);
}
});</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.watchFile(filename[, options], listener)</code><span><a class="mark" href="#all_fs_fswatchfilefilename-options-listener" id="all_fs_fswatchfilefilename-options-listener">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_watchfile_filename_options_listener"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.5.0</td>
<td><p>The <code>bigint</code> option is now supported.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>persistent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</code></li>
<li><code>interval</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>5007</code></li>
</ul>
</li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<ul>
<li><code>current</code> <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a></li>
<li><code>previous</code> <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a></li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsstatwatcher" class="type"><fs.StatWatcher></a></li>
</ul>
<p>Watch for changes on <code>filename</code>. The callback <code>listener</code> will be called each
time the file is accessed.</p>
<p>The <code>options</code> argument may be omitted. If provided, it should be an object. The
<code>options</code> object may contain a boolean named <code>persistent</code> that indicates
whether the process should continue to run as long as files are being watched.
The <code>options</code> object may specify an <code>interval</code> property indicating how often the
target should be polled in milliseconds.</p>
<p>The <code>listener</code> gets two arguments the current stat object and the previous
stat object:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { watchFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">watchFile</span>(<span class="hljs-string">'message.text'</span>, <span class="hljs-function">(<span class="hljs-params">curr, prev</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`the current mtime is: <span class="hljs-subst">${curr.mtime}</span>`</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`the previous mtime was: <span class="hljs-subst">${prev.mtime}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>These stat objects are instances of <code>fs.Stat</code>. If the <code>bigint</code> option is <code>true</code>,
the numeric values in these objects are specified as <code>BigInt</code>s.</p>
<p>To be notified when the file was modified, not just accessed, it is necessary
to compare <code>curr.mtimeMs</code> and <code>prev.mtimeMs</code>.</p>
<p>When an <code>fs.watchFile</code> operation results in an <code>ENOENT</code> error, it
will invoke the listener once, with all the fields zeroed (or, for dates, the
Unix Epoch). If the file is created later on, the listener will be called
again, with the latest stat objects. This is a change in functionality since
v0.10.</p>
<p>Using <a href="#all_fs_fswatchfilename-options-listener"><code>fs.watch()</code></a> is more efficient than <code>fs.watchFile</code> and
<code>fs.unwatchFile</code>. <code>fs.watch</code> should be used instead of <code>fs.watchFile</code> and
<code>fs.unwatchFile</code> when possible.</p>
<p>When a file being watched by <code>fs.watchFile()</code> disappears and reappears,
then the contents of <code>previous</code> in the second callback event (the file's
reappearance) will be the same as the contents of <code>previous</code> in the first
callback event (its disappearance).</p>
<p>This happens when:</p>
<ul>
<li>the file is deleted, followed by a restore</li>
<li>the file is renamed and then renamed a second time back to its original name</li>
</ul>
<h4><code>fs.write(fd, buffer, offset[, length[, position]], callback)</code><span><a class="mark" href="#all_fs_fswritefd-buffer-offset-length-position-callback" id="all_fs_fswritefd-buffer-offset-length-position-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_write_fd_buffer_offset_length_position_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>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>buffer</code> parameter won't coerce unsupported input to strings anymore.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>buffer</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.4.0</td>
<td><p>The <code>buffer</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>The <code>offset</code> and <code>length</code> parameters are optional now.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_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></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>buffer.byteLength - offset</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</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>
<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>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_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></li>
</ul>
</li>
</ul>
<p>Write <code>buffer</code> to the file specified by <code>fd</code>.</p>
<p><code>offset</code> determines the part of the buffer to be written, and <code>length</code> is
an integer specifying the number of bytes to write.</p>
<p><code>position</code> refers to the offset from the beginning of the file where this data
should be written. If <code>typeof position !== 'number'</code>, the data will be written
at the current position. See <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>.</p>
<p>The callback will be given three arguments <code>(err, bytesWritten, buffer)</code> where
<code>bytesWritten</code> specifies how many <em>bytes</em> were written from <code>buffer</code>.</p>
<p>If this method is invoked as its <a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed version, it returns
a promise for an <code>Object</code> with <code>bytesWritten</code> and <code>buffer</code> properties.</p>
<p>It is unsafe to use <code>fs.write()</code> multiple times on the same file without waiting
for the callback. For this scenario, <a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a> is
recommended.</p>
<p>On Linux, positional writes don't work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.</p>
<h4><code>fs.write(fd, buffer[, options], callback)</code><span><a class="mark" href="#all_fs_fswritefd-buffer-options-callback" id="all_fs_fswritefd-buffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_write_fd_buffer_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_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></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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>buffer.byteLength - offset</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>null</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>
<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>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_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></li>
</ul>
</li>
</ul>
<p>Write <code>buffer</code> to the file specified by <code>fd</code>.</p>
<p>Similar to the above <code>fs.write</code> function, this version takes an
optional <code>options</code> object. If no <code>options</code> object is specified, it will
default with the above values.</p>
<h4><code>fs.write(fd, string[, position[, encoding]], callback)</code><span><a class="mark" href="#all_fs_fswritefd-string-position-encoding-callback" id="all_fs_fswritefd-string-position-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_write_fd_string_position_encoding_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.0.0</td>
<td><p>Passing to the <code>string</code> parameter an object with an own <code>toString</code> function is no longer supported.</p></td></tr>
<tr><td>v17.8.0</td>
<td><p>Passing to the <code>string</code> parameter an object with an own <code>toString</code> function is deprecated.</p></td></tr>
<tr><td>v14.12.0</td>
<td><p>The <code>string</code> parameter will stringify an object with an explicit <code>toString</code> function.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>string</code> parameter won't coerce unsupported input to strings anymore.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>The <code>position</code> parameter is optional now.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.11.5</td>
<td><p><span>Added in: v0.11.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <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> <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>
<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>written</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</li>
</ul>
<p>Write <code>string</code> to the file specified by <code>fd</code>. If <code>string</code> is not a string,
an exception is thrown.</p>
<p><code>position</code> refers to the offset from the beginning of the file where this data
should be written. If <code>typeof position !== 'number'</code> the data will be written at
the current position. See <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>.</p>
<p><code>encoding</code> is the expected string encoding.</p>
<p>The callback will receive the arguments <code>(err, written, string)</code> where <code>written</code>
specifies how many <em>bytes</em> the passed string required to be written. Bytes
written is not necessarily the same as string characters written. See
<a href="#all_buffer_static-method-bufferbytelengthstring-encoding"><code>Buffer.byteLength</code></a>.</p>
<p>It is unsafe to use <code>fs.write()</code> multiple times on the same file without waiting
for the callback. For this scenario, <a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a> is
recommended.</p>
<p>On Linux, positional writes don't work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.</p>
<p>On Windows, if the file descriptor is connected to the console (e.g. <code>fd == 1</code>
or <code>stdout</code>) a string containing non-ASCII characters will not be rendered
properly by default, regardless of the encoding used.
It is possible to configure the console to render UTF-8 properly by changing the
active codepage with the <code>chcp 65001</code> command. See the <a href="https://ss64.com/nt/chcp.html">chcp</a> docs for more
details.</p>
<h4><code>fs.writeFile(file, data[, options], callback)</code><span><a class="mark" href="#all_fs_fswritefilefile-data-options-callback" id="all_fs_fswritefilefile-data-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writefile_file_data_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>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v19.0.0</td>
<td><p>Passing to the <code>string</code> parameter an object with an own <code>toString</code> function is no longer supported.</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>v17.8.0</td>
<td><p>Passing to the <code>string</code> parameter an object with an own <code>toString</code> function is deprecated.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>The error returned may be an <code>AggregateError</code> if more than one error is returned.</p></td></tr>
<tr><td>v15.2.0, v14.17.0</td>
<td><p>The options argument may include an AbortSignal to abort an ongoing writeFile request.</p></td></tr>
<tr><td>v14.12.0</td>
<td><p>The <code>data</code> parameter will stringify an object with an explicit <code>toString</code> function.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>data</code> parameter won't coerce unsupported input to strings anymore.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>data</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.4.0</td>
<td><p>The <code>data</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>file</code> parameter can be a file descriptor now.</p></td></tr>
<tr><td>v0.1.29</td>
<td><p><span>Added in: v0.1.29</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> filename or file descriptor</li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If all data is successfully written to the file, and
<code>flush</code> is <code>true</code>, <code>fs.fsync()</code> is used to flush the data.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows aborting an in-progress writeFile</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>
<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 href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError" class="type"><AggregateError></a></li>
</ul>
</li>
</ul>
<p>When <code>file</code> is a filename, asynchronously writes data to the file, replacing the
file if it already exists. <code>data</code> can be a string or a buffer.</p>
<p>When <code>file</code> is a file descriptor, the behavior is similar to calling
<code>fs.write()</code> directly (which is recommended). See the notes below on using
a file descriptor.</p>
<p>The <code>encoding</code> option is ignored if <code>data</code> is a buffer.</p>
<p>The <code>mode</code> option only affects the newly created file. See <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>
for more details.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { writeFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello Node.js'</span>));
<span class="hljs-title function_">writeFile</span>(<span class="hljs-string">'message.txt'</span>, data, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The file has been saved!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>If <code>options</code> is a string, then it specifies the encoding:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { writeFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">writeFile</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'Hello Node.js'</span>, <span class="hljs-string">'utf8'</span>, callback);</code> <button class="copy-button">copy</button></pre>
<p>It is unsafe to use <code>fs.writeFile()</code> multiple times on the same file without
waiting for the callback. For this scenario, <a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a> is
recommended.</p>
<p>Similarly to <code>fs.readFile</code> - <code>fs.writeFile</code> is a convenience method that
performs multiple <code>write</code> calls internally to write the buffer passed to it.
For performance sensitive code consider using <a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a>.</p>
<p>It is possible to use an <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> to cancel an <code>fs.writeFile()</code>.
Cancelation is "best effort", and some amount of data is likely still
to be written.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { writeFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</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> { signal } = controller;
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello Node.js'</span>));
<span class="hljs-title function_">writeFile</span>(<span class="hljs-string">'message.txt'</span>, data, { signal }, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-comment">// When a request is aborted - the callback is called with an AbortError</span>
});
<span class="hljs-comment">// When the request should be aborted</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<p>Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering <code>fs.writeFile</code> performs.</p>
<h5>Using <code>fs.writeFile()</code> with file descriptors<span><a class="mark" href="#all_fs_using-fswritefile-with-file-descriptors" id="all_fs_using-fswritefile-with-file-descriptors">#</a></span><a aria-hidden="true" class="legacy" id="fs_using_fs_writefile_with_file_descriptors"></a></h5>
<p>When <code>file</code> is a file descriptor, the behavior is almost identical to directly
calling <code>fs.write()</code> like:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { write } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-title function_">write</span>(fd, <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(data, options.<span class="hljs-property">encoding</span>), callback);</code> <button class="copy-button">copy</button></pre>
<p>The difference from directly calling <code>fs.write()</code> is that under some unusual
conditions, <code>fs.write()</code> might write only part of the buffer and need to be
retried to write the remaining data, whereas <code>fs.writeFile()</code> retries until
the data is entirely written (or an error occurs).</p>
<p>The implications of this are a common source of confusion. In
the file descriptor case, the file is not replaced! The data is not necessarily
written to the beginning of the file, and the file's original data may remain
before and/or after the newly written data.</p>
<p>For example, if <code>fs.writeFile()</code> is called twice in a row, first to write the
string <code>'Hello'</code>, then to write the string <code>', World'</code>, the file would contain
<code>'Hello, World'</code>, and might contain some of the file's original data (depending
on the size of the original file, and the position of the file descriptor). If
a file name had been used instead of a descriptor, the file would be guaranteed
to contain only <code>', World'</code>.</p>
<h4><code>fs.writev(fd, buffers[, position], callback)</code><span><a class="mark" href="#all_fs_fswritevfd-buffers-position-callback" id="all_fs_fswritevfd-buffers-position-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writev_fd_buffers_position_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>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>v12.9.0</td>
<td><p><span>Added in: v12.9.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type"><ArrayBufferView[]></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</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>
<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>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type"><ArrayBufferView[]></a></li>
</ul>
</li>
</ul>
<p>Write an array of <code>ArrayBufferView</code>s to the file specified by <code>fd</code> using
<code>writev()</code>.</p>
<p><code>position</code> is the offset from the beginning of the file where this data
should be written. If <code>typeof position !== 'number'</code>, the data will be written
at the current position.</p>
<p>The callback will be given three arguments: <code>err</code>, <code>bytesWritten</code>, and
<code>buffers</code>. <code>bytesWritten</code> is how many bytes were written from <code>buffers</code>.</p>
<p>If this method is <a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed, it returns a promise for an
<code>Object</code> with <code>bytesWritten</code> and <code>buffers</code> properties.</p>
<p>It is unsafe to use <code>fs.writev()</code> multiple times on the same file without
waiting for the callback. For this scenario, use <a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a>.</p>
<p>On Linux, positional writes don't work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.</p>
</section><section><h3>Synchronous API<span><a class="mark" href="#all_fs_synchronous-api" id="all_fs_synchronous-api">#</a></span><a aria-hidden="true" class="legacy" id="fs_synchronous_api"></a></h3>
<p>The synchronous APIs perform all operations synchronously, blocking the
event loop until the operation completes or fails.</p>
<h4><code>fs.accessSync(path[, mode])</code><span><a class="mark" href="#all_fs_fsaccesssyncpath-mode" id="all_fs_fsaccesssyncpath-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_accesssync_path_mode"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</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>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>fs.constants.F_OK</code></li>
</ul>
<p>Synchronously tests a user's permissions for the file or directory specified
by <code>path</code>. The <code>mode</code> argument is an optional integer that specifies the
accessibility checks to be performed. <code>mode</code> should be either the value
<code>fs.constants.F_OK</code> or a mask consisting of the bitwise OR of any of
<code>fs.constants.R_OK</code>, <code>fs.constants.W_OK</code>, and <code>fs.constants.X_OK</code> (e.g.
<code>fs.constants.W_OK | fs.constants.R_OK</code>). Check <a href="#all_fs_file-access-constants">File access constants</a> for
possible values of <code>mode</code>.</p>
<p>If any of the accessibility checks fail, an <code>Error</code> will be thrown. Otherwise,
the method will return <code>undefined</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { accessSync, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">accessSync</span>(<span class="hljs-string">'etc/passwd'</span>, constants.<span class="hljs-property">R_OK</span> | constants.<span class="hljs-property">W_OK</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'can read/write'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'no access!'</span>);
}</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.appendFileSync(path, data[, options])</code><span><a class="mark" href="#all_fs_fsappendfilesyncpath-data-options" id="all_fs_fsappendfilesyncpath-data-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_appendfilesync_path_data_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>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The passed <code>options</code> object will never be modified.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>file</code> parameter can be a file descriptor now.</p></td></tr>
<tr><td>v0.6.7</td>
<td><p><span>Added in: v0.6.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> filename or file descriptor</li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the underlying file descriptor is flushed
prior to closing it. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Synchronously append data to a file, creating the file if it does not yet
exist. <code>data</code> can be a string or a <a href="#all_buffer_class-buffer" class="type"><Buffer></a>.</p>
<p>The <code>mode</code> option only affects the newly created file. See <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>
for more details.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { appendFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">appendFileSync</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'data to append'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The "data to append" was appended to file!'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-comment">/* Handle the error */</span>
}</code> <button class="copy-button">copy</button></pre>
<p>If <code>options</code> is a string, then it specifies the encoding:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { appendFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">appendFileSync</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'data to append'</span>, <span class="hljs-string">'utf8'</span>);</code> <button class="copy-button">copy</button></pre>
<p>The <code>path</code> may be specified as a numeric file descriptor that has been opened
for appending (using <code>fs.open()</code> or <code>fs.openSync()</code>). The file descriptor will
not be closed automatically.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { openSync, closeSync, appendFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">let</span> fd;
<span class="hljs-keyword">try</span> {
fd = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'a'</span>);
<span class="hljs-title function_">appendFileSync</span>(fd, <span class="hljs-string">'data to append'</span>, <span class="hljs-string">'utf8'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-comment">/* Handle the error */</span>
} <span class="hljs-keyword">finally</span> {
<span class="hljs-keyword">if</span> (fd !== <span class="hljs-literal">undefined</span>)
<span class="hljs-title function_">closeSync</span>(fd);
}</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.chmodSync(path, mode)</code><span><a class="mark" href="#all_fs_fschmodsyncpath-mode" id="all_fs_fschmodsyncpath-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_chmodsync_path_mode"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.6.7</td>
<td><p><span>Added in: v0.6.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>mode</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#Number_type" class="type"><integer></a></li>
</ul>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fschmodpath-mode-callback"><code>fs.chmod()</code></a>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a> documentation for more detail.</p>
<h4><code>fs.chownSync(path, uid, gid)</code><span><a class="mark" href="#all_fs_fschownsyncpath-uid-gid" id="all_fs_fschownsyncpath-uid-gid">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_chownsync_path_uid_gid"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.1.97</td>
<td><p><span>Added in: v0.1.97</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Synchronously changes owner and group of a file. Returns <code>undefined</code>.
This is the synchronous version of <a href="#all_fs_fschownpath-uid-gid-callback"><code>fs.chown()</code></a>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a> documentation for more detail.</p>
<h4><code>fs.closeSync(fd)</code><span><a class="mark" href="#all_fs_fsclosesyncfd" id="all_fs_fsclosesyncfd">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_closesync_fd"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Closes the file descriptor. Returns <code>undefined</code>.</p>
<p>Calling <code>fs.closeSync()</code> on any file descriptor (<code>fd</code>) that is currently in use
through any other <code>fs</code> operation may lead to undefined behavior.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/close.2.html"><code>close(2)</code></a> documentation for more detail.</p>
<h4><code>fs.copyFileSync(src, dest[, mode])</code><span><a class="mark" href="#all_fs_fscopyfilesyncsrc-dest-mode" id="all_fs_fscopyfilesyncsrc-dest-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_copyfilesync_src_dest_mode"></a></h4>
<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>Changed <code>flags</code> argument to <code>mode</code> and imposed stricter type validation.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> source filename to copy</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> destination filename of the copy operation</li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> modifiers for copy operation. <strong>Default:</strong> <code>0</code>.</li>
</ul>
<p>Synchronously copies <code>src</code> to <code>dest</code>. By default, <code>dest</code> is overwritten if it
already exists. Returns <code>undefined</code>. Node.js makes no guarantees about the
atomicity of the copy operation. If an error occurs after the destination file
has been opened for writing, Node.js will attempt to remove the destination.</p>
<p><code>mode</code> is an optional integer that specifies the behavior
of the copy operation. It is possible to create a mask consisting of the bitwise
OR of two or more values (e.g.
<code>fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE</code>).</p>
<ul>
<li><code>fs.constants.COPYFILE_EXCL</code>: The copy operation will fail if <code>dest</code> already
exists.</li>
<li><code>fs.constants.COPYFILE_FICLONE</code>: The copy operation will attempt to create a
copy-on-write reflink. If the platform does not support copy-on-write, then a
fallback copy mechanism is used.</li>
<li><code>fs.constants.COPYFILE_FICLONE_FORCE</code>: The copy operation will attempt to
create a copy-on-write reflink. If the platform does not support
copy-on-write, then the operation will fail.</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { copyFileSync, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// destination.txt will be created or overwritten by default.</span>
<span class="hljs-title function_">copyFileSync</span>(<span class="hljs-string">'source.txt'</span>, <span class="hljs-string">'destination.txt'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'source.txt was copied to destination.txt'</span>);
<span class="hljs-comment">// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.</span>
<span class="hljs-title function_">copyFileSync</span>(<span class="hljs-string">'source.txt'</span>, <span class="hljs-string">'destination.txt'</span>, constants.<span class="hljs-property">COPYFILE_EXCL</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.cpSync(src, dest[, options])</code><span><a class="mark" href="#all_fs_fscpsyncsrc-dest-options" id="all_fs_fscpsyncsrc-dest-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_cpsync_src_dest_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>v20.1.0</td>
<td><p>Accept an additional <code>mode</code> option to specify the copy behavior as the <code>mode</code> argument of <code>fs.copyFile()</code>.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p>Accepts an additional <code>verbatimSymlinks</code> option to specify whether to perform path resolution for symlinks.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> source path to copy.</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> destination path to copy to.</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>dereference</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> dereference symlinks. <strong>Default:</strong> <code>false</code>.</li>
<li><code>errorOnExist</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> when <code>force</code> is <code>false</code>, and the destination
exists, throw an error. <strong>Default:</strong> <code>false</code>.</li>
<li><code>filter</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Function to filter copied files/directories. Return
<code>true</code> to copy the item, <code>false</code> to ignore it. When ignoring a directory,
all of its contents will be skipped as well. <strong>Default:</strong> <code>undefined</code>
<ul>
<li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> source path to copy.</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> destination path to copy to.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Any non-<code>Promise</code> value that is coercible
to <code>boolean</code>.</li>
</ul>
</li>
<li><code>force</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> overwrite existing file or directory. The copy
operation will ignore errors if you set this to false and the destination
exists. Use the <code>errorOnExist</code> option to change this behavior.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> modifiers for copy operation. <strong>Default:</strong> <code>0</code>.
See <code>mode</code> flag of <a href="#all_fs_fscopyfilesyncsrc-dest-mode"><code>fs.copyFileSync()</code></a>.</li>
<li><code>preserveTimestamps</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> timestamps from <code>src</code> will
be preserved. <strong>Default:</strong> <code>false</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> copy directories recursively <strong>Default:</strong> <code>false</code></li>
<li><code>verbatimSymlinks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, path resolution for symlinks will
be skipped. <strong>Default:</strong> <code>false</code></li>
</ul>
</li>
</ul>
<p>Synchronously copies the entire directory structure from <code>src</code> to <code>dest</code>,
including subdirectories and files.</p>
<p>When copying a directory to another directory, globs are not supported and
behavior is similar to <code>cp dir1/ dir2/</code>.</p>
<h4><code>fs.existsSync(path)</code><span><a class="mark" href="#all_fs_fsexistssyncpath" id="all_fs_fsexistssyncpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_existssync_path"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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 <code>true</code> if the path exists, <code>false</code> otherwise.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fsexistspath-callback"><code>fs.exists()</code></a>.</p>
<p><code>fs.exists()</code> is deprecated, but <code>fs.existsSync()</code> is not. The <code>callback</code>
parameter to <code>fs.exists()</code> accepts parameters that are inconsistent with other
Node.js callbacks. <code>fs.existsSync()</code> does not use a callback.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { existsSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">existsSync</span>(<span class="hljs-string">'/etc/passwd'</span>))
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The path exists.'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.fchmodSync(fd, mode)</code><span><a class="mark" href="#all_fs_fsfchmodsyncfd-mode" id="all_fs_fsfchmodsyncfd-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fchmodsync_fd_mode"></a></h4>
<div class="api_metadata">
<span>Added in: v0.4.7</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>mode</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#Number_type" class="type"><integer></a></li>
</ul>
<p>Sets the permissions on the file. Returns <code>undefined</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/fchmod.2.html"><code>fchmod(2)</code></a> documentation for more detail.</p>
<h4><code>fs.fchownSync(fd, uid, gid)</code><span><a class="mark" href="#all_fs_fsfchownsyncfd-uid-gid" id="all_fs_fsfchownsyncfd-uid-gid">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fchownsync_fd_uid_gid"></a></h4>
<div class="api_metadata">
<span>Added in: v0.4.7</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The file's new owner's user id.</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The file's new group's group id.</li>
</ul>
<p>Sets the owner of the file. Returns <code>undefined</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/fchown.2.html"><code>fchown(2)</code></a> documentation for more detail.</p>
<h4><code>fs.fdatasyncSync(fd)</code><span><a class="mark" href="#all_fs_fsfdatasyncsyncfd" id="all_fs_fsfdatasyncsyncfd">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fdatasyncsync_fd"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.96</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Forces all currently queued I/O operations associated with the file to the
operating system's synchronized I/O completion state. Refer to the POSIX
<a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html"><code>fdatasync(2)</code></a> documentation for details. Returns <code>undefined</code>.</p>
<h4><code>fs.fstatSync(fd[, options])</code><span><a class="mark" href="#all_fs_fsfstatsyncfd-options" id="all_fs_fsfstatsyncfd-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fstatsync_fd_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>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v0.1.95</td>
<td><p><span>Added in: v0.1.95</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></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>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned
<a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a></li>
</ul>
<p>Retrieves the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> for the file descriptor.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/fstat.2.html"><code>fstat(2)</code></a> documentation for more detail.</p>
<h4><code>fs.fsyncSync(fd)</code><span><a class="mark" href="#all_fs_fsfsyncsyncfd" id="all_fs_fsfsyncsyncfd">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fsyncsync_fd"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.96</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Request that all data for the open file descriptor is flushed to the storage
device. The specific implementation is operating system and device specific.
Refer to the POSIX <a href="http://man7.org/linux/man-pages/man2/fsync.2.html"><code>fsync(2)</code></a> documentation for more detail. Returns <code>undefined</code>.</p>
<h4><code>fs.ftruncateSync(fd[, len])</code><span><a class="mark" href="#all_fs_fsftruncatesyncfd-len" id="all_fs_fsftruncatesyncfd-len">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_ftruncatesync_fd_len"></a></h4>
<div class="api_metadata">
<span>Added in: v0.8.6</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li>
</ul>
<p>Truncates the file descriptor. Returns <code>undefined</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fsftruncatefd-len-callback"><code>fs.ftruncate()</code></a>.</p>
<h4><code>fs.futimesSync(fd, atime, mtime)</code><span><a class="mark" href="#all_fs_fsfutimessyncfd-atime-mtime" id="all_fs_fsfutimessyncfd-atime-mtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_futimessync_fd_atime_mtime"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.1.0</td>
<td><p>Numeric strings, <code>NaN</code>, and <code>Infinity</code> are now allowed time specifiers.</p></td></tr>
<tr><td>v0.4.2</td>
<td><p><span>Added in: v0.4.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
</ul>
<p>Synchronous version of <a href="#all_fs_fsfutimesfd-atime-mtime-callback"><code>fs.futimes()</code></a>. Returns <code>undefined</code>.</p>
<h4><code>fs.lchmodSync(path, mode)</code><span><a class="mark" href="#all_fs_fslchmodsyncpath-mode" id="all_fs_fslchmodsyncpath-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lchmodsync_path_mode"></a></h4>
<div class="api_metadata">
<span>Deprecated since: v0.4.7</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Changes the permissions on a symbolic link. Returns <code>undefined</code>.</p>
<p>This method is only implemented on macOS.</p>
<p>See the POSIX <a href="https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2"><code>lchmod(2)</code></a> documentation for more detail.</p>
<h4><code>fs.lchownSync(path, uid, gid)</code><span><a class="mark" href="#all_fs_fslchownsyncpath-uid-gid" id="all_fs_fslchownsyncpath-uid-gid">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lchownsync_path_uid_gid"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.6.0</td>
<td><p>This API is no longer deprecated.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The file's new owner's user id.</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The file's new group's group id.</li>
</ul>
<p>Set the owner for the path. Returns <code>undefined</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/lchown.2.html"><code>lchown(2)</code></a> documentation for more details.</p>
<h4><code>fs.lutimesSync(path, atime, mtime)</code><span><a class="mark" href="#all_fs_fslutimessyncpath-atime-mtime" id="all_fs_fslutimessyncpath-atime-mtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lutimessync_path_atime_mtime"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
</ul>
<p>Change the file system timestamps of the symbolic link referenced by <code>path</code>.
Returns <code>undefined</code>, or throws an exception when parameters are incorrect or
the operation fails. This is the synchronous version of <a href="#all_fs_fslutimespath-atime-mtime-callback"><code>fs.lutimes()</code></a>.</p>
<h4><code>fs.linkSync(existingPath, newPath)</code><span><a class="mark" href="#all_fs_fslinksyncexistingpath-newpath" id="all_fs_fslinksyncexistingpath-newpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_linksync_existingpath_newpath"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>existingPath</code> and <code>newPath</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>existingPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
</ul>
<p>Creates a new link from the <code>existingPath</code> to the <code>newPath</code>. See the POSIX
<a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a> documentation for more detail. Returns <code>undefined</code>.</p>
<h4><code>fs.lstatSync(path[, options])</code><span><a class="mark" href="#all_fs_fslstatsyncpath-options" id="all_fs_fslstatsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lstatsync_path_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>v15.3.0, v14.17.0</td>
<td><p>Accepts a <code>throwIfNoEntry</code> option to specify whether an exception should be thrown if the entry does not exist.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.1.30</td>
<td><p><span>Added in: v0.1.30</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned
<a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>throwIfNoEntry</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether an exception will be thrown
if no file system entry exists, rather than returning <code>undefined</code>.
<strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a></li>
</ul>
<p>Retrieves the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> for the symbolic link referred to by <code>path</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/lstat.2.html"><code>lstat(2)</code></a> documentation for more details.</p>
<h4><code>fs.mkdirSync(path[, options])</code><span><a class="mark" href="#all_fs_fsmkdirsyncpath-options" id="all_fs_fsmkdirsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_mkdirsync_path_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>v13.11.0, v12.17.0</td>
<td><p>In <code>recursive</code> mode, the first created path is returned now.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p>The second argument can now be an <code>options</code> object with <code>recursive</code> and <code>mode</code> properties.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a>
<ul>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>mode</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#Number_type" class="type"><integer></a> Not supported on Windows. <strong>Default:</strong> <code>0o777</code>.</li>
</ul>
</li>
<li>Returns: <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#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>Synchronously creates a directory. Returns <code>undefined</code>, or if <code>recursive</code> is
<code>true</code>, the first directory path created.
This is the synchronous version of <a href="#all_fs_fsmkdirpath-options-callback"><code>fs.mkdir()</code></a>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html"><code>mkdir(2)</code></a> documentation for more details.</p>
<h4><code>fs.mkdtempSync(prefix[, options])</code><span><a class="mark" href="#all_fs_fsmkdtempsyncprefix-options" id="all_fs_fsmkdtempsyncprefix-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_mkdtempsync_prefix_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>v20.6.0</td>
<td><p>The <code>prefix</code> parameter now accepts buffers and URL.</p></td></tr>
<tr><td>v16.5.0, v14.18.0</td>
<td><p>The <code>prefix</code> parameter now accepts an empty string.</p></td></tr>
<tr><td>v5.10.0</td>
<td><p><span>Added in: v5.10.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>prefix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the created directory path.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fsmkdtempprefix-options-callback"><code>fs.mkdtemp()</code></a>.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use.</p>
<h4><code>fs.opendirSync(path[, options])</code><span><a class="mark" href="#all_fs_fsopendirsyncpath-options" id="all_fs_fsopendirsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_opendirsync_path_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>v20.1.0</td>
<td><p>Added <code>recursive</code> option.</p></td></tr>
<tr><td>v13.1.0, v12.16.0</td>
<td><p>The <code>bufferSize</code> option was introduced.</p></td></tr>
<tr><td>v12.12.0</td>
<td><p><span>Added in: v12.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>bufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of directory entries that are buffered
internally when reading from the directory. Higher values lead to better
performance but higher memory usage. <strong>Default:</strong> <code>32</code></li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsdir" class="type"><fs.Dir></a></li>
</ul>
<p>Synchronously open a directory. See <a href="http://man7.org/linux/man-pages/man3/opendir.3.html"><code>opendir(3)</code></a>.</p>
<p>Creates an <a href="#all_fs_class-fsdir" class="type"><fs.Dir></a>, which contains all further functions for reading from
and cleaning up the directory.</p>
<p>The <code>encoding</code> option sets the encoding for the <code>path</code> while opening the
directory and subsequent read operations.</p>
<h4><code>fs.openSync(path[, flags[, mode]])</code><span><a class="mark" href="#all_fs_fsopensyncpath-flags-mode" id="all_fs_fsopensyncpath-flags-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_opensync_path_flags_mode"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.1.0</td>
<td><p>The <code>flags</code> argument is now optional and defaults to <code>'r'</code>.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>The <code>as</code> and <code>as+</code> flags are supported now.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>flags</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#Number_type" class="type"><number></a> <strong>Default:</strong> <code>'r'</code>.
See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>.</li>
<li><code>mode</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#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Returns an integer representing the file descriptor.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>.</p>
<h4><code>fs.readdirSync(path[, options])</code><span><a class="mark" href="#all_fs_fsreaddirsyncpath-options" id="all_fs_fsreaddirsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readdirsync_path_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>v20.1.0</td>
<td><p>Added <code>recursive</code> option.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>New option <code>withFileTypes</code> was added.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>withFileTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, reads the contents of a directory
recursively. In recursive mode, it will list all files, sub files, and
directories. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer[]></a> | <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent[]></a></li>
</ul>
<p>Reads the contents of the directory.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> documentation for more details.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the filenames returned. If the <code>encoding</code> is set to <code>'buffer'</code>,
the filenames returned will be passed as <a href="#all_buffer_class-buffer" class="type"><Buffer></a> objects.</p>
<p>If <code>options.withFileTypes</code> is set to <code>true</code>, the result will contain
<a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> objects.</p>
<h4><code>fs.readFileSync(path[, options])</code><span><a class="mark" href="#all_fs_fsreadfilesyncpath-options" id="all_fs_fsreadfilesyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readfilesync_path_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>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>path</code> parameter can be a file descriptor now.</p></td></tr>
<tr><td>v0.1.8</td>
<td><p><span>Added in: v0.1.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> filename or file descriptor</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Returns the contents of the <code>path</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fsreadfilepath-options-callback"><code>fs.readFile()</code></a>.</p>
<p>If the <code>encoding</code> option is specified then this function returns a
string. Otherwise it returns a buffer.</p>
<p>Similar to <a href="#all_fs_fsreadfilepath-options-callback"><code>fs.readFile()</code></a>, when the path is a directory, the behavior of
<code>fs.readFileSync()</code> is platform-specific.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// macOS, Linux, and Windows</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'<directory>'</span>);
<span class="hljs-comment">// => [Error: EISDIR: illegal operation on a directory, read <directory>]</span>
<span class="hljs-comment">// FreeBSD</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'<directory>'</span>); <span class="hljs-comment">// => <data></span></code> <button class="copy-button">copy</button></pre>
<h4><code>fs.readlinkSync(path[, options])</code><span><a class="mark" href="#all_fs_fsreadlinksyncpath-options" id="all_fs_fsreadlinksyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readlinksync_path_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>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Returns the symbolic link's string value.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/readlink.2.html"><code>readlink(2)</code></a> documentation for more details.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the link path returned. If the <code>encoding</code> is set to <code>'buffer'</code>,
the link path returned will be passed as a <a href="#all_buffer_class-buffer" class="type"><Buffer></a> object.</p>
<h4><code>fs.readSync(fd, buffer, offset, length[, position])</code><span><a class="mark" href="#all_fs_fsreadsyncfd-buffer-offset-length-position" id="all_fs_fsreadsyncfd-buffer-offset-length-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readsync_fd_buffer_offset_length_position"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>buffer</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>length</code> parameter can now be <code>0</code>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_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></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Returns the number of <code>bytesRead</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fsreadfd-buffer-offset-length-position-callback"><code>fs.read()</code></a>.</p>
<h4><code>fs.readSync(fd, buffer[, options])</code><span><a class="mark" href="#all_fs_fsreadsyncfd-buffer-options" id="all_fs_fsreadsyncfd-buffer-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readsync_fd_buffer_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>v13.13.0, v12.17.0</td>
<td><p>Options object can be passed in to make offset, length, and position optional.</p></td></tr>
<tr><td>v13.13.0, v12.17.0</td>
<td><p><span>Added in: v13.13.0, v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_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></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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>buffer.byteLength - offset</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Returns the number of <code>bytesRead</code>.</p>
<p>Similar to the above <code>fs.readSync</code> function, this version takes an optional <code>options</code> object.
If no <code>options</code> object is specified, it will default with the above values.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fsreadfd-buffer-offset-length-position-callback"><code>fs.read()</code></a>.</p>
<h4><code>fs.readvSync(fd, buffers[, position])</code><span><a class="mark" href="#all_fs_fsreadvsyncfd-buffers-position" id="all_fs_fsreadvsyncfd-buffers-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readvsync_fd_buffers_position"></a></h4>
<div class="api_metadata">
<span>Added in: v13.13.0, v12.17.0</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type"><ArrayBufferView[]></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes read.</li>
</ul>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fsreadvfd-buffers-position-callback"><code>fs.readv()</code></a>.</p>
<h4><code>fs.realpathSync(path[, options])</code><span><a class="mark" href="#all_fs_fsrealpathsyncpath-options" id="all_fs_fsrealpathsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_realpathsync_path_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>v8.0.0</td>
<td><p>Pipe/Socket resolve support was added.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v6.4.0</td>
<td><p>Calling <code>realpathSync</code> now works again for various edge cases on Windows.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>cache</code> parameter was removed.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Returns the resolved pathname.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fsrealpathpath-options-callback"><code>fs.realpath()</code></a>.</p>
<h4><code>fs.realpathSync.native(path[, options])</code><span><a class="mark" href="#all_fs_fsrealpathsyncnativepath-options" id="all_fs_fsrealpathsyncnativepath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_realpathsync_native_path_options"></a></h4>
<div class="api_metadata">
<span>Added in: v9.2.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>options</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/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> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man3/realpath.3.html"><code>realpath(3)</code></a>.</p>
<p>Only paths that can be converted to UTF8 strings are supported.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the path returned. If the <code>encoding</code> is set to <code>'buffer'</code>,
the path returned will be passed as a <a href="#all_buffer_class-buffer" class="type"><Buffer></a> object.</p>
<p>On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on <code>/proc</code> in order for this function to work. Glibc does not have
this restriction.</p>
<h4><code>fs.renameSync(oldPath, newPath)</code><span><a class="mark" href="#all_fs_fsrenamesyncoldpath-newpath" id="all_fs_fsrenamesyncoldpath-newpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_renamesync_oldpath_newpath"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>oldPath</code> and <code>newPath</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>oldPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
</ul>
<p>Renames the file from <code>oldPath</code> to <code>newPath</code>. Returns <code>undefined</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/rename.2.html"><code>rename(2)</code></a> documentation for more details.</p>
<h4><code>fs.rmdirSync(path[, options])</code><span><a class="mark" href="#all_fs_fsrmdirsyncpath-options" id="all_fs_fsrmdirsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_rmdirsync_path_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>v16.0.0</td>
<td><p>Using <code>fs.rmdirSync(path, { recursive: true })</code> on a <code>path</code> that is a file is no longer permitted and results in an <code>ENOENT</code> error on Windows and an <code>ENOTDIR</code> error on POSIX.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Using <code>fs.rmdirSync(path, { recursive: true })</code> on a <code>path</code> that does not exist is no longer permitted and results in a <code>ENOENT</code> error.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>The <code>recursive</code> option is deprecated, using it triggers a deprecation warning.</p></td></tr>
<tr><td>v14.14.0</td>
<td><p>The <code>recursive</code> option is deprecated, use <code>fs.rmSync</code> instead.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p>The <code>maxBusyTries</code> option is renamed to <code>maxRetries</code>, and its default is 0. The <code>emfileWait</code> option has been removed, and <code>EMFILE</code> errors use the same retry logic as other errors. The <code>retryDelay</code> option is now supported. <code>ENFILE</code> errors are now retried.</p></td></tr>
<tr><td>v12.10.0</td>
<td><p>The <code>recursive</code>, <code>maxBusyTries</code>, and <code>emfileWait</code> options are now supported.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameters can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>maxRetries</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> If an <code>EBUSY</code>, <code>EMFILE</code>, <code>ENFILE</code>, <code>ENOTEMPTY</code>, or
<code>EPERM</code> error is encountered, Node.js retries the operation with a linear
backoff wait of <code>retryDelay</code> milliseconds longer on each try. This option
represents the number of retries. This option is ignored if the <code>recursive</code>
option is not <code>true</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, perform a recursive directory removal. In
recursive mode, operations are retried on failure. <strong>Default:</strong> <code>false</code>.
<strong>Deprecated.</strong></li>
<li><code>retryDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The amount of time in milliseconds to wait between
retries. This option is ignored if the <code>recursive</code> option is not <code>true</code>.
<strong>Default:</strong> <code>100</code>.</li>
</ul>
</li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/rmdir.2.html"><code>rmdir(2)</code></a>. Returns <code>undefined</code>.</p>
<p>Using <code>fs.rmdirSync()</code> on a file (not a directory) results in an <code>ENOENT</code> error
on Windows and an <code>ENOTDIR</code> error on POSIX.</p>
<p>To get a behavior similar to the <code>rm -rf</code> Unix command, use <a href="#all_fs_fsrmsyncpath-options"><code>fs.rmSync()</code></a>
with options <code>{ recursive: true, force: true }</code>.</p>
<h4><code>fs.rmSync(path[, options])</code><span><a class="mark" href="#all_fs_fsrmsyncpath-options" id="all_fs_fsrmsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_rmsync_path_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>v17.3.0, v16.14.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v14.14.0</td>
<td><p><span>Added in: v14.14.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>force</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, exceptions will be ignored if <code>path</code> does
not exist. <strong>Default:</strong> <code>false</code>.</li>
<li><code>maxRetries</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> If an <code>EBUSY</code>, <code>EMFILE</code>, <code>ENFILE</code>, <code>ENOTEMPTY</code>, or
<code>EPERM</code> error is encountered, Node.js will retry the operation with a linear
backoff wait of <code>retryDelay</code> milliseconds longer on each try. This option
represents the number of retries. This option is ignored if the <code>recursive</code>
option is not <code>true</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, perform a recursive directory removal. In
recursive mode operations are retried on failure. <strong>Default:</strong> <code>false</code>.</li>
<li><code>retryDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The amount of time in milliseconds to wait between
retries. This option is ignored if the <code>recursive</code> option is not <code>true</code>.
<strong>Default:</strong> <code>100</code>.</li>
</ul>
</li>
</ul>
<p>Synchronously removes files and directories (modeled on the standard POSIX <code>rm</code>
utility). Returns <code>undefined</code>.</p>
<h4><code>fs.statSync(path[, options])</code><span><a class="mark" href="#all_fs_fsstatsyncpath-options" id="all_fs_fsstatsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_statsync_path_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>v15.3.0, v14.17.0</td>
<td><p>Accepts a <code>throwIfNoEntry</code> option to specify whether an exception should be thrown if the entry does not exist.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned
<a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>throwIfNoEntry</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether an exception will be thrown
if no file system entry exists, rather than returning <code>undefined</code>.
<strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a></li>
</ul>
<p>Retrieves the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> for the path.</p>
<h4><code>fs.statfsSync(path[, options])</code><span><a class="mark" href="#all_fs_fsstatfssyncpath-options" id="all_fs_fsstatfssyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_statfssync_path_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned
<a href="#all_fs_class-fsstatfs" class="type"><fs.StatFs></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsstatfs" class="type"><fs.StatFs></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/statfs.2.html"><code>statfs(2)</code></a>. Returns information about the mounted file system which
contains <code>path</code>.</p>
<p>In case of an error, the <code>err.code</code> will be one of <a href="#all_errors_common-system-errors">Common System Errors</a>.</p>
<h4><code>fs.symlinkSync(target, path[, type])</code><span><a class="mark" href="#all_fs_fssymlinksynctarget-path-type" id="all_fs_fssymlinksynctarget-path-type">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_symlinksync_target_path_type"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>If the <code>type</code> argument is left undefined, Node will autodetect <code>target</code> type and automatically select <code>dir</code> or <code>file</code>.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>target</code> and <code>path</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>type</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> <strong>Default:</strong> <code>null</code></li>
</ul>
<p>Returns <code>undefined</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fssymlinktarget-path-type-callback"><code>fs.symlink()</code></a>.</p>
<h4><code>fs.truncateSync(path[, len])</code><span><a class="mark" href="#all_fs_fstruncatesyncpath-len" id="all_fs_fstruncatesyncpath-len">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_truncatesync_path_len"></a></h4>
<div class="api_metadata">
<span>Added in: v0.8.6</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li>
</ul>
<p>Truncates the file. Returns <code>undefined</code>. A file descriptor can also be
passed as the first argument. In this case, <code>fs.ftruncateSync()</code> is called.</p>
<p>Passing a file descriptor is deprecated and may result in an error being thrown
in the future.</p>
<h4><code>fs.unlinkSync(path)</code><span><a class="mark" href="#all_fs_fsunlinksyncpath" id="all_fs_fsunlinksyncpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_unlinksync_path"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a>. Returns <code>undefined</code>.</p>
<h4><code>fs.utimesSync(path, atime, mtime)</code><span><a class="mark" href="#all_fs_fsutimessyncpath-atime-mtime" id="all_fs_fsutimessyncpath-atime-mtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_utimessync_path_atime_mtime"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p><code>NaN</code>, <code>Infinity</code>, and <code>-Infinity</code> are no longer valid time specifiers.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v4.1.0</td>
<td><p>Numeric strings, <code>NaN</code>, and <code>Infinity</code> are now allowed time specifiers.</p></td></tr>
<tr><td>v0.4.2</td>
<td><p><span>Added in: v0.4.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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/Global_Objects/Date" class="type"><Date></a></li>
</ul>
<p>Returns <code>undefined</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fsutimespath-atime-mtime-callback"><code>fs.utimes()</code></a>.</p>
<h4><code>fs.writeFileSync(file, data[, options])</code><span><a class="mark" href="#all_fs_fswritefilesyncfile-data-options" id="all_fs_fswritefilesyncfile-data-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writefilesync_file_data_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>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v19.0.0</td>
<td><p>Passing to the <code>data</code> parameter an object with an own <code>toString</code> function is no longer supported.</p></td></tr>
<tr><td>v17.8.0</td>
<td><p>Passing to the <code>data</code> parameter an object with an own <code>toString</code> function is deprecated.</p></td></tr>
<tr><td>v14.12.0</td>
<td><p>The <code>data</code> parameter will stringify an object with an explicit <code>toString</code> function.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>data</code> parameter won't coerce unsupported input to strings anymore.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>data</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v7.4.0</td>
<td><p>The <code>data</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>file</code> parameter can be a file descriptor now.</p></td></tr>
<tr><td>v0.1.29</td>
<td><p><span>Added in: v0.1.29</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> filename or file descriptor</li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If all data is successfully written to the file, and
<code>flush</code> is <code>true</code>, <code>fs.fsyncSync()</code> is used to flush the data.</li>
</ul>
</li>
</ul>
<p>Returns <code>undefined</code>.</p>
<p>The <code>mode</code> option only affects the newly created file. See <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>
for more details.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fswritefilefile-data-options-callback"><code>fs.writeFile()</code></a>.</p>
<h4><code>fs.writeSync(fd, buffer, offset[, length[, position]])</code><span><a class="mark" href="#all_fs_fswritesyncfd-buffer-offset-length-position" id="all_fs_fswritesyncfd-buffer-offset-length-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writesync_fd_buffer_offset_length_position"></a></h4>
<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>The <code>buffer</code> parameter won't coerce unsupported input to strings anymore.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>buffer</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v7.4.0</td>
<td><p>The <code>buffer</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>The <code>offset</code> and <code>length</code> parameters are optional now.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_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></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>buffer.byteLength - offset</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes written.</li>
</ul>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fswritefd-buffer-offset-length-position-callback"><code>fs.write(fd, buffer...)</code></a>.</p>
<h4><code>fs.writeSync(fd, buffer[, options])</code><span><a class="mark" href="#all_fs_fswritesyncfd-buffer-options" id="all_fs_fswritesyncfd-buffer-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writesync_fd_buffer_options"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffer</code> <a href="#all_buffer_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></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>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>buffer.byteLength - offset</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>null</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes written.</li>
</ul>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fswritefd-buffer-offset-length-position-callback"><code>fs.write(fd, buffer...)</code></a>.</p>
<h4><code>fs.writeSync(fd, string[, position[, encoding]])</code><span><a class="mark" href="#all_fs_fswritesyncfd-string-position-encoding" id="all_fs_fswritesyncfd-string-position-encoding">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writesync_fd_string_position_encoding"></a></h4>
<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>The <code>string</code> parameter won't coerce unsupported input to strings anymore.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>The <code>position</code> parameter is optional now.</p></td></tr>
<tr><td>v0.11.5</td>
<td><p><span>Added in: v0.11.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <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> <strong>Default:</strong> <code>'utf8'</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes written.</li>
</ul>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fswritefd-string-position-encoding-callback"><code>fs.write(fd, string...)</code></a>.</p>
<h4><code>fs.writevSync(fd, buffers[, position])</code><span><a class="mark" href="#all_fs_fswritevsyncfd-buffers-position" id="all_fs_fswritevsyncfd-buffers-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writevsync_fd_buffers_position"></a></h4>
<div class="api_metadata">
<span>Added in: v12.9.0</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type"><ArrayBufferView[]></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes written.</li>
</ul>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fswritevfd-buffers-position-callback"><code>fs.writev()</code></a>.</p>
</section><section><h3>Common Objects<span><a class="mark" href="#all_fs_common-objects" id="all_fs_common-objects">#</a></span><a aria-hidden="true" class="legacy" id="fs_common_objects"></a></h3>
<p>The common objects are shared by all of the file system API variants
(promise, callback, and synchronous).</p>
<h4>Class: <code>fs.Dir</code><span><a class="mark" href="#all_fs_class-fsdir" id="all_fs_class-fsdir">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_dir"></a></h4>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<p>A class representing a directory stream.</p>
<p>Created by <a href="#all_fs_fsopendirpath-options-callback"><code>fs.opendir()</code></a>, <a href="#all_fs_fsopendirsyncpath-options"><code>fs.opendirSync()</code></a>, or
<a href="#all_fs_fspromisesopendirpath-options"><code>fsPromises.opendir()</code></a>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { opendir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> dir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">opendir</span>(<span class="hljs-string">'./'</span>);
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> dirent <span class="hljs-keyword">of</span> dir)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(dirent.<span class="hljs-property">name</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}</code> <button class="copy-button">copy</button></pre>
<p>When using the async iterator, the <a href="#all_fs_class-fsdir" class="type"><fs.Dir></a> object will be automatically
closed after the iterator exits.</p>
<h5><code>dir.close()</code><span><a class="mark" href="#all_fs_dirclose" id="all_fs_dirclose">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_close"></a></h5>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Asynchronously close the directory's underlying resource handle.
Subsequent reads will result in errors.</p>
<p>A promise is returned that will be fulfilled after the resource has been
closed.</p>
<h5><code>dir.close(callback)</code><span><a class="mark" href="#all_fs_dirclosecallback" id="all_fs_dirclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_close_callback"></a></h5>
<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</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>v12.12.0</td>
<td><p><span>Added in: v12.12.0</span></p></td></tr>
</tbody></table>
</details>
</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>
<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>
</ul>
</li>
</ul>
<p>Asynchronously close the directory's underlying resource handle.
Subsequent reads will result in errors.</p>
<p>The <code>callback</code> will be called after the resource handle has been closed.</p>
<h5><code>dir.closeSync()</code><span><a class="mark" href="#all_fs_dirclosesync" id="all_fs_dirclosesync">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_closesync"></a></h5>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<p>Synchronously close the directory's underlying resource handle.
Subsequent reads will result in errors.</p>
<h5><code>dir.path</code><span><a class="mark" href="#all_fs_dirpath" id="all_fs_dirpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_path"></a></h5>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The read-only path of this directory as was provided to <a href="#all_fs_fsopendirpath-options-callback"><code>fs.opendir()</code></a>,
<a href="#all_fs_fsopendirsyncpath-options"><code>fs.opendirSync()</code></a>, or <a href="#all_fs_fspromisesopendirpath-options"><code>fsPromises.opendir()</code></a>.</p>
<h5><code>dir.read()</code><span><a class="mark" href="#all_fs_dirread" id="all_fs_dirread">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_read"></a></h5>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with a <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a></li>
</ul>
<p>Asynchronously read the next directory entry via <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> as an
<a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a>.</p>
<p>A promise is returned that will be fulfilled with an <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a>, or <code>null</code>
if there are no more directory entries to read.</p>
<p>Directory entries returned by this function are in no particular order as
provided by the operating system's underlying directory mechanisms.
Entries added or removed while iterating over the directory might not be
included in the iteration results.</p>
<h5><code>dir.read(callback)</code><span><a class="mark" href="#all_fs_dirreadcallback" id="all_fs_dirreadcallback">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_read_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v12.12.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>
<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>dirent</code> <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a></li>
</ul>
</li>
</ul>
<p>Asynchronously read the next directory entry via <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> as an
<a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a>.</p>
<p>After the read is completed, the <code>callback</code> will be called with an
<a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a>, or <code>null</code> if there are no more directory entries to read.</p>
<p>Directory entries returned by this function are in no particular order as
provided by the operating system's underlying directory mechanisms.
Entries added or removed while iterating over the directory might not be
included in the iteration results.</p>
<h5><code>dir.readSync()</code><span><a class="mark" href="#all_fs_dirreadsync" id="all_fs_dirreadsync">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_readsync"></a></h5>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li>Returns: <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a></li>
</ul>
<p>Synchronously read the next directory entry as an <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a>. See the
POSIX <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> documentation for more detail.</p>
<p>If there are no more directory entries to read, <code>null</code> will be returned.</p>
<p>Directory entries returned by this function are in no particular order as
provided by the operating system's underlying directory mechanisms.
Entries added or removed while iterating over the directory might not be
included in the iteration results.</p>
<h5><code>dir[Symbol.asyncIterator]()</code><span><a class="mark" href="#all_fs_dirsymbolasynciterator" id="all_fs_dirsymbolasynciterator">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_symbol_asynciterator"></a></h5>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a> An AsyncIterator of <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a></li>
</ul>
<p>Asynchronously iterates over the directory until all entries have
been read. Refer to the POSIX <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> documentation for more detail.</p>
<p>Entries returned by the async iterator are always an <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a>.
The <code>null</code> case from <code>dir.read()</code> is handled internally.</p>
<p>See <a href="#all_fs_class-fsdir" class="type"><fs.Dir></a> for an example.</p>
<p>Directory entries returned by this iterator are in no particular order as
provided by the operating system's underlying directory mechanisms.
Entries added or removed while iterating over the directory might not be
included in the iteration results.</p>
<h4>Class: <code>fs.Dirent</code><span><a class="mark" href="#all_fs_class-fsdirent" id="all_fs_class-fsdirent">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_dirent"></a></h4>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<p>A representation of a directory entry, which can be a file or a subdirectory
within the directory, as returned by reading from an <a href="#all_fs_class-fsdir" class="type"><fs.Dir></a>. The
directory entry is a combination of the file name and file type pairs.</p>
<p>Additionally, when <a href="#all_fs_fsreaddirpath-options-callback"><code>fs.readdir()</code></a> or <a href="#all_fs_fsreaddirsyncpath-options"><code>fs.readdirSync()</code></a> is called with
the <code>withFileTypes</code> option set to <code>true</code>, the resulting array is filled with
<a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> objects, rather than strings or <a href="#all_buffer_class-buffer" class="type"><Buffer></a>s.</p>
<h5><code>dirent.isBlockDevice()</code><span><a class="mark" href="#all_fs_direntisblockdevice" id="all_fs_direntisblockdevice">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_isblockdevice"></a></h5>
<div class="api_metadata">
<span>Added in: v10.10.0</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>Returns <code>true</code> if the <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> object describes a block device.</p>
<h5><code>dirent.isCharacterDevice()</code><span><a class="mark" href="#all_fs_direntischaracterdevice" id="all_fs_direntischaracterdevice">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_ischaracterdevice"></a></h5>
<div class="api_metadata">
<span>Added in: v10.10.0</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>Returns <code>true</code> if the <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> object describes a character device.</p>
<h5><code>dirent.isDirectory()</code><span><a class="mark" href="#all_fs_direntisdirectory" id="all_fs_direntisdirectory">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_isdirectory"></a></h5>
<div class="api_metadata">
<span>Added in: v10.10.0</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>Returns <code>true</code> if the <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> object describes a file system
directory.</p>
<h5><code>dirent.isFIFO()</code><span><a class="mark" href="#all_fs_direntisfifo" id="all_fs_direntisfifo">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_isfifo"></a></h5>
<div class="api_metadata">
<span>Added in: v10.10.0</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>Returns <code>true</code> if the <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> object describes a first-in-first-out
(FIFO) pipe.</p>
<h5><code>dirent.isFile()</code><span><a class="mark" href="#all_fs_direntisfile" id="all_fs_direntisfile">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_isfile"></a></h5>
<div class="api_metadata">
<span>Added in: v10.10.0</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>Returns <code>true</code> if the <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> object describes a regular file.</p>
<h5><code>dirent.isSocket()</code><span><a class="mark" href="#all_fs_direntissocket" id="all_fs_direntissocket">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_issocket"></a></h5>
<div class="api_metadata">
<span>Added in: v10.10.0</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>Returns <code>true</code> if the <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> object describes a socket.</p>
<h5><code>dirent.isSymbolicLink()</code><span><a class="mark" href="#all_fs_direntissymboliclink" id="all_fs_direntissymboliclink">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_issymboliclink"></a></h5>
<div class="api_metadata">
<span>Added in: v10.10.0</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>Returns <code>true</code> if the <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> object describes a symbolic link.</p>
<h5><code>dirent.name</code><span><a class="mark" href="#all_fs_direntname" id="all_fs_direntname">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_name"></a></h5>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>The file name that this <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> object refers to. The type of this
value is determined by the <code>options.encoding</code> passed to <a href="#all_fs_fsreaddirpath-options-callback"><code>fs.readdir()</code></a> or
<a href="#all_fs_fsreaddirsyncpath-options"><code>fs.readdirSync()</code></a>.</p>
<h5><code>dirent.parentPath</code><span><a class="mark" href="#all_fs_direntparentpath" id="all_fs_direntparentpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_parentpath"></a></h5>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The path to the parent directory of the file this <a href="#all_fs_class-fsdirent" class="type"><fs.Dirent></a> object refers to.</p>
<h5><code>dirent.path</code><span><a class="mark" href="#all_fs_direntpath" id="all_fs_direntpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_path"></a></h5>
<div class="api_metadata">
<span>Added in: v20.1.0, v18.17.0</span><span>Deprecated since: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_fs_direntparentpath"><code>dirent.parentPath</code></a> instead.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Alias for <code>dirent.parentPath</code>.</p>
<h4>Class: <code>fs.FSWatcher</code><span><a class="mark" href="#all_fs_class-fsfswatcher" id="all_fs_class-fsfswatcher">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_fswatcher"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li>Extends <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>A successful call to <a href="#all_fs_fswatchfilename-options-listener"><code>fs.watch()</code></a> method will return a new <a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a>
object.</p>
<p>All <a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a> objects emit a <code>'change'</code> event whenever a specific watched
file is modified.</p>
<h5>Event: <code>'change'</code><span><a class="mark" href="#all_fs_event-change" id="all_fs_event-change">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_change"></a></h5>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>eventType</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The type of change event that has occurred</li>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The filename that changed (if relevant/available)</li>
</ul>
<p>Emitted when something changes in a watched directory or file.
See more details in <a href="#all_fs_fswatchfilename-options-listener"><code>fs.watch()</code></a>.</p>
<p>The <code>filename</code> argument may not be provided depending on operating system
support. If <code>filename</code> is provided, it will be provided as a <a href="#all_buffer_class-buffer" class="type"><Buffer></a> if
<code>fs.watch()</code> is called with its <code>encoding</code> option set to <code>'buffer'</code>, otherwise
<code>filename</code> will be a UTF-8 string.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { watch } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// Example when handled through fs.watch() listener</span>
<span class="hljs-title function_">watch</span>(<span class="hljs-string">'./tmp'</span>, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'buffer'</span> }, <span class="hljs-function">(<span class="hljs-params">eventType, filename</span>) =></span> {
<span class="hljs-keyword">if</span> (filename) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(filename);
<span class="hljs-comment">// Prints: <Buffer ...></span>
}
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_fs_event-close_1" id="all_fs_event-close_1">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_close_1"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>Emitted when the watcher stops watching for changes. The closed
<a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a> object is no longer usable in the event handler.</p>
<h5>Event: <code>'error'</code><span><a class="mark" href="#all_fs_event-error" id="all_fs_event-error">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_error"></a></h5>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</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>
</ul>
<p>Emitted when an error occurs while watching the file. The errored
<a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a> object is no longer usable in the event handler.</p>
<h5><code>watcher.close()</code><span><a class="mark" href="#all_fs_watcherclose" id="all_fs_watcherclose">#</a></span><a aria-hidden="true" class="legacy" id="fs_watcher_close"></a></h5>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<p>Stop watching for changes on the given <a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a>. Once stopped, the
<a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a> object is no longer usable.</p>
<h5><code>watcher.ref()</code><span><a class="mark" href="#all_fs_watcherref" id="all_fs_watcherref">#</a></span><a aria-hidden="true" class="legacy" id="fs_watcher_ref"></a></h5>
<div class="api_metadata">
<span>Added in: v14.3.0, v12.20.0</span>
</div>
<ul>
<li>Returns: <a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a></li>
</ul>
<p>When called, requests that the Node.js event loop <em>not</em> exit so long as the
<a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a> is active. Calling <code>watcher.ref()</code> multiple times will have
no effect.</p>
<p>By default, all <a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a> objects are "ref'ed", making it normally
unnecessary to call <code>watcher.ref()</code> unless <code>watcher.unref()</code> had been
called previously.</p>
<h5><code>watcher.unref()</code><span><a class="mark" href="#all_fs_watcherunref" id="all_fs_watcherunref">#</a></span><a aria-hidden="true" class="legacy" id="fs_watcher_unref"></a></h5>
<div class="api_metadata">
<span>Added in: v14.3.0, v12.20.0</span>
</div>
<ul>
<li>Returns: <a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a></li>
</ul>
<p>When called, the active <a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a> object will not require the Node.js
event loop to remain active. If there is no other activity keeping the
event loop running, the process may exit before the <a href="#all_fs_class-fsfswatcher" class="type"><fs.FSWatcher></a> object's
callback is invoked. Calling <code>watcher.unref()</code> multiple times will have
no effect.</p>
<h4>Class: <code>fs.StatWatcher</code><span><a class="mark" href="#all_fs_class-fsstatwatcher" id="all_fs_class-fsstatwatcher">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_statwatcher"></a></h4>
<div class="api_metadata">
<span>Added in: v14.3.0, v12.20.0</span>
</div>
<ul>
<li>Extends <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>A successful call to <code>fs.watchFile()</code> method will return a new <a href="#all_fs_class-fsstatwatcher" class="type"><fs.StatWatcher></a>
object.</p>
<h5><code>watcher.ref()</code><span><a class="mark" href="#all_fs_watcherref_1" id="all_fs_watcherref_1">#</a></span><a aria-hidden="true" class="legacy" id="fs_watcher_ref_1"></a></h5>
<div class="api_metadata">
<span>Added in: v14.3.0, v12.20.0</span>
</div>
<ul>
<li>Returns: <a href="#all_fs_class-fsstatwatcher" class="type"><fs.StatWatcher></a></li>
</ul>
<p>When called, requests that the Node.js event loop <em>not</em> exit so long as the
<a href="#all_fs_class-fsstatwatcher" class="type"><fs.StatWatcher></a> is active. Calling <code>watcher.ref()</code> multiple times will have
no effect.</p>
<p>By default, all <a href="#all_fs_class-fsstatwatcher" class="type"><fs.StatWatcher></a> objects are "ref'ed", making it normally
unnecessary to call <code>watcher.ref()</code> unless <code>watcher.unref()</code> had been
called previously.</p>
<h5><code>watcher.unref()</code><span><a class="mark" href="#all_fs_watcherunref_1" id="all_fs_watcherunref_1">#</a></span><a aria-hidden="true" class="legacy" id="fs_watcher_unref_1"></a></h5>
<div class="api_metadata">
<span>Added in: v14.3.0, v12.20.0</span>
</div>
<ul>
<li>Returns: <a href="#all_fs_class-fsstatwatcher" class="type"><fs.StatWatcher></a></li>
</ul>
<p>When called, the active <a href="#all_fs_class-fsstatwatcher" class="type"><fs.StatWatcher></a> object will not require the Node.js
event loop to remain active. If there is no other activity keeping the
event loop running, the process may exit before the <a href="#all_fs_class-fsstatwatcher" class="type"><fs.StatWatcher></a> object's
callback is invoked. Calling <code>watcher.unref()</code> multiple times will have
no effect.</p>
<h4>Class: <code>fs.ReadStream</code><span><a class="mark" href="#all_fs_class-fsreadstream" id="all_fs_class-fsreadstream">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_readstream"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a></li>
</ul>
<p>Instances of <a href="#all_fs_class-fsreadstream" class="type"><fs.ReadStream></a> are created and returned using the
<a href="#all_fs_fscreatereadstreampath-options"><code>fs.createReadStream()</code></a> function.</p>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_fs_event-close_2" id="all_fs_event-close_2">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_close_2"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<p>Emitted when the <a href="#all_fs_class-fsreadstream" class="type"><fs.ReadStream></a>'s underlying file descriptor has been closed.</p>
<h5>Event: <code>'open'</code><span><a class="mark" href="#all_fs_event-open" id="all_fs_event-open">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_open"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Integer file descriptor used by the <a href="#all_fs_class-fsreadstream" class="type"><fs.ReadStream></a>.</li>
</ul>
<p>Emitted when the <a href="#all_fs_class-fsreadstream" class="type"><fs.ReadStream></a>'s file descriptor has been opened.</p>
<h5>Event: <code>'ready'</code><span><a class="mark" href="#all_fs_event-ready" id="all_fs_event-ready">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_ready"></a></h5>
<div class="api_metadata">
<span>Added in: v9.11.0</span>
</div>
<p>Emitted when the <a href="#all_fs_class-fsreadstream" class="type"><fs.ReadStream></a> is ready to be used.</p>
<p>Fires immediately after <code>'open'</code>.</p>
<h5><code>readStream.bytesRead</code><span><a class="mark" href="#all_fs_readstreambytesread" id="all_fs_readstreambytesread">#</a></span><a aria-hidden="true" class="legacy" id="fs_readstream_bytesread"></a></h5>
<div class="api_metadata">
<span>Added in: v6.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>The number of bytes that have been read so far.</p>
<h5><code>readStream.path</code><span><a class="mark" href="#all_fs_readstreampath" id="all_fs_readstreampath">#</a></span><a aria-hidden="true" class="legacy" id="fs_readstream_path"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>The path to the file the stream is reading from as specified in the first
argument to <code>fs.createReadStream()</code>. If <code>path</code> is passed as a string, then
<code>readStream.path</code> will be a string. If <code>path</code> is passed as a <a href="#all_buffer_class-buffer" class="type"><Buffer></a>, then
<code>readStream.path</code> will be a <a href="#all_buffer_class-buffer" class="type"><Buffer></a>. If <code>fd</code> is specified, then
<code>readStream.path</code> will be <code>undefined</code>.</p>
<h5><code>readStream.pending</code><span><a class="mark" href="#all_fs_readstreampending" id="all_fs_readstreampending">#</a></span><a aria-hidden="true" class="legacy" id="fs_readstream_pending"></a></h5>
<div class="api_metadata">
<span>Added in: v11.2.0, v10.16.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 is <code>true</code> if the underlying file has not been opened yet,
i.e. before the <code>'ready'</code> event is emitted.</p>
<h4>Class: <code>fs.Stats</code><span><a class="mark" href="#all_fs_class-fsstats" id="all_fs_class-fsstats">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_stats"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Public constructor is deprecated.</p></td></tr>
<tr><td>v8.1.0</td>
<td><p>Added times as numbers.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>A <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object provides information about a file.</p>
<p>Objects returned from <a href="#all_fs_fsstatpath-options-callback"><code>fs.stat()</code></a>, <a href="#all_fs_fslstatpath-options-callback"><code>fs.lstat()</code></a>, <a href="#all_fs_fsfstatfd-options-callback"><code>fs.fstat()</code></a>, and
their synchronous counterparts are of this type.
If <code>bigint</code> in the <code>options</code> passed to those methods is true, the numeric values
will be <code>bigint</code> instead of <code>number</code>, and the object will contain additional
nanosecond-precision properties suffixed with <code>Ns</code>.
<code>Stat</code> objects are not to be created directly using the <code>new</code> keyword.</p>
<pre><code class="language-console">Stats {
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atimeMs: 1318289051000.1,
mtimeMs: 1318289051000.1,
ctimeMs: 1318289051000.1,
birthtimeMs: 1318289051000.1,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }</code> <button class="copy-button">copy</button></pre>
<p><code>bigint</code> version:</p>
<pre><code class="language-console">BigIntStats {
dev: 2114n,
ino: 48064969n,
mode: 33188n,
nlink: 1n,
uid: 85n,
gid: 100n,
rdev: 0n,
size: 527n,
blksize: 4096n,
blocks: 8n,
atimeMs: 1318289051000n,
mtimeMs: 1318289051000n,
ctimeMs: 1318289051000n,
birthtimeMs: 1318289051000n,
atimeNs: 1318289051000000000n,
mtimeNs: 1318289051000000000n,
ctimeNs: 1318289051000000000n,
birthtimeNs: 1318289051000000000n,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }</code> <button class="copy-button">copy</button></pre>
<h5><code>stats.isBlockDevice()</code><span><a class="mark" href="#all_fs_statsisblockdevice" id="all_fs_statsisblockdevice">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_isblockdevice"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.10</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>Returns <code>true</code> if the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object describes a block device.</p>
<h5><code>stats.isCharacterDevice()</code><span><a class="mark" href="#all_fs_statsischaracterdevice" id="all_fs_statsischaracterdevice">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_ischaracterdevice"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.10</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>Returns <code>true</code> if the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object describes a character device.</p>
<h5><code>stats.isDirectory()</code><span><a class="mark" href="#all_fs_statsisdirectory" id="all_fs_statsisdirectory">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_isdirectory"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.10</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>Returns <code>true</code> if the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object describes a file system directory.</p>
<p>If the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object was obtained from calling <a href="#all_fs_fslstatpath-options-callback"><code>fs.lstat()</code></a> on a
symbolic link which resolves to a directory, this method will return <code>false</code>.
This is because <a href="#all_fs_fslstatpath-options-callback"><code>fs.lstat()</code></a> returns information
about a symbolic link itself and not the path it resolves to.</p>
<h5><code>stats.isFIFO()</code><span><a class="mark" href="#all_fs_statsisfifo" id="all_fs_statsisfifo">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_isfifo"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.10</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>Returns <code>true</code> if the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object describes a first-in-first-out (FIFO)
pipe.</p>
<h5><code>stats.isFile()</code><span><a class="mark" href="#all_fs_statsisfile" id="all_fs_statsisfile">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_isfile"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.10</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>Returns <code>true</code> if the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object describes a regular file.</p>
<h5><code>stats.isSocket()</code><span><a class="mark" href="#all_fs_statsissocket" id="all_fs_statsissocket">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_issocket"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.10</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>Returns <code>true</code> if the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object describes a socket.</p>
<h5><code>stats.isSymbolicLink()</code><span><a class="mark" href="#all_fs_statsissymboliclink" id="all_fs_statsissymboliclink">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_issymboliclink"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.10</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>Returns <code>true</code> if the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object describes a symbolic link.</p>
<p>This method is only valid when using <a href="#all_fs_fslstatpath-options-callback"><code>fs.lstat()</code></a>.</p>
<h5><code>stats.dev</code><span><a class="mark" href="#all_fs_statsdev" id="all_fs_statsdev">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_dev"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The numeric identifier of the device containing the file.</p>
<h5><code>stats.ino</code><span><a class="mark" href="#all_fs_statsino" id="all_fs_statsino">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_ino"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The file system specific "Inode" number for the file.</p>
<h5><code>stats.mode</code><span><a class="mark" href="#all_fs_statsmode" id="all_fs_statsmode">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_mode"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>A bit-field describing the file type and mode.</p>
<h5><code>stats.nlink</code><span><a class="mark" href="#all_fs_statsnlink" id="all_fs_statsnlink">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_nlink"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The number of hard-links that exist for the file.</p>
<h5><code>stats.uid</code><span><a class="mark" href="#all_fs_statsuid" id="all_fs_statsuid">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_uid"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The numeric user identifier of the user that owns the file (POSIX).</p>
<h5><code>stats.gid</code><span><a class="mark" href="#all_fs_statsgid" id="all_fs_statsgid">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_gid"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The numeric group identifier of the group that owns the file (POSIX).</p>
<h5><code>stats.rdev</code><span><a class="mark" href="#all_fs_statsrdev" id="all_fs_statsrdev">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_rdev"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>A numeric device identifier if the file represents a device.</p>
<h5><code>stats.size</code><span><a class="mark" href="#all_fs_statssize" id="all_fs_statssize">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_size"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The size of the file in bytes.</p>
<p>If the underlying file system does not support getting the size of the file,
this will be <code>0</code>.</p>
<h5><code>stats.blksize</code><span><a class="mark" href="#all_fs_statsblksize" id="all_fs_statsblksize">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_blksize"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The file system block size for i/o operations.</p>
<h5><code>stats.blocks</code><span><a class="mark" href="#all_fs_statsblocks" id="all_fs_statsblocks">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_blocks"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The number of blocks allocated for this file.</p>
<h5><code>stats.atimeMs</code><span><a class="mark" href="#all_fs_statsatimems" id="all_fs_statsatimems">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_atimems"></a></h5>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The timestamp indicating the last time this file was accessed expressed in
milliseconds since the POSIX Epoch.</p>
<h5><code>stats.mtimeMs</code><span><a class="mark" href="#all_fs_statsmtimems" id="all_fs_statsmtimems">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_mtimems"></a></h5>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The timestamp indicating the last time this file was modified expressed in
milliseconds since the POSIX Epoch.</p>
<h5><code>stats.ctimeMs</code><span><a class="mark" href="#all_fs_statsctimems" id="all_fs_statsctimems">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_ctimems"></a></h5>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The timestamp indicating the last time the file status was changed expressed
in milliseconds since the POSIX Epoch.</p>
<h5><code>stats.birthtimeMs</code><span><a class="mark" href="#all_fs_statsbirthtimems" id="all_fs_statsbirthtimems">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_birthtimems"></a></h5>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The timestamp indicating the creation time of this file expressed in
milliseconds since the POSIX Epoch.</p>
<h5><code>stats.atimeNs</code><span><a class="mark" href="#all_fs_statsatimens" id="all_fs_statsatimens">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_atimens"></a></h5>
<div class="api_metadata">
<span>Added in: v12.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Only present when <code>bigint: true</code> is passed into the method that generates
the object.
The timestamp indicating the last time this file was accessed expressed in
nanoseconds since the POSIX Epoch.</p>
<h5><code>stats.mtimeNs</code><span><a class="mark" href="#all_fs_statsmtimens" id="all_fs_statsmtimens">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_mtimens"></a></h5>
<div class="api_metadata">
<span>Added in: v12.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Only present when <code>bigint: true</code> is passed into the method that generates
the object.
The timestamp indicating the last time this file was modified expressed in
nanoseconds since the POSIX Epoch.</p>
<h5><code>stats.ctimeNs</code><span><a class="mark" href="#all_fs_statsctimens" id="all_fs_statsctimens">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_ctimens"></a></h5>
<div class="api_metadata">
<span>Added in: v12.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Only present when <code>bigint: true</code> is passed into the method that generates
the object.
The timestamp indicating the last time the file status was changed expressed
in nanoseconds since the POSIX Epoch.</p>
<h5><code>stats.birthtimeNs</code><span><a class="mark" href="#all_fs_statsbirthtimens" id="all_fs_statsbirthtimens">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_birthtimens"></a></h5>
<div class="api_metadata">
<span>Added in: v12.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Only present when <code>bigint: true</code> is passed into the method that generates
the object.
The timestamp indicating the creation time of this file expressed in
nanoseconds since the POSIX Epoch.</p>
<h5><code>stats.atime</code><span><a class="mark" href="#all_fs_statsatime" id="all_fs_statsatime">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_atime"></a></h5>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li>
</ul>
<p>The timestamp indicating the last time this file was accessed.</p>
<h5><code>stats.mtime</code><span><a class="mark" href="#all_fs_statsmtime" id="all_fs_statsmtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_mtime"></a></h5>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li>
</ul>
<p>The timestamp indicating the last time this file was modified.</p>
<h5><code>stats.ctime</code><span><a class="mark" href="#all_fs_statsctime" id="all_fs_statsctime">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_ctime"></a></h5>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li>
</ul>
<p>The timestamp indicating the last time the file status was changed.</p>
<h5><code>stats.birthtime</code><span><a class="mark" href="#all_fs_statsbirthtime" id="all_fs_statsbirthtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_birthtime"></a></h5>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li>
</ul>
<p>The timestamp indicating the creation time of this file.</p>
<h5>Stat time values<span><a class="mark" href="#all_fs_stat-time-values" id="all_fs_stat-time-values">#</a></span><a aria-hidden="true" class="legacy" id="fs_stat_time_values"></a></h5>
<p>The <code>atimeMs</code>, <code>mtimeMs</code>, <code>ctimeMs</code>, <code>birthtimeMs</code> properties are
numeric values that hold the corresponding times in milliseconds. Their
precision is platform specific. When <code>bigint: true</code> is passed into the
method that generates the object, the properties will be <a href="https://tc39.github.io/proposal-bigint">bigints</a>,
otherwise they will be <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type">numbers</a>.</p>
<p>The <code>atimeNs</code>, <code>mtimeNs</code>, <code>ctimeNs</code>, <code>birthtimeNs</code> properties are
<a href="https://tc39.github.io/proposal-bigint">bigints</a> that hold the corresponding times in nanoseconds. They are
only present when <code>bigint: true</code> is passed into the method that generates
the object. Their precision is platform specific.</p>
<p><code>atime</code>, <code>mtime</code>, <code>ctime</code>, and <code>birthtime</code> are
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date"><code>Date</code></a> object alternate representations of the various times. The
<code>Date</code> and number values are not connected. Assigning a new number value, or
mutating the <code>Date</code> value, will not be reflected in the corresponding alternate
representation.</p>
<p>The times in the stat object have the following semantics:</p>
<ul>
<li><code>atime</code> "Access Time": Time when file data last accessed. Changed
by the <a href="http://man7.org/linux/man-pages/man2/mknod.2.html"><code>mknod(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html"><code>utimes(2)</code></a>, and <a href="http://man7.org/linux/man-pages/man2/read.2.html"><code>read(2)</code></a> system calls.</li>
<li><code>mtime</code> "Modified Time": Time when file data last modified.
Changed by the <a href="http://man7.org/linux/man-pages/man2/mknod.2.html"><code>mknod(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html"><code>utimes(2)</code></a>, and <a href="http://man7.org/linux/man-pages/man2/write.2.html"><code>write(2)</code></a> system calls.</li>
<li><code>ctime</code> "Change Time": Time when file status was last changed
(inode data modification). Changed by the <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a>,
<a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/mknod.2.html"><code>mknod(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/rename.2.html"><code>rename(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html"><code>utimes(2)</code></a>,
<a href="http://man7.org/linux/man-pages/man2/read.2.html"><code>read(2)</code></a>, and <a href="http://man7.org/linux/man-pages/man2/write.2.html"><code>write(2)</code></a> system calls.</li>
<li><code>birthtime</code> "Birth Time": Time of file creation. Set once when the
file is created. On file systems where birthtime is not available,
this field may instead hold either the <code>ctime</code> or
<code>1970-01-01T00:00Z</code> (ie, Unix epoch timestamp <code>0</code>). This value may be greater
than <code>atime</code> or <code>mtime</code> in this case. On Darwin and other FreeBSD variants,
also set if the <code>atime</code> is explicitly set to an earlier value than the current
<code>birthtime</code> using the <a href="http://man7.org/linux/man-pages/man2/utimes.2.html"><code>utimes(2)</code></a> system call.</li>
</ul>
<p>Prior to Node.js 0.12, the <code>ctime</code> held the <code>birthtime</code> on Windows systems. As
of 0.12, <code>ctime</code> is not "creation time", and on Unix systems, it never was.</p>
<h4>Class: <code>fs.StatFs</code><span><a class="mark" href="#all_fs_class-fsstatfs" id="all_fs_class-fsstatfs">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_statfs"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<p>Provides information about a mounted file system.</p>
<p>Objects returned from <a href="#all_fs_fsstatfspath-options-callback"><code>fs.statfs()</code></a> and its synchronous counterpart are of
this type. If <code>bigint</code> in the <code>options</code> passed to those methods is <code>true</code>, the
numeric values will be <code>bigint</code> instead of <code>number</code>.</p>
<pre><code class="language-console">StatFs {
type: 1397114950,
bsize: 4096,
blocks: 121938943,
bfree: 61058895,
bavail: 61058895,
files: 999,
ffree: 1000000
}</code> <button class="copy-button">copy</button></pre>
<p><code>bigint</code> version:</p>
<pre><code class="language-console">StatFs {
type: 1397114950n,
bsize: 4096n,
blocks: 121938943n,
bfree: 61058895n,
bavail: 61058895n,
files: 999n,
ffree: 1000000n
}</code> <button class="copy-button">copy</button></pre>
<h5><code>statfs.bavail</code><span><a class="mark" href="#all_fs_statfsbavail" id="all_fs_statfsbavail">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_bavail"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Free blocks available to unprivileged users.</p>
<h5><code>statfs.bfree</code><span><a class="mark" href="#all_fs_statfsbfree" id="all_fs_statfsbfree">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_bfree"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Free blocks in file system.</p>
<h5><code>statfs.blocks</code><span><a class="mark" href="#all_fs_statfsblocks" id="all_fs_statfsblocks">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_blocks"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Total data blocks in file system.</p>
<h5><code>statfs.bsize</code><span><a class="mark" href="#all_fs_statfsbsize" id="all_fs_statfsbsize">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_bsize"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Optimal transfer block size.</p>
<h5><code>statfs.ffree</code><span><a class="mark" href="#all_fs_statfsffree" id="all_fs_statfsffree">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_ffree"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Free file nodes in file system.</p>
<h5><code>statfs.files</code><span><a class="mark" href="#all_fs_statfsfiles" id="all_fs_statfsfiles">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_files"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Total file nodes in file system.</p>
<h5><code>statfs.type</code><span><a class="mark" href="#all_fs_statfstype" id="all_fs_statfstype">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_type"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Type of file system.</p>
<h4>Class: <code>fs.WriteStream</code><span><a class="mark" href="#all_fs_class-fswritestream" id="all_fs_class-fswritestream">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_writestream"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<ul>
<li>Extends <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a></li>
</ul>
<p>Instances of <a href="#all_fs_class-fswritestream" class="type"><fs.WriteStream></a> are created and returned using the
<a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a> function.</p>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_fs_event-close_3" id="all_fs_event-close_3">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_close_3"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<p>Emitted when the <a href="#all_fs_class-fswritestream" class="type"><fs.WriteStream></a>'s underlying file descriptor has been closed.</p>
<h5>Event: <code>'open'</code><span><a class="mark" href="#all_fs_event-open_1" id="all_fs_event-open_1">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_open_1"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Integer file descriptor used by the <a href="#all_fs_class-fswritestream" class="type"><fs.WriteStream></a>.</li>
</ul>
<p>Emitted when the <a href="#all_fs_class-fswritestream" class="type"><fs.WriteStream></a>'s file is opened.</p>
<h5>Event: <code>'ready'</code><span><a class="mark" href="#all_fs_event-ready_1" id="all_fs_event-ready_1">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_ready_1"></a></h5>
<div class="api_metadata">
<span>Added in: v9.11.0</span>
</div>
<p>Emitted when the <a href="#all_fs_class-fswritestream" class="type"><fs.WriteStream></a> is ready to be used.</p>
<p>Fires immediately after <code>'open'</code>.</p>
<h5><code>writeStream.bytesWritten</code><span><a class="mark" href="#all_fs_writestreambyteswritten" id="all_fs_writestreambyteswritten">#</a></span><a aria-hidden="true" class="legacy" id="fs_writestream_byteswritten"></a></h5>
<div class="api_metadata">
<span>Added in: v0.4.7</span>
</div>
<p>The number of bytes written so far. Does not include data that is still queued
for writing.</p>
<h5><code>writeStream.close([callback])</code><span><a class="mark" href="#all_fs_writestreamclosecallback" id="all_fs_writestreamclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="fs_writestream_close_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</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>
<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>
</ul>
</li>
</ul>
<p>Closes <code>writeStream</code>. Optionally accepts a
callback that will be executed once the <code>writeStream</code>
is closed.</p>
<h5><code>writeStream.path</code><span><a class="mark" href="#all_fs_writestreampath" id="all_fs_writestreampath">#</a></span><a aria-hidden="true" class="legacy" id="fs_writestream_path"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<p>The path to the file the stream is writing to as specified in the first
argument to <a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a>. If <code>path</code> is passed as a string, then
<code>writeStream.path</code> will be a string. If <code>path</code> is passed as a <a href="#all_buffer_class-buffer" class="type"><Buffer></a>, then
<code>writeStream.path</code> will be a <a href="#all_buffer_class-buffer" class="type"><Buffer></a>.</p>
<h5><code>writeStream.pending</code><span><a class="mark" href="#all_fs_writestreampending" id="all_fs_writestreampending">#</a></span><a aria-hidden="true" class="legacy" id="fs_writestream_pending"></a></h5>
<div class="api_metadata">
<span>Added in: v11.2.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 is <code>true</code> if the underlying file has not been opened yet,
i.e. before the <code>'ready'</code> event is emitted.</p>
<h4><code>fs.constants</code><span><a class="mark" href="#all_fs_fsconstants" id="all_fs_fsconstants">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_constants"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns an object containing commonly used constants for file system
operations.</p>
<h5>FS constants<span><a class="mark" href="#all_fs_fs-constants" id="all_fs_fs-constants">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_constants_1"></a></h5>
<p>The following constants are exported by <code>fs.constants</code> and <code>fsPromises.constants</code>.</p>
<p>Not every constant will be available on every operating system;
this is especially important for Windows, where many of the POSIX specific
definitions are not available.
For portable applications it is recommended to check for their presence
before use.</p>
<p>To use more than one constant, use the bitwise OR <code>|</code> operator.</p>
<p>Example:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> {
<span class="hljs-variable constant_">O_RDWR</span>,
<span class="hljs-variable constant_">O_CREAT</span>,
<span class="hljs-variable constant_">O_EXCL</span>,
} = constants;
<span class="hljs-title function_">open</span>(<span class="hljs-string">'/path/to/my/file'</span>, <span class="hljs-variable constant_">O_RDWR</span> | <span class="hljs-variable constant_">O_CREAT</span> | <span class="hljs-variable constant_">O_EXCL</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-comment">// ...</span>
});</code> <button class="copy-button">copy</button></pre>
<h6>File access constants<span><a class="mark" href="#all_fs_file-access-constants" id="all_fs_file-access-constants">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_access_constants"></a></h6>
<p>The following constants are meant for use as the <code>mode</code> parameter passed to
<a href="#all_fs_fspromisesaccesspath-mode"><code>fsPromises.access()</code></a>, <a href="#all_fs_fsaccesspath-mode-callback"><code>fs.access()</code></a>, and <a href="#all_fs_fsaccesssyncpath-mode"><code>fs.accessSync()</code></a>.</p>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>F_OK</code></td>
<td>Flag indicating that the file is visible to the calling process.
This is useful for determining if a file exists, but says nothing
about <code>rwx</code> permissions. Default if no mode is specified.</td>
</tr>
<tr>
<td><code>R_OK</code></td>
<td>Flag indicating that the file can be read by the calling process.</td>
</tr>
<tr>
<td><code>W_OK</code></td>
<td>Flag indicating that the file can be written by the calling
process.</td>
</tr>
<tr>
<td><code>X_OK</code></td>
<td>Flag indicating that the file can be executed by the calling
process. This has no effect on Windows
(will behave like <code>fs.constants.F_OK</code>).</td>
</tr>
</tbody></table>
<p>The definitions are also available on Windows.</p>
<h6>File copy constants<span><a class="mark" href="#all_fs_file-copy-constants" id="all_fs_file-copy-constants">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_copy_constants"></a></h6>
<p>The following constants are meant for use with <a href="#all_fs_fscopyfilesrc-dest-mode-callback"><code>fs.copyFile()</code></a>.</p>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>COPYFILE_EXCL</code></td>
<td>If present, the copy operation will fail with an error if the
destination path already exists.</td>
</tr>
<tr>
<td><code>COPYFILE_FICLONE</code></td>
<td>If present, the copy operation will attempt to create a
copy-on-write reflink. If the underlying platform does not support
copy-on-write, then a fallback copy mechanism is used.</td>
</tr>
<tr>
<td><code>COPYFILE_FICLONE_FORCE</code></td>
<td>If present, the copy operation will attempt to create a
copy-on-write reflink. If the underlying platform does not support
copy-on-write, then the operation will fail with an error.</td>
</tr>
</tbody></table>
<p>The definitions are also available on Windows.</p>
<h6>File open constants<span><a class="mark" href="#all_fs_file-open-constants" id="all_fs_file-open-constants">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_open_constants"></a></h6>
<p>The following constants are meant for use with <code>fs.open()</code>.</p>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>O_RDONLY</code></td>
<td>Flag indicating to open a file for read-only access.</td>
</tr>
<tr>
<td><code>O_WRONLY</code></td>
<td>Flag indicating to open a file for write-only access.</td>
</tr>
<tr>
<td><code>O_RDWR</code></td>
<td>Flag indicating to open a file for read-write access.</td>
</tr>
<tr>
<td><code>O_CREAT</code></td>
<td>Flag indicating to create the file if it does not already exist.</td>
</tr>
<tr>
<td><code>O_EXCL</code></td>
<td>Flag indicating that opening a file should fail if the
<code>O_CREAT</code> flag is set and the file already exists.</td>
</tr>
<tr>
<td><code>O_NOCTTY</code></td>
<td>Flag indicating that if path identifies a terminal device, opening the
path shall not cause that terminal to become the controlling terminal for
the process (if the process does not already have one).</td>
</tr>
<tr>
<td><code>O_TRUNC</code></td>
<td>Flag indicating that if the file exists and is a regular file, and the
file is opened successfully for write access, its length shall be truncated
to zero.</td>
</tr>
<tr>
<td><code>O_APPEND</code></td>
<td>Flag indicating that data will be appended to the end of the file.</td>
</tr>
<tr>
<td><code>O_DIRECTORY</code></td>
<td>Flag indicating that the open should fail if the path is not a
directory.</td>
</tr>
<tr>
<td><code>O_NOATIME</code></td>
<td>Flag indicating reading accesses to the file system will no longer
result in an update to the <code>atime</code> information associated with
the file. This flag is available on Linux operating systems only.</td>
</tr>
<tr>
<td><code>O_NOFOLLOW</code></td>
<td>Flag indicating that the open should fail if the path is a symbolic
link.</td>
</tr>
<tr>
<td><code>O_SYNC</code></td>
<td>Flag indicating that the file is opened for synchronized I/O with write
operations waiting for file integrity.</td>
</tr>
<tr>
<td><code>O_DSYNC</code></td>
<td>Flag indicating that the file is opened for synchronized I/O with write
operations waiting for data integrity.</td>
</tr>
<tr>
<td><code>O_SYMLINK</code></td>
<td>Flag indicating to open the symbolic link itself rather than the
resource it is pointing to.</td>
</tr>
<tr>
<td><code>O_DIRECT</code></td>
<td>When set, an attempt will be made to minimize caching effects of file
I/O.</td>
</tr>
<tr>
<td><code>O_NONBLOCK</code></td>
<td>Flag indicating to open the file in nonblocking mode when possible.</td>
</tr>
<tr>
<td><code>UV_FS_O_FILEMAP</code></td>
<td>When set, a memory file mapping is used to access the file. This flag
is available on Windows operating systems only. On other operating systems,
this flag is ignored.</td>
</tr>
</tbody></table>
<p>On Windows, only <code>O_APPEND</code>, <code>O_CREAT</code>, <code>O_EXCL</code>, <code>O_RDONLY</code>, <code>O_RDWR</code>,
<code>O_TRUNC</code>, <code>O_WRONLY</code>, and <code>UV_FS_O_FILEMAP</code> are available.</p>
<h6>File type constants<span><a class="mark" href="#all_fs_file-type-constants" id="all_fs_file-type-constants">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_type_constants"></a></h6>
<p>The following constants are meant for use with the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object's
<code>mode</code> property for determining a file's type.</p>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>S_IFMT</code></td>
<td>Bit mask used to extract the file type code.</td>
</tr>
<tr>
<td><code>S_IFREG</code></td>
<td>File type constant for a regular file.</td>
</tr>
<tr>
<td><code>S_IFDIR</code></td>
<td>File type constant for a directory.</td>
</tr>
<tr>
<td><code>S_IFCHR</code></td>
<td>File type constant for a character-oriented device file.</td>
</tr>
<tr>
<td><code>S_IFBLK</code></td>
<td>File type constant for a block-oriented device file.</td>
</tr>
<tr>
<td><code>S_IFIFO</code></td>
<td>File type constant for a FIFO/pipe.</td>
</tr>
<tr>
<td><code>S_IFLNK</code></td>
<td>File type constant for a symbolic link.</td>
</tr>
<tr>
<td><code>S_IFSOCK</code></td>
<td>File type constant for a socket.</td>
</tr>
</tbody></table>
<p>On Windows, only <code>S_IFCHR</code>, <code>S_IFDIR</code>, <code>S_IFLNK</code>, <code>S_IFMT</code>, and <code>S_IFREG</code>,
are available.</p>
<h6>File mode constants<span><a class="mark" href="#all_fs_file-mode-constants" id="all_fs_file-mode-constants">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_mode_constants"></a></h6>
<p>The following constants are meant for use with the <a href="#all_fs_class-fsstats" class="type"><fs.Stats></a> object's
<code>mode</code> property for determining the access permissions for a file.</p>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>S_IRWXU</code></td>
<td>File mode indicating readable, writable, and executable by owner.</td>
</tr>
<tr>
<td><code>S_IRUSR</code></td>
<td>File mode indicating readable by owner.</td>
</tr>
<tr>
<td><code>S_IWUSR</code></td>
<td>File mode indicating writable by owner.</td>
</tr>
<tr>
<td><code>S_IXUSR</code></td>
<td>File mode indicating executable by owner.</td>
</tr>
<tr>
<td><code>S_IRWXG</code></td>
<td>File mode indicating readable, writable, and executable by group.</td>
</tr>
<tr>
<td><code>S_IRGRP</code></td>
<td>File mode indicating readable by group.</td>
</tr>
<tr>
<td><code>S_IWGRP</code></td>
<td>File mode indicating writable by group.</td>
</tr>
<tr>
<td><code>S_IXGRP</code></td>
<td>File mode indicating executable by group.</td>
</tr>
<tr>
<td><code>S_IRWXO</code></td>
<td>File mode indicating readable, writable, and executable by others.</td>
</tr>
<tr>
<td><code>S_IROTH</code></td>
<td>File mode indicating readable by others.</td>
</tr>
<tr>
<td><code>S_IWOTH</code></td>
<td>File mode indicating writable by others.</td>
</tr>
<tr>
<td><code>S_IXOTH</code></td>
<td>File mode indicating executable by others.</td>
</tr>
</tbody></table>
<p>On Windows, only <code>S_IRUSR</code> and <code>S_IWUSR</code> are available.</p>
</section><section><h3>Notes<span><a class="mark" href="#all_fs_notes" id="all_fs_notes">#</a></span><a aria-hidden="true" class="legacy" id="fs_notes"></a></h3>
<h4>Ordering of callback and promise-based operations<span><a class="mark" href="#all_fs_ordering-of-callback-and-promise-based-operations" id="all_fs_ordering-of-callback-and-promise-based-operations">#</a></span><a aria-hidden="true" class="legacy" id="fs_ordering_of_callback_and_promise_based_operations"></a></h4>
<p>Because they are executed asynchronously by the underlying thread pool,
there is no guaranteed ordering when using either the callback or
promise-based methods.</p>
<p>For example, the following is prone to error because the <code>fs.stat()</code>
operation might complete before the <code>fs.rename()</code> operation:</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>);
fs.<span class="hljs-title function_">rename</span>(<span class="hljs-string">'/tmp/hello'</span>, <span class="hljs-string">'/tmp/world'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'renamed complete'</span>);
});
fs.<span class="hljs-title function_">stat</span>(<span class="hljs-string">'/tmp/world'</span>, <span class="hljs-function">(<span class="hljs-params">err, stats</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stats: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(stats)}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>It is important to correctly order the operations by awaiting the results
of one before invoking the other:</p>
<pre class="with-53-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> { rename, stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">const</span> oldPath = <span class="hljs-string">'/tmp/hello'</span>;
<span class="hljs-keyword">const</span> newPath = <span class="hljs-string">'/tmp/world'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">rename</span>(oldPath, newPath);
<span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(newPath);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stats: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(stats)}</span>`</span>);
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'there was an error:'</span>, error.<span class="hljs-property">message</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { rename, stat } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);
(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params">oldPath, newPath</span>) {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">rename</span>(oldPath, newPath);
<span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(newPath);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stats: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(stats)}</span>`</span>);
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'there was an error:'</span>, error.<span class="hljs-property">message</span>);
}
})(<span class="hljs-string">'/tmp/hello'</span>, <span class="hljs-string">'/tmp/world'</span>);</code><button class="copy-button">copy</button></pre>
<p>Or, when using the callback APIs, move the <code>fs.stat()</code> call into the callback
of the <code>fs.rename()</code> operation:</p>
<pre class="with-53-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> { rename, stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">rename</span>(<span class="hljs-string">'/tmp/hello'</span>, <span class="hljs-string">'/tmp/world'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-title function_">stat</span>(<span class="hljs-string">'/tmp/world'</span>, <span class="hljs-function">(<span class="hljs-params">err, stats</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stats: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(stats)}</span>`</span>);
});
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { rename, stat } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);
<span class="hljs-title function_">rename</span>(<span class="hljs-string">'/tmp/hello'</span>, <span class="hljs-string">'/tmp/world'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-title function_">stat</span>(<span class="hljs-string">'/tmp/world'</span>, <span class="hljs-function">(<span class="hljs-params">err, stats</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stats: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(stats)}</span>`</span>);
});
});</code><button class="copy-button">copy</button></pre>
<h4>File paths<span><a class="mark" href="#all_fs_file-paths" id="all_fs_file-paths">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_paths"></a></h4>
<p>Most <code>fs</code> operations accept file paths that may be specified in the form of
a string, a <a href="#all_buffer_class-buffer" class="type"><Buffer></a>, or a <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> object using the <code>file:</code> protocol.</p>
<h5>String paths<span><a class="mark" href="#all_fs_string-paths" id="all_fs_string-paths">#</a></span><a aria-hidden="true" class="legacy" id="fs_string_paths"></a></h5>
<p>String paths are interpreted as UTF-8 character sequences identifying
the absolute or relative filename. Relative paths will be resolved relative
to the current working directory as determined by calling <code>process.cwd()</code>.</p>
<p>Example using an absolute path on POSIX:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">let</span> fd;
<span class="hljs-keyword">try</span> {
fd = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'/open/some/file.txt'</span>, <span class="hljs-string">'r'</span>);
<span class="hljs-comment">// Do something with the file</span>
} <span class="hljs-keyword">finally</span> {
<span class="hljs-keyword">await</span> fd?.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<p>Example using a relative path on POSIX (relative to <code>process.cwd()</code>):</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">let</span> fd;
<span class="hljs-keyword">try</span> {
fd = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'file.txt'</span>, <span class="hljs-string">'r'</span>);
<span class="hljs-comment">// Do something with the file</span>
} <span class="hljs-keyword">finally</span> {
<span class="hljs-keyword">await</span> fd?.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<h5>File URL paths<span><a class="mark" href="#all_fs_file-url-paths" id="all_fs_file-url-paths">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_url_paths"></a></h5>
<div class="api_metadata">
<span>Added in: v7.6.0</span>
</div>
<p>For most <code>node:fs</code> module functions, the <code>path</code> or <code>filename</code> argument may be
passed as a <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> object using the <code>file:</code> protocol.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///tmp/hello'</span>));</code> <button class="copy-button">copy</button></pre>
<p><code>file:</code> URLs are always absolute paths.</p>
<h6>Platform-specific considerations<span><a class="mark" href="#all_fs_platform-specific-considerations" id="all_fs_platform-specific-considerations">#</a></span><a aria-hidden="true" class="legacy" id="fs_platform_specific_considerations"></a></h6>
<p>On Windows, <code>file:</code> <a href="#all_url_the-whatwg-url-api" class="type"><URL></a>s with a host name convert to UNC paths, while <code>file:</code>
<a href="#all_url_the-whatwg-url-api" class="type"><URL></a>s with drive letters convert to local absolute paths. <code>file:</code> <a href="#all_url_the-whatwg-url-api" class="type"><URL></a>s
with no host name and no drive letter will result in an error:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// On Windows :</span>
<span class="hljs-comment">// - WHATWG file URLs with hostname convert to UNC path</span>
<span class="hljs-comment">// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file://hostname/p/a/t/h/file'</span>));
<span class="hljs-comment">// - WHATWG file URLs with drive letters convert to absolute path</span>
<span class="hljs-comment">// file:///C:/tmp/hello => C:\tmp\hello</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/tmp/hello'</span>));
<span class="hljs-comment">// - WHATWG file URLs without hostname must have a drive letters</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///notdriveletter/p/a/t/h/file'</span>));
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///c/p/a/t/h/file'</span>));
<span class="hljs-comment">// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute</span></code> <button class="copy-button">copy</button></pre>
<p><code>file:</code> <a href="#all_url_the-whatwg-url-api" class="type"><URL></a>s with drive letters must use <code>:</code> as a separator just after
the drive letter. Using another separator will result in an error.</p>
<p>On all other platforms, <code>file:</code> <a href="#all_url_the-whatwg-url-api" class="type"><URL></a>s with a host name are unsupported and
will result in an error:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// On other platforms:</span>
<span class="hljs-comment">// - WHATWG file URLs with hostname are unsupported</span>
<span class="hljs-comment">// file://hostname/p/a/t/h/file => throw!</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file://hostname/p/a/t/h/file'</span>));
<span class="hljs-comment">// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute</span>
<span class="hljs-comment">// - WHATWG file URLs convert to absolute path</span>
<span class="hljs-comment">// file:///tmp/hello => /tmp/hello</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///tmp/hello'</span>));</code> <button class="copy-button">copy</button></pre>
<p>A <code>file:</code> <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> having encoded slash characters will result in an error on all
platforms:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// On Windows</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/p/a/t/h/%2F'</span>));
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/p/a/t/h/%2f'</span>));
<span class="hljs-comment">/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
\ or / characters */</span>
<span class="hljs-comment">// On POSIX</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///p/a/t/h/%2F'</span>));
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///p/a/t/h/%2f'</span>));
<span class="hljs-comment">/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
/ characters */</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows, <code>file:</code> <a href="#all_url_the-whatwg-url-api" class="type"><URL></a>s having encoded backslash will result in an error:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// On Windows</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/path/%5C'</span>));
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/path/%5c'</span>));
<span class="hljs-comment">/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
\ or / characters */</span></code> <button class="copy-button">copy</button></pre>
<h5>Buffer paths<span><a class="mark" href="#all_fs_buffer-paths" id="all_fs_buffer-paths">#</a></span><a aria-hidden="true" class="legacy" id="fs_buffer_paths"></a></h5>
<p>Paths specified using a <a href="#all_buffer_class-buffer" class="type"><Buffer></a> are useful primarily on certain POSIX
operating systems that treat file paths as opaque byte sequences. On such
systems, it is possible for a single file path to contain sub-sequences that
use multiple character encodings. As with string paths, <a href="#all_buffer_class-buffer" class="type"><Buffer></a> paths may
be relative or absolute:</p>
<p>Example using an absolute path on POSIX:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">let</span> fd;
<span class="hljs-keyword">try</span> {
fd = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'/open/some/file.txt'</span>), <span class="hljs-string">'r'</span>);
<span class="hljs-comment">// Do something with the file</span>
} <span class="hljs-keyword">finally</span> {
<span class="hljs-keyword">await</span> fd?.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<h5>Per-drive working directories on Windows<span><a class="mark" href="#all_fs_per-drive-working-directories-on-windows" id="all_fs_per-drive-working-directories-on-windows">#</a></span><a aria-hidden="true" class="legacy" id="fs_per_drive_working_directories_on_windows"></a></h5>
<p>On Windows, Node.js follows the concept of per-drive working directory. This
behavior can be observed when using a drive path without a backslash. For
example <code>fs.readdirSync('C:\\')</code> can potentially return a different result than
<code>fs.readdirSync('C:')</code>. For more information, see
<a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths">this MSDN page</a>.</p>
<h4>File descriptors<span><a class="mark" href="#all_fs_file-descriptors_1" id="all_fs_file-descriptors_1">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_descriptors_1"></a></h4>
<p>On POSIX systems, for every process, the kernel maintains a table of currently
open files and resources. Each open file is assigned a simple numeric
identifier called a <em>file descriptor</em>. At the system-level, all file system
operations use these file descriptors to identify and track each specific
file. Windows systems use a different but conceptually similar mechanism for
tracking resources. To simplify things for users, Node.js abstracts away the
differences between operating systems and assigns all open files a numeric file
descriptor.</p>
<p>The callback-based <code>fs.open()</code>, and synchronous <code>fs.openSync()</code> methods open a
file and allocate a new file descriptor. Once allocated, the file descriptor may
be used to read data from, write data to, or request information about the file.</p>
<p>Operating systems limit the number of file descriptors that may be open
at any given time so it is critical to close the descriptor when operations
are completed. Failure to do so will result in a memory leak that will
eventually cause an application to crash.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close, fstat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">closeFd</span>(<span class="hljs-params">fd</span>) {
<span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});
}
<span class="hljs-title function_">open</span>(<span class="hljs-string">'/open/some/file.txt'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">fstat</span>(fd, <span class="hljs-function">(<span class="hljs-params">err, stat</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-title function_">closeFd</span>(fd);
<span class="hljs-keyword">throw</span> err;
}
<span class="hljs-comment">// use stat</span>
<span class="hljs-title function_">closeFd</span>(fd);
});
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-title function_">closeFd</span>(fd);
<span class="hljs-keyword">throw</span> err;
}
});</code> <button class="copy-button">copy</button></pre>
<p>The promise-based APIs use a <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> object in place of the numeric
file descriptor. These objects are better managed by the system to ensure
that resources are not leaked. However, it is still required that they are
closed when operations are completed:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">let</span> file;
<span class="hljs-keyword">try</span> {
file = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'/open/some/file.txt'</span>, <span class="hljs-string">'r'</span>);
<span class="hljs-keyword">const</span> stat = <span class="hljs-keyword">await</span> file.<span class="hljs-title function_">stat</span>();
<span class="hljs-comment">// use stat</span>
} <span class="hljs-keyword">finally</span> {
<span class="hljs-keyword">await</span> file.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<h4>Threadpool usage<span><a class="mark" href="#all_fs_threadpool-usage" id="all_fs_threadpool-usage">#</a></span><a aria-hidden="true" class="legacy" id="fs_threadpool_usage"></a></h4>
<p>All callback and promise-based file system APIs (with the exception of
<code>fs.FSWatcher()</code>) use libuv's threadpool. This can have surprising and negative
performance implications for some applications. See the
<a href="#all_cli_uv_threadpool_sizesize"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>
<h4>File system flags<span><a class="mark" href="#all_fs_file-system-flags" id="all_fs_file-system-flags">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_system_flags"></a></h4>
<p>The following flags are available wherever the <code>flag</code> option takes a
string.</p>
<ul>
<li>
<p><code>'a'</code>: Open file for appending.
The file is created if it does not exist.</p>
</li>
<li>
<p><code>'ax'</code>: Like <code>'a'</code> but fails if the path exists.</p>
</li>
<li>
<p><code>'a+'</code>: Open file for reading and appending.
The file is created if it does not exist.</p>
</li>
<li>
<p><code>'ax+'</code>: Like <code>'a+'</code> but fails if the path exists.</p>
</li>
<li>
<p><code>'as'</code>: Open file for appending in synchronous mode.
The file is created if it does not exist.</p>
</li>
<li>
<p><code>'as+'</code>: Open file for reading and appending in synchronous mode.
The file is created if it does not exist.</p>
</li>
<li>
<p><code>'r'</code>: Open file for reading.
An exception occurs if the file does not exist.</p>
</li>
<li>
<p><code>'rs'</code>: Open file for reading in synchronous mode.
An exception occurs if the file does not exist.</p>
</li>
<li>
<p><code>'r+'</code>: Open file for reading and writing.
An exception occurs if the file does not exist.</p>
</li>
<li>
<p><code>'rs+'</code>: Open file for reading and writing in synchronous mode. Instructs
the operating system to bypass the local file system cache.</p>
<p>This is primarily useful for opening files on NFS mounts as it allows
skipping the potentially stale local cache. It has a very real impact on
I/O performance so using this flag is not recommended unless it is needed.</p>
<p>This doesn't turn <code>fs.open()</code> or <code>fsPromises.open()</code> into a synchronous
blocking call. If synchronous operation is desired, something like
<code>fs.openSync()</code> should be used.</p>
</li>
<li>
<p><code>'w'</code>: Open file for writing.
The file is created (if it does not exist) or truncated (if it exists).</p>
</li>
<li>
<p><code>'wx'</code>: Like <code>'w'</code> but fails if the path exists.</p>
</li>
<li>
<p><code>'w+'</code>: Open file for reading and writing.
The file is created (if it does not exist) or truncated (if it exists).</p>
</li>
<li>
<p><code>'wx+'</code>: Like <code>'w+'</code> but fails if the path exists.</p>
</li>
</ul>
<p><code>flag</code> can also be a number as documented by <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a>; commonly used constants
are available from <code>fs.constants</code>. On Windows, flags are translated to
their equivalent ones where applicable, e.g. <code>O_WRONLY</code> to <code>FILE_GENERIC_WRITE</code>,
or <code>O_EXCL|O_CREAT</code> to <code>CREATE_NEW</code>, as accepted by <code>CreateFileW</code>.</p>
<p>The exclusive flag <code>'x'</code> (<code>O_EXCL</code> flag in <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a>) causes the operation to
return an error if the path already exists. On POSIX, if the path is a symbolic
link, using <code>O_EXCL</code> returns an error even if the link is to a path that does
not exist. The exclusive flag might not work with network file systems.</p>
<p>On Linux, positional writes don't work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.</p>
<p>Modifying a file rather than replacing it may require the <code>flag</code> option to be
set to <code>'r+'</code> rather than the default <code>'w'</code>.</p>
<p>The behavior of some flags are platform-specific. As such, opening a directory
on macOS and Linux with the <code>'a+'</code> flag, as in the example below, will return an
error. In contrast, on Windows and FreeBSD, a file descriptor or a <code>FileHandle</code>
will be returned.</p>
<pre><code class="language-js"><span class="hljs-comment">// macOS and Linux</span>
fs.<span class="hljs-title function_">open</span>(<span class="hljs-string">'<directory>'</span>, <span class="hljs-string">'a+'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-comment">// => [Error: EISDIR: illegal operation on a directory, open <directory>]</span>
});
<span class="hljs-comment">// Windows and FreeBSD</span>
fs.<span class="hljs-title function_">open</span>(<span class="hljs-string">'<directory>'</span>, <span class="hljs-string">'a+'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-comment">// => null, <fd></span>
});</code> <button class="copy-button">copy</button></pre>
<p>On Windows, opening an existing hidden file using the <code>'w'</code> flag (either
through <code>fs.open()</code>, <code>fs.writeFile()</code>, or <code>fsPromises.open()</code>) will fail with
<code>EPERM</code>. Existing hidden files can be opened for writing with the <code>'r+'</code> flag.</p>
<p>A call to <code>fs.ftruncate()</code> or <code>filehandle.truncate()</code> can be used to reset
the file contents.</p></section>
</section>
<section><h2>Global objects<span><a class="mark" href="#all_globals_global-objects" id="all_globals_global-objects">#</a></span><a aria-hidden="true" class="legacy" id="globals_global_objects"></a></h2>
<p>These objects are available in all modules.</p>
<p>The following variables may appear to be global but are not. They exist only in
the scope of <a href="modules.html">CommonJS modules</a>:</p>
<ul>
<li><a href="#all_modules___dirname"><code>__dirname</code></a></li>
<li><a href="#all_modules___filename"><code>__filename</code></a></li>
<li><a href="#all_modules_exports"><code>exports</code></a></li>
<li><a href="#all_modules_module"><code>module</code></a></li>
<li><a href="#all_modules_requireid"><code>require()</code></a></li>
</ul>
<p>The objects listed here are specific to Node.js. There are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects">built-in objects</a>
that are part of the JavaScript language itself, which are also globally
accessible.</p>
<section><h3>Class: <code>AbortController</code><span><a class="mark" href="#all_globals_class-abortcontroller" id="all_globals_class-abortcontroller">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_abortcontroller"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.4.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.0.0, v14.17.0</td>
<td><p><span>Added in: v15.0.0, v14.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>A utility class used to signal cancelation in selected <code>Promise</code>-based APIs.
The API is based on the Web API <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController"><code>AbortController</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
ac.<span class="hljs-property">signal</span>.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'abort'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Aborted!'</span>),
{ <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span> });
ac.<span class="hljs-title function_">abort</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(ac.<span class="hljs-property">signal</span>.<span class="hljs-property">aborted</span>); <span class="hljs-comment">// Prints true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>abortController.abort([reason])</code><span><a class="mark" href="#all_globals_abortcontrollerabortreason" id="all_globals_abortcontrollerabortreason">#</a></span><a aria-hidden="true" class="legacy" id="globals_abortcontroller_abort_reason"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.2.0, v16.14.0</td>
<td><p>Added the new optional reason argument.</p></td></tr>
<tr><td>v15.0.0, v14.17.0</td>
<td><p><span>Added in: v15.0.0, v14.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> An optional reason, retrievable on the <code>AbortSignal</code>'s
<code>reason</code> property.</li>
</ul>
<p>Triggers the abort signal, causing the <code>abortController.signal</code> to emit
the <code>'abort'</code> event.</p>
<h4><code>abortController.signal</code><span><a class="mark" href="#all_globals_abortcontrollersignal" id="all_globals_abortcontrollersignal">#</a></span><a aria-hidden="true" class="legacy" id="globals_abortcontroller_signal"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.17.0</span>
</div>
<ul>
<li>Type: <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a></li>
</ul>
<h4>Class: <code>AbortSignal</code><span><a class="mark" href="#all_globals_class-abortsignal" id="all_globals_class-abortsignal">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_abortsignal"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.17.0</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventtarget" class="type"><EventTarget></a></li>
</ul>
<p>The <code>AbortSignal</code> is used to notify observers when the
<code>abortController.abort()</code> method is called.</p>
<h5>Static method: <code>AbortSignal.abort([reason])</code><span><a class="mark" href="#all_globals_static-method-abortsignalabortreason" id="all_globals_static-method-abortsignalabortreason">#</a></span><a aria-hidden="true" class="legacy" id="globals_static_method_abortsignal_abort_reason"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.2.0, v16.14.0</td>
<td><p>Added the new optional reason argument.</p></td></tr>
<tr><td>v15.12.0, v14.17.0</td>
<td><p><span>Added in: v15.12.0, v14.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>reason</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="#all_globals_class-abortsignal" class="type"><AbortSignal></a></li>
</ul>
<p>Returns a new already aborted <code>AbortSignal</code>.</p>
<h5>Static method: <code>AbortSignal.timeout(delay)</code><span><a class="mark" href="#all_globals_static-method-abortsignaltimeoutdelay" id="all_globals_static-method-abortsignaltimeoutdelay">#</a></span><a aria-hidden="true" class="legacy" id="globals_static_method_abortsignal_timeout_delay"></a></h5>
<div class="api_metadata">
<span>Added in: v17.3.0, v16.14.0</span>
</div>
<ul>
<li><code>delay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds to wait before triggering
the AbortSignal.</li>
</ul>
<p>Returns a new <code>AbortSignal</code> which will be aborted in <code>delay</code> milliseconds.</p>
<h5>Static method: <code>AbortSignal.any(signals)</code><span><a class="mark" href="#all_globals_static-method-abortsignalanysignals" id="all_globals_static-method-abortsignalanysignals">#</a></span><a aria-hidden="true" class="legacy" id="globals_static_method_abortsignal_any_signals"></a></h5>
<div class="api_metadata">
<span>Added in: v20.3.0</span>
</div>
<ul>
<li><code>signals</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal[]></a> The <code>AbortSignal</code>s of which to compose a new <code>AbortSignal</code>.</li>
</ul>
<p>Returns a new <code>AbortSignal</code> which will be aborted if any of the provided
signals are aborted. Its <a href="#all_globals_abortsignalreason"><code>abortSignal.reason</code></a> will be set to whichever
one of the <code>signals</code> caused it to be aborted.</p>
<h5>Event: <code>'abort'</code><span><a class="mark" href="#all_globals_event-abort" id="all_globals_event-abort">#</a></span><a aria-hidden="true" class="legacy" id="globals_event_abort"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.17.0</span>
</div>
<p>The <code>'abort'</code> event is emitted when the <code>abortController.abort()</code> method
is called. The callback is invoked with a single object argument with a
single <code>type</code> property set to <code>'abort'</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-comment">// Use either the onabort property...</span>
ac.<span class="hljs-property">signal</span>.<span class="hljs-property">onabort</span> = <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'aborted!'</span>);
<span class="hljs-comment">// Or the EventTarget API...</span>
ac.<span class="hljs-property">signal</span>.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'abort'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>); <span class="hljs-comment">// Prints 'abort'</span>
}, { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span> });
ac.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<p>The <code>AbortController</code> with which the <code>AbortSignal</code> is associated will only
ever trigger the <code>'abort'</code> event once. We recommended that code check
that the <code>abortSignal.aborted</code> attribute is <code>false</code> before adding an <code>'abort'</code>
event listener.</p>
<p>Any event listeners attached to the <code>AbortSignal</code> should use the
<code>{ once: true }</code> option (or, if using the <code>EventEmitter</code> APIs to attach a
listener, use the <code>once()</code> method) to ensure that the event listener is
removed as soon as the <code>'abort'</code> event is handled. Failure to do so may
result in memory leaks.</p>
<h5><code>abortSignal.aborted</code><span><a class="mark" href="#all_globals_abortsignalaborted" id="all_globals_abortsignalaborted">#</a></span><a aria-hidden="true" class="legacy" id="globals_abortsignal_aborted"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.17.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> True after the <code>AbortController</code> has been aborted.</li>
</ul>
<h5><code>abortSignal.onabort</code><span><a class="mark" href="#all_globals_abortsignalonabort" id="all_globals_abortsignalonabort">#</a></span><a aria-hidden="true" class="legacy" id="globals_abortsignal_onabort"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.17.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>An optional callback function that may be set by user code to be notified
when the <code>abortController.abort()</code> function has been called.</p>
<h5><code>abortSignal.reason</code><span><a class="mark" href="#all_globals_abortsignalreason" id="all_globals_abortsignalreason">#</a></span><a aria-hidden="true" class="legacy" id="globals_abortsignal_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v17.2.0, v16.14.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>An optional reason specified when the <code>AbortSignal</code> was triggered.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
ac.<span class="hljs-title function_">abort</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'boom!'</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(ac.<span class="hljs-property">signal</span>.<span class="hljs-property">reason</span>); <span class="hljs-comment">// Error: boom!</span></code> <button class="copy-button">copy</button></pre>
<h5><code>abortSignal.throwIfAborted()</code><span><a class="mark" href="#all_globals_abortsignalthrowifaborted" id="all_globals_abortsignalthrowifaborted">#</a></span><a aria-hidden="true" class="legacy" id="globals_abortsignal_throwifaborted"></a></h5>
<div class="api_metadata">
<span>Added in: v17.3.0, v16.17.0</span>
</div>
<p>If <code>abortSignal.aborted</code> is <code>true</code>, throws <code>abortSignal.reason</code>.</p>
</section><section><h3>Class: <code>Blob</code><span><a class="mark" href="#all_globals_class-blob" id="all_globals_class-blob">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_blob"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p>See <a href="#all_buffer_class-blob" class="type"><Blob></a>.</p>
</section><section><h3>Class: <code>Buffer</code><span><a class="mark" href="#all_globals_class-buffer" id="all_globals_class-buffer">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_buffer"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.103</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>Used to handle binary data. See the <a href="buffer.html">buffer section</a>.</p>
</section><section><h3>Class: <code>ByteLengthQueuingStrategy</code><span><a class="mark" href="#all_globals_class-bytelengthqueuingstrategy" id="all_globals_class-bytelengthqueuingstrategy">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_bytelengthqueuingstrategy"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-bytelengthqueuingstrategy"><code>ByteLengthQueuingStrategy</code></a>.</p>
</section><section><h3><code>__dirname</code><span><a class="mark" href="#all_globals___dirname" id="all_globals___dirname">#</a></span><a aria-hidden="true" class="legacy" id="globals_dirname"></a></h3>
<p>This variable may appear to be global but is not. See <a href="#all_modules___dirname"><code>__dirname</code></a>.</p>
</section><section><h3><code>__filename</code><span><a class="mark" href="#all_globals___filename" id="all_globals___filename">#</a></span><a aria-hidden="true" class="legacy" id="globals_filename"></a></h3>
<p>This variable may appear to be global but is not. See <a href="#all_modules___filename"><code>__filename</code></a>.</p>
</section><section><h3><code>atob(data)</code><span><a class="mark" href="#all_globals_atobdata" id="all_globals_atobdata">#</a></span><a aria-hidden="true" class="legacy" id="globals_atob_data"></a></h3>
<div class="api_metadata">
<span>Added in: v16.0.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy. Use <code>Buffer.from(data, 'base64')</code> instead.</div><p></p>
<p>Global alias for <a href="#all_buffer_bufferatobdata"><code>buffer.atob()</code></a>.</p>
</section><section><h3><code>BroadcastChannel</code><span><a class="mark" href="#all_globals_broadcastchannel" id="all_globals_broadcastchannel">#</a></span><a aria-hidden="true" class="legacy" id="globals_broadcastchannel"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p>See <a href="#all_worker_threads_class-broadcastchannel-extends-eventtarget" class="type"><BroadcastChannel></a>.</p>
</section><section><h3><code>btoa(data)</code><span><a class="mark" href="#all_globals_btoadata" id="all_globals_btoadata">#</a></span><a aria-hidden="true" class="legacy" id="globals_btoa_data"></a></h3>
<div class="api_metadata">
<span>Added in: v16.0.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy. Use <code>buf.toString('base64')</code> instead.</div><p></p>
<p>Global alias for <a href="#all_buffer_bufferbtoadata"><code>buffer.btoa()</code></a>.</p>
</section><section><h3><code>clearImmediate(immediateObject)</code><span><a class="mark" href="#all_globals_clearimmediateimmediateobject" id="all_globals_clearimmediateimmediateobject">#</a></span><a aria-hidden="true" class="legacy" id="globals_clearimmediate_immediateobject"></a></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<p><a href="#all_timers_clearimmediateimmediate"><code>clearImmediate</code></a> is described in the <a href="timers.html">timers</a> section.</p>
</section><section><h3><code>clearInterval(intervalObject)</code><span><a class="mark" href="#all_globals_clearintervalintervalobject" id="all_globals_clearintervalintervalobject">#</a></span><a aria-hidden="true" class="legacy" id="globals_clearinterval_intervalobject"></a></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>
<p><a href="#all_timers_clearintervaltimeout"><code>clearInterval</code></a> is described in the <a href="timers.html">timers</a> section.</p>
</section><section><h3><code>clearTimeout(timeoutObject)</code><span><a class="mark" href="#all_globals_cleartimeouttimeoutobject" id="all_globals_cleartimeouttimeoutobject">#</a></span><a aria-hidden="true" class="legacy" id="globals_cleartimeout_timeoutobject"></a></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>
<p><a href="#all_timers_cleartimeouttimeout"><code>clearTimeout</code></a> is described in the <a href="timers.html">timers</a> section.</p>
</section><section><h3>Class: <code>CompressionStream</code><span><a class="mark" href="#all_globals_class-compressionstream" id="all_globals_class-compressionstream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_compressionstream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-compressionstream"><code>CompressionStream</code></a>.</p>
</section><section><h3><code>console</code><span><a class="mark" href="#all_globals_console" id="all_globals_console">#</a></span><a aria-hidden="true" class="legacy" id="globals_console"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Used to print to stdout and stderr. See the <a href="console.html"><code>console</code></a> section.</p>
</section><section><h3>Class: <code>CountQueuingStrategy</code><span><a class="mark" href="#all_globals_class-countqueuingstrategy" id="all_globals_class-countqueuingstrategy">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_countqueuingstrategy"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-countqueuingstrategy"><code>CountQueuingStrategy</code></a>.</p>
</section><section><h3><code>Crypto</code><span><a class="mark" href="#all_globals_crypto" id="all_globals_crypto">#</a></span><a aria-hidden="true" class="legacy" id="globals_crypto"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>No longer behind <code>--experimental-global-webcrypto</code> CLI flag.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p><span>Added in: v17.6.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the
<a href="#all_cli_--no-experimental-global-webcrypto"><code>--no-experimental-global-webcrypto</code></a> CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webcrypto_class-crypto" class="type"><Crypto></a>. This global is available
only if the Node.js binary was compiled with including support for the
<code>node:crypto</code> module.</p>
</section><section><h3><code>crypto</code><span><a class="mark" href="#all_globals_crypto_1" id="all_globals_crypto_1">#</a></span><a aria-hidden="true" class="legacy" id="globals_crypto_1"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>No longer behind <code>--experimental-global-webcrypto</code> CLI flag.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p><span>Added in: v17.6.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the
<a href="#all_cli_--no-experimental-global-webcrypto"><code>--no-experimental-global-webcrypto</code></a> CLI flag.</div><p></p>
<p>A browser-compatible implementation of the <a href="webcrypto.html">Web Crypto API</a>.</p>
</section><section><h3><code>CryptoKey</code><span><a class="mark" href="#all_globals_cryptokey" id="all_globals_cryptokey">#</a></span><a aria-hidden="true" class="legacy" id="globals_cryptokey"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>No longer behind <code>--experimental-global-webcrypto</code> CLI flag.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p><span>Added in: v17.6.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the
<a href="#all_cli_--no-experimental-global-webcrypto"><code>--no-experimental-global-webcrypto</code></a> CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>. This global is available
only if the Node.js binary was compiled with including support for the
<code>node:crypto</code> module.</p>
</section><section><h3><code>CustomEvent</code><span><a class="mark" href="#all_globals_customevent" id="all_globals_customevent">#</a></span><a aria-hidden="true" class="legacy" id="globals_customevent"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>No longer behind <code>--experimental-global-customevent</code> CLI flag.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p><span>Added in: v18.7.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the
<a href="#all_cli_--no-experimental-global-customevent"><code>--no-experimental-global-customevent</code></a> CLI flag.</div><p></p>
<p>A browser-compatible implementation of the <a href="https://dom.spec.whatwg.org/#customevent"><code>CustomEvent</code> Web API</a>.</p>
</section><section><h3>Class: <code>DecompressionStream</code><span><a class="mark" href="#all_globals_class-decompressionstream" id="all_globals_class-decompressionstream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_decompressionstream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-decompressionstream"><code>DecompressionStream</code></a>.</p>
</section><section><h3><code>Event</code><span><a class="mark" href="#all_globals_event" id="all_globals_event">#</a></span><a aria-hidden="true" class="legacy" id="globals_event"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.4.0</td>
<td><p>No longer experimental.</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>
<p>A browser-compatible implementation of the <code>Event</code> class. See
<a href="#all_events_eventtarget-and-event-api"><code>EventTarget</code> and <code>Event</code> API</a> for more details.</p>
</section><section><h3><code>EventSource</code><span><a class="mark" href="#all_globals_eventsource" id="all_globals_eventsource">#</a></span><a aria-hidden="true" class="legacy" id="globals_eventsource"></a></h3>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Enable this API with the <a href="#all_cli_--experimental-eventsource"><code>--experimental-eventsource</code></a>
CLI flag.</div><p></p>
<p>A browser-compatible implementation of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource"><code>EventSource</code></a> class.</p>
</section><section><h3><code>EventTarget</code><span><a class="mark" href="#all_globals_eventtarget" id="all_globals_eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="globals_eventtarget"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.4.0</td>
<td><p>No longer experimental.</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>
<p>A browser-compatible implementation of the <code>EventTarget</code> class. See
<a href="#all_events_eventtarget-and-event-api"><code>EventTarget</code> and <code>Event</code> API</a> for more details.</p>
</section><section><h3><code>exports</code><span><a class="mark" href="#all_globals_exports" id="all_globals_exports">#</a></span><a aria-hidden="true" class="legacy" id="globals_exports"></a></h3>
<p>This variable may appear to be global but is not. See <a href="#all_modules_exports"><code>exports</code></a>.</p>
</section><section><h3><code>fetch</code><span><a class="mark" href="#all_globals_fetch" id="all_globals_fetch">#</a></span><a aria-hidden="true" class="legacy" id="globals_fetch"></a></h3>
<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</td>
<td><p>No longer behind <code>--experimental-fetch</code> CLI flag.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p><span>Added in: v17.5.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the <a href="#all_cli_--no-experimental-fetch"><code>--no-experimental-fetch</code></a>
CLI flag.</div><p></p>
<p>A browser-compatible implementation of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/fetch"><code>fetch()</code></a> function.</p>
</section><section><h3>Class: <code>File</code><span><a class="mark" href="#all_globals_class-file" id="all_globals_class-file">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_file"></a></h3>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<p>See <a href="#all_buffer_class-file" class="type"><File></a>.</p>
</section><section><h3>Class <code>FormData</code><span><a class="mark" href="#all_globals_class-formdata" id="all_globals_class-formdata">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_formdata"></a></h3>
<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</td>
<td><p>No longer behind <code>--experimental-fetch</code> CLI flag.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p><span>Added in: v17.6.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the <a href="#all_cli_--no-experimental-fetch"><code>--no-experimental-fetch</code></a>
CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="https://developer.mozilla.org/en-US/docs/Web/API/FormData" class="type"><FormData></a>.</p>
</section><section><h3><code>global</code><span><a class="mark" href="#all_globals_global" id="all_globals_global">#</a></span><a aria-hidden="true" class="legacy" id="globals_global"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy. Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis"><code>globalThis</code></a> instead.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The global namespace object.</li>
</ul>
<p>In browsers, the top-level scope has traditionally been the global scope. This
means that <code>var something</code> will define a new global variable, except within
ECMAScript modules. In Node.js, this is different. The top-level scope is not
the global scope; <code>var something</code> inside a Node.js module will be local to that
module, regardless of whether it is a <a href="modules.html">CommonJS module</a> or an
<a href="esm.html">ECMAScript module</a>.</p>
</section><section><h3>Class <code>Headers</code><span><a class="mark" href="#all_globals_class-headers" id="all_globals_class-headers">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_headers"></a></h3>
<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</td>
<td><p>No longer behind <code>--experimental-fetch</code> CLI flag.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p><span>Added in: v17.5.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the <a href="#all_cli_--no-experimental-fetch"><code>--no-experimental-fetch</code></a>
CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="https://developer.mozilla.org/en-US/docs/Web/API/Headers" class="type"><Headers></a>.</p>
</section><section><h3><code>MessageChannel</code><span><a class="mark" href="#all_globals_messagechannel" id="all_globals_messagechannel">#</a></span><a aria-hidden="true" class="legacy" id="globals_messagechannel"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>The <code>MessageChannel</code> class. See <a href="#all_worker_threads_class-messagechannel"><code>MessageChannel</code></a> for more details.</p>
</section><section><h3><code>MessageEvent</code><span><a class="mark" href="#all_globals_messageevent" id="all_globals_messageevent">#</a></span><a aria-hidden="true" class="legacy" id="globals_messageevent"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>The <code>MessageEvent</code> class. See <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/MessageEvent"><code>MessageEvent</code></a> for more details.</p>
</section><section><h3><code>MessagePort</code><span><a class="mark" href="#all_globals_messageport" id="all_globals_messageport">#</a></span><a aria-hidden="true" class="legacy" id="globals_messageport"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>The <code>MessagePort</code> class. See <a href="#all_worker_threads_class-messageport"><code>MessagePort</code></a> for more details.</p>
</section><section><h3><code>module</code><span><a class="mark" href="#all_globals_module" id="all_globals_module">#</a></span><a aria-hidden="true" class="legacy" id="globals_module"></a></h3>
<p>This variable may appear to be global but is not. See <a href="#all_modules_module"><code>module</code></a>.</p>
</section><section><h3><code>PerformanceEntry</code><span><a class="mark" href="#all_globals_performanceentry" id="all_globals_performanceentry">#</a></span><a aria-hidden="true" class="legacy" id="globals_performanceentry"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<p>The <code>PerformanceEntry</code> class. See <a href="#all_perf_hooks_class-performanceentry"><code>PerformanceEntry</code></a> for more details.</p>
</section><section><h3><code>PerformanceMark</code><span><a class="mark" href="#all_globals_performancemark" id="all_globals_performancemark">#</a></span><a aria-hidden="true" class="legacy" id="globals_performancemark"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<p>The <code>PerformanceMark</code> class. See <a href="#all_perf_hooks_class-performancemark"><code>PerformanceMark</code></a> for more details.</p>
</section><section><h3><code>PerformanceMeasure</code><span><a class="mark" href="#all_globals_performancemeasure" id="all_globals_performancemeasure">#</a></span><a aria-hidden="true" class="legacy" id="globals_performancemeasure"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<p>The <code>PerformanceMeasure</code> class. See <a href="#all_perf_hooks_class-performancemeasure"><code>PerformanceMeasure</code></a> for more details.</p>
</section><section><h3><code>PerformanceObserver</code><span><a class="mark" href="#all_globals_performanceobserver" id="all_globals_performanceobserver">#</a></span><a aria-hidden="true" class="legacy" id="globals_performanceobserver"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<p>The <code>PerformanceObserver</code> class. See <a href="#all_perf_hooks_class-performanceobserver"><code>PerformanceObserver</code></a> for more details.</p>
</section><section><h3><code>PerformanceObserverEntryList</code><span><a class="mark" href="#all_globals_performanceobserverentrylist" id="all_globals_performanceobserverentrylist">#</a></span><a aria-hidden="true" class="legacy" id="globals_performanceobserverentrylist"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<p>The <code>PerformanceObserverEntryList</code> class. See
<a href="#all_perf_hooks_class-performanceobserverentrylist"><code>PerformanceObserverEntryList</code></a> for more details.</p>
</section><section><h3><code>PerformanceResourceTiming</code><span><a class="mark" href="#all_globals_performanceresourcetiming" id="all_globals_performanceresourcetiming">#</a></span><a aria-hidden="true" class="legacy" id="globals_performanceresourcetiming"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<p>The <code>PerformanceResourceTiming</code> class. See <a href="#all_perf_hooks_class-performanceresourcetiming"><code>PerformanceResourceTiming</code></a> for
more details.</p>
</section><section><h3><code>performance</code><span><a class="mark" href="#all_globals_performance" id="all_globals_performance">#</a></span><a aria-hidden="true" class="legacy" id="globals_performance"></a></h3>
<div class="api_metadata">
<span>Added in: v16.0.0</span>
</div>
<p>The <a href="#all_perf_hooks_perf_hooksperformance"><code>perf_hooks.performance</code></a> object.</p>
</section><section><h3><code>process</code><span><a class="mark" href="#all_globals_process" id="all_globals_process">#</a></span><a aria-hidden="true" class="legacy" id="globals_process"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.7</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The process object. See the <a href="#all_process_process"><code>process</code> object</a> section.</p>
</section><section><h3><code>queueMicrotask(callback)</code><span><a class="mark" href="#all_globals_queuemicrotaskcallback" id="all_globals_queuemicrotaskcallback">#</a></span><a aria-hidden="true" class="legacy" id="globals_queuemicrotask_callback"></a></h3>
<div class="api_metadata">
<span>Added in: v11.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> Function to be queued.</li>
</ul>
<p>The <code>queueMicrotask()</code> method queues a microtask to invoke <code>callback</code>. If
<code>callback</code> throws an exception, the <a href="#all_process_process"><code>process</code> object</a> <code>'uncaughtException'</code>
event will be emitted.</p>
<p>The microtask queue is managed by V8 and may be used in a similar manner to
the <a href="#all_process_processnexttickcallback-args"><code>process.nextTick()</code></a> queue, which is managed by Node.js. The
<code>process.nextTick()</code> queue is always processed before the microtask queue
within each turn of the Node.js event loop.</p>
<pre><code class="language-js"><span class="hljs-comment">// Here, `queueMicrotask()` is used to ensure the 'load' event is always</span>
<span class="hljs-comment">// emitted asynchronously, and therefore consistently. Using</span>
<span class="hljs-comment">// `process.nextTick()` here would result in the 'load' event always emitting</span>
<span class="hljs-comment">// before any other promise jobs.</span>
<span class="hljs-title class_">DataHandler</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">load</span> = <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">key</span>) {
<span class="hljs-keyword">const</span> hit = <span class="hljs-variable language_">this</span>.<span class="hljs-property">_cache</span>.<span class="hljs-title function_">get</span>(key);
<span class="hljs-keyword">if</span> (hit !== <span class="hljs-literal">undefined</span>) {
<span class="hljs-title function_">queueMicrotask</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'load'</span>, hit);
});
<span class="hljs-keyword">return</span>;
}
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetchData</span>(key);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">_cache</span>.<span class="hljs-title function_">set</span>(key, data);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'load'</span>, data);
};</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>ReadableByteStreamController</code><span><a class="mark" href="#all_globals_class-readablebytestreamcontroller" id="all_globals_class-readablebytestreamcontroller">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_readablebytestreamcontroller"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-readablebytestreamcontroller"><code>ReadableByteStreamController</code></a>.</p>
</section><section><h3>Class: <code>ReadableStream</code><span><a class="mark" href="#all_globals_class-readablestream" id="all_globals_class-readablestream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_readablestream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-readablestream"><code>ReadableStream</code></a>.</p>
</section><section><h3>Class: <code>ReadableStreamBYOBReader</code><span><a class="mark" href="#all_globals_class-readablestreambyobreader" id="all_globals_class-readablestreambyobreader">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_readablestreambyobreader"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-readablestreambyobreader"><code>ReadableStreamBYOBReader</code></a>.</p>
</section><section><h3>Class: <code>ReadableStreamBYOBRequest</code><span><a class="mark" href="#all_globals_class-readablestreambyobrequest" id="all_globals_class-readablestreambyobrequest">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_readablestreambyobrequest"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-readablestreambyobrequest"><code>ReadableStreamBYOBRequest</code></a>.</p>
</section><section><h3>Class: <code>ReadableStreamDefaultController</code><span><a class="mark" href="#all_globals_class-readablestreamdefaultcontroller" id="all_globals_class-readablestreamdefaultcontroller">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_readablestreamdefaultcontroller"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-readablestreamdefaultcontroller"><code>ReadableStreamDefaultController</code></a>.</p>
</section><section><h3>Class: <code>ReadableStreamDefaultReader</code><span><a class="mark" href="#all_globals_class-readablestreamdefaultreader" id="all_globals_class-readablestreamdefaultreader">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_readablestreamdefaultreader"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-readablestreamdefaultreader"><code>ReadableStreamDefaultReader</code></a>.</p>
</section><section><h3><code>require()</code><span><a class="mark" href="#all_globals_require" id="all_globals_require">#</a></span><a aria-hidden="true" class="legacy" id="globals_require"></a></h3>
<p>This variable may appear to be global but is not. See <a href="#all_modules_requireid"><code>require()</code></a>.</p>
</section><section><h3><code>Response</code><span><a class="mark" href="#all_globals_response" id="all_globals_response">#</a></span><a aria-hidden="true" class="legacy" id="globals_response"></a></h3>
<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</td>
<td><p>No longer behind <code>--experimental-fetch</code> CLI flag.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p><span>Added in: v17.5.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the <a href="#all_cli_--no-experimental-fetch"><code>--no-experimental-fetch</code></a>
CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="https://developer.mozilla.org/en-US/docs/Web/API/Response" class="type"><Response></a>.</p>
</section><section><h3><code>Request</code><span><a class="mark" href="#all_globals_request" id="all_globals_request">#</a></span><a aria-hidden="true" class="legacy" id="globals_request"></a></h3>
<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</td>
<td><p>No longer behind <code>--experimental-fetch</code> CLI flag.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p><span>Added in: v17.5.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the <a href="#all_cli_--no-experimental-fetch"><code>--no-experimental-fetch</code></a>
CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="https://developer.mozilla.org/en-US/docs/Web/API/Request" class="type"><Request></a>.</p>
</section><section><h3><code>setImmediate(callback[, ...args])</code><span><a class="mark" href="#all_globals_setimmediatecallback-args" id="all_globals_setimmediatecallback-args">#</a></span><a aria-hidden="true" class="legacy" id="globals_setimmediate_callback_args"></a></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<p><a href="#all_timers_setimmediatecallback-args"><code>setImmediate</code></a> is described in the <a href="timers.html">timers</a> section.</p>
</section><section><h3><code>setInterval(callback, delay[, ...args])</code><span><a class="mark" href="#all_globals_setintervalcallback-delay-args" id="all_globals_setintervalcallback-delay-args">#</a></span><a aria-hidden="true" class="legacy" id="globals_setinterval_callback_delay_args"></a></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>
<p><a href="#all_timers_setintervalcallback-delay-args"><code>setInterval</code></a> is described in the <a href="timers.html">timers</a> section.</p>
</section><section><h3><code>setTimeout(callback, delay[, ...args])</code><span><a class="mark" href="#all_globals_settimeoutcallback-delay-args" id="all_globals_settimeoutcallback-delay-args">#</a></span><a aria-hidden="true" class="legacy" id="globals_settimeout_callback_delay_args"></a></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>
<p><a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout</code></a> is described in the <a href="timers.html">timers</a> section.</p>
</section><section><h3><code>structuredClone(value[, options])</code><span><a class="mark" href="#all_globals_structuredclonevalue-options" id="all_globals_structuredclonevalue-options">#</a></span><a aria-hidden="true" class="legacy" id="globals_structuredclone_value_options"></a></h3>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p>The WHATWG <a href="https://developer.mozilla.org/en-US/docs/Web/API/structuredClone"><code>structuredClone</code></a> method.</p>
</section><section><h3><code>SubtleCrypto</code><span><a class="mark" href="#all_globals_subtlecrypto" id="all_globals_subtlecrypto">#</a></span><a aria-hidden="true" class="legacy" id="globals_subtlecrypto"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>No longer behind <code>--experimental-global-webcrypto</code> CLI flag.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p><span>Added in: v17.6.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the
<a href="#all_cli_--no-experimental-global-webcrypto"><code>--no-experimental-global-webcrypto</code></a> CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webcrypto_class-subtlecrypto" class="type"><SubtleCrypto></a>. This global is available
only if the Node.js binary was compiled with including support for the
<code>node:crypto</code> module.</p>
</section><section><h3><code>DOMException</code><span><a class="mark" href="#all_globals_domexception" id="all_globals_domexception">#</a></span><a aria-hidden="true" class="legacy" id="globals_domexception"></a></h3>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p>The WHATWG <code>DOMException</code> class. See <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMException"><code>DOMException</code></a> for more details.</p>
</section><section><h3><code>TextDecoder</code><span><a class="mark" href="#all_globals_textdecoder" id="all_globals_textdecoder">#</a></span><a aria-hidden="true" class="legacy" id="globals_textdecoder"></a></h3>
<div class="api_metadata">
<span>Added in: v11.0.0</span>
</div>
<p>The WHATWG <code>TextDecoder</code> class. See the <a href="#all_util_class-utiltextdecoder"><code>TextDecoder</code></a> section.</p>
</section><section><h3>Class: <code>TextDecoderStream</code><span><a class="mark" href="#all_globals_class-textdecoderstream" id="all_globals_class-textdecoderstream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_textdecoderstream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-textdecoderstream"><code>TextDecoderStream</code></a>.</p>
</section><section><h3><code>TextEncoder</code><span><a class="mark" href="#all_globals_textencoder" id="all_globals_textencoder">#</a></span><a aria-hidden="true" class="legacy" id="globals_textencoder"></a></h3>
<div class="api_metadata">
<span>Added in: v11.0.0</span>
</div>
<p>The WHATWG <code>TextEncoder</code> class. See the <a href="#all_util_class-utiltextencoder"><code>TextEncoder</code></a> section.</p>
</section><section><h3>Class: <code>TextEncoderStream</code><span><a class="mark" href="#all_globals_class-textencoderstream" id="all_globals_class-textencoderstream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_textencoderstream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-textencoderstream"><code>TextEncoderStream</code></a>.</p>
</section><section><h3>Class: <code>TransformStream</code><span><a class="mark" href="#all_globals_class-transformstream" id="all_globals_class-transformstream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_transformstream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-transformstream"><code>TransformStream</code></a>.</p>
</section><section><h3>Class: <code>TransformStreamDefaultController</code><span><a class="mark" href="#all_globals_class-transformstreamdefaultcontroller" id="all_globals_class-transformstreamdefaultcontroller">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_transformstreamdefaultcontroller"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-transformstreamdefaultcontroller"><code>TransformStreamDefaultController</code></a>.</p>
</section><section><h3><code>URL</code><span><a class="mark" href="#all_globals_url" id="all_globals_url">#</a></span><a aria-hidden="true" class="legacy" id="globals_url"></a></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>The WHATWG <code>URL</code> class. See the <a href="#all_url_class-url"><code>URL</code></a> section.</p>
</section><section><h3><code>URLSearchParams</code><span><a class="mark" href="#all_globals_urlsearchparams" id="all_globals_urlsearchparams">#</a></span><a aria-hidden="true" class="legacy" id="globals_urlsearchparams"></a></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>The WHATWG <code>URLSearchParams</code> class. See the <a href="#all_url_class-urlsearchparams"><code>URLSearchParams</code></a> section.</p>
</section><section><h3><code>WebAssembly</code><span><a class="mark" href="#all_globals_webassembly" id="all_globals_webassembly">#</a></span><a aria-hidden="true" class="legacy" id="globals_webassembly"></a></h3>
<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/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The object that acts as the namespace for all W3C
<a href="https://webassembly.org">WebAssembly</a> related functionality. See the
<a href="https://developer.mozilla.org/en-US/docs/WebAssembly">Mozilla Developer Network</a> for usage and compatibility.</p>
</section><section><h3><code>WebSocket</code><span><a class="mark" href="#all_globals_websocket" id="all_globals_websocket">#</a></span><a aria-hidden="true" class="legacy" id="globals_websocket"></a></h3>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket"><code>WebSocket</code></a>. Enable this API
with the <a href="#all_cli_--experimental-websocket"><code>--experimental-websocket</code></a> CLI flag.</p>
</section><section><h3>Class: <code>WritableStream</code><span><a class="mark" href="#all_globals_class-writablestream" id="all_globals_class-writablestream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_writablestream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-writablestream"><code>WritableStream</code></a>.</p>
</section><section><h3>Class: <code>WritableStreamDefaultController</code><span><a class="mark" href="#all_globals_class-writablestreamdefaultcontroller" id="all_globals_class-writablestreamdefaultcontroller">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_writablestreamdefaultcontroller"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-writablestreamdefaultcontroller"><code>WritableStreamDefaultController</code></a>.</p>
</section><section><h3>Class: <code>WritableStreamDefaultWriter</code><span><a class="mark" href="#all_globals_class-writablestreamdefaultwriter" id="all_globals_class-writablestreamdefaultwriter">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_writablestreamdefaultwriter"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-writablestreamdefaultwriter"><code>WritableStreamDefaultWriter</code></a>.</p></section>
</section>
<section><h2>HTTP<span><a class="mark" href="#all_http_http" id="all_http_http">#</a></span><a aria-hidden="true" class="legacy" id="http_http"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/http.js">lib/http.js</a></p>
<p>This module, containing both a client and server, can be imported via
<code>require('node:http')</code> (CommonJS) or <code>import * as http from 'node:http'</code> (ES module).</p>
<p>The HTTP interfaces in Node.js are designed to support many features
of the protocol which have been traditionally difficult to use.
In particular, large, possibly chunk-encoded, messages. The interface is
careful to never buffer entire requests or responses, so the
user is able to stream data.</p>
<p>HTTP message headers are represented by an object like this:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span> <span class="hljs-attr">"content-length"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"123"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"content-type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"text/plain"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"connection"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"keep-alive"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"host"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"example.com"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"accept"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"*/*"</span> <span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Keys are lowercased. Values are not modified.</p>
<p>In order to support the full spectrum of possible HTTP applications, the Node.js
HTTP API is very low-level. It deals with stream handling and message
parsing only. It parses a message into headers and body but it does not
parse the actual headers or the body.</p>
<p>See <a href="#all_http_messageheaders"><code>message.headers</code></a> for details on how duplicate headers are handled.</p>
<p>The raw headers as they were received are retained in the <code>rawHeaders</code>
property, which is an array of <code>[key, value, key2, value2, ...]</code>. For
example, the previous message header object might have a <code>rawHeaders</code>
list like the following:</p>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js">[ <span class="hljs-string">'ConTent-Length'</span>, <span class="hljs-string">'123456'</span>,
<span class="hljs-string">'content-LENGTH'</span>, <span class="hljs-string">'123'</span>,
<span class="hljs-string">'content-type'</span>, <span class="hljs-string">'text/plain'</span>,
<span class="hljs-string">'CONNECTION'</span>, <span class="hljs-string">'keep-alive'</span>,
<span class="hljs-string">'Host'</span>, <span class="hljs-string">'example.com'</span>,
<span class="hljs-string">'accepT'</span>, <span class="hljs-string">'*/*'</span> ]</code> <button class="copy-button">copy</button></pre>
<section><h3>Class: <code>http.Agent</code><span><a class="mark" href="#all_http_class-httpagent" id="all_http_class-httpagent">#</a></span><a aria-hidden="true" class="legacy" id="http_class_http_agent"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<p>An <code>Agent</code> is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the
<code>keepAlive</code> <a href="#all_http_new-agentoptions">option</a>.</p>
<p>Pooled connections have TCP Keep-Alive enabled for them, but servers may
still close idle connections, in which case they will be removed from the
pool and a new connection will be made when a new HTTP request is made for
that host and port. Servers may also refuse to allow multiple requests
over the same connection, in which case the connection will have to be
remade for every request and cannot be pooled. The <code>Agent</code> will still make
the requests to that server, but each one will occur over a new connection.</p>
<p>When a connection is closed by the client or the server, it is removed
from the pool. Any unused sockets in the pool will be unrefed so as not
to keep the Node.js process running when there are no outstanding requests.
(see <a href="#all_net_socketunref"><code>socket.unref()</code></a>).</p>
<p>It is good practice, to <a href="#all_http_agentdestroy"><code>destroy()</code></a> an <code>Agent</code> instance when it is no
longer in use, because unused sockets consume OS resources.</p>
<p>Sockets are removed from an agent when the socket emits either
a <code>'close'</code> event or an <code>'agentRemove'</code> event. When intending to keep one
HTTP request open for a long time without keeping it in the agent, something
like the following may be done:</p>
<pre><code class="language-js">http.<span class="hljs-title function_">get</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-comment">// Do stuff</span>
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'socket'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
socket.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'agentRemove'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>An agent may also be used for an individual request. By providing
<code>{agent: false}</code> as an option to the <code>http.get()</code> or <code>http.request()</code>
functions, a one-time use <code>Agent</code> with default options will be used
for the client connection.</p>
<p><code>agent:false</code>:</p>
<pre><code class="language-js">http.<span class="hljs-title function_">get</span>({
<span class="hljs-attr">hostname</span>: <span class="hljs-string">'localhost'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
<span class="hljs-attr">agent</span>: <span class="hljs-literal">false</span>, <span class="hljs-comment">// Create a new agent just for this one request</span>
}, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-comment">// Do stuff with response</span>
});</code> <button class="copy-button">copy</button></pre>
<h4><code>new Agent([options])</code><span><a class="mark" href="#all_http_new-agentoptions" id="all_http_new-agentoptions">#</a></span><a aria-hidden="true" class="legacy" id="http_new_agent_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>v15.6.0, v14.17.0</td>
<td><p>Change the default scheduling from 'fifo' to 'lifo'.</p></td></tr>
<tr><td>v14.5.0, v12.20.0</td>
<td><p>Add <code>scheduling</code> option to specify the free socket scheduling strategy.</p></td></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Add <code>maxTotalSockets</code> option to agent constructor.</p></td></tr>
<tr><td>v0.3.4</td>
<td><p><span>Added in: v0.3.4</span></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> Set of configurable options to set on the agent.
Can have the following fields:
<ul>
<li><code>keepAlive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Keep sockets around even when there are no
outstanding requests, so they can be used for future requests without
having to reestablish a TCP connection. Not to be confused with the
<code>keep-alive</code> value of the <code>Connection</code> header. The <code>Connection: keep-alive</code>
header is always sent when using an agent except when the <code>Connection</code>
header is explicitly specified or when the <code>keepAlive</code> and <code>maxSockets</code>
options are respectively set to <code>false</code> and <code>Infinity</code>, in which case
<code>Connection: close</code> will be used. <strong>Default:</strong> <code>false</code>.</li>
<li><code>keepAliveMsecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> When using the <code>keepAlive</code> option, specifies
the <a href="#all_net_socketsetkeepaliveenable-initialdelay">initial delay</a>
for TCP Keep-Alive packets. Ignored when the
<code>keepAlive</code> option is <code>false</code> or <code>undefined</code>. <strong>Default:</strong> <code>1000</code>.</li>
<li><code>maxSockets</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Maximum number of sockets to allow per host.
If the same host opens multiple concurrent connections, each request
will use new socket until the <code>maxSockets</code> value is reached.
If the host attempts to open more connections than <code>maxSockets</code>,
the additional requests will enter into a pending request queue, and
will enter active connection state when an existing connection terminates.
This makes sure there are at most <code>maxSockets</code> active connections at
any point in time, from a given host.
<strong>Default:</strong> <code>Infinity</code>.</li>
<li><code>maxTotalSockets</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Maximum number of sockets allowed for
all hosts in total. Each request will use a new socket
until the maximum is reached.
<strong>Default:</strong> <code>Infinity</code>.</li>
<li><code>maxFreeSockets</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Maximum number of sockets per host to leave open
in a free state. Only relevant if <code>keepAlive</code> is set to <code>true</code>.
<strong>Default:</strong> <code>256</code>.</li>
<li><code>scheduling</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Scheduling strategy to apply when picking
the next free socket to use. It can be <code>'fifo'</code> or <code>'lifo'</code>.
The main difference between the two scheduling strategies is that <code>'lifo'</code>
selects the most recently used socket, while <code>'fifo'</code> selects
the least recently used socket.
In case of a low rate of request per second, the <code>'lifo'</code> scheduling
will lower the risk of picking a socket that might have been closed
by the server due to inactivity.
In case of a high rate of request per second,
the <code>'fifo'</code> scheduling will maximize the number of open sockets,
while the <code>'lifo'</code> scheduling will keep it as low as possible.
<strong>Default:</strong> <code>'lifo'</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Socket timeout in milliseconds.
This will set the timeout when the socket is created.</li>
</ul>
</li>
</ul>
<p><code>options</code> in <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect()</code></a> are also supported.</p>
<p>To configure any of them, a custom <a href="#all_http_class-httpagent"><code>http.Agent</code></a> instance must be created.</p>
<pre class="with-59-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_">Agent</span>, request } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">const</span> keepAliveAgent = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Agent</span>({ <span class="hljs-attr">keepAlive</span>: <span class="hljs-literal">true</span> });
options.<span class="hljs-property">agent</span> = keepAliveAgent;
<span class="hljs-title function_">request</span>(options, onResponseCallback);</code><code class="language-js cjs"><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> keepAliveAgent = <span class="hljs-keyword">new</span> http.<span class="hljs-title class_">Agent</span>({ <span class="hljs-attr">keepAlive</span>: <span class="hljs-literal">true</span> });
options.<span class="hljs-property">agent</span> = keepAliveAgent;
http.<span class="hljs-title function_">request</span>(options, onResponseCallback);</code><button class="copy-button">copy</button></pre>
<h4><code>agent.createConnection(options[, callback])</code><span><a class="mark" href="#all_http_agentcreateconnectionoptions-callback" id="all_http_agentcreateconnectionoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_createconnection_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</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> Options containing connection details. Check
<a href="#all_net_netcreateconnectionoptions-connectlistener"><code>net.createConnection()</code></a> for the format of the options</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 function that receives the created socket</li>
<li>Returns: <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>Produces a socket/stream to be used for HTTP requests.</p>
<p>By default, this function is the same as <a href="#all_net_netcreateconnectionoptions-connectlistener"><code>net.createConnection()</code></a>. However,
custom agents may override this method in case greater flexibility is desired.</p>
<p>A socket/stream can be supplied in one of two ways: by returning the
socket/stream from this function, or by passing the socket/stream to <code>callback</code>.</p>
<p>This method is guaranteed to return an instance of the <a href="#all_net_class-netsocket" class="type"><net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type"><net.Socket></a>.</p>
<p><code>callback</code> has a signature of <code>(err, stream)</code>.</p>
<h4><code>agent.keepSocketAlive(socket)</code><span><a class="mark" href="#all_http_agentkeepsocketalivesocket" id="all_http_agentkeepsocketalivesocket">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_keepsocketalive_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>Called when <code>socket</code> is detached from a request and could be persisted by the
<code>Agent</code>. Default behavior is to:</p>
<pre><code class="language-js">socket.<span class="hljs-title function_">setKeepAlive</span>(<span class="hljs-literal">true</span>, <span class="hljs-variable language_">this</span>.<span class="hljs-property">keepAliveMsecs</span>);
socket.<span class="hljs-title function_">unref</span>();
<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;</code> <button class="copy-button">copy</button></pre>
<p>This method can be overridden by a particular <code>Agent</code> subclass. If this
method returns a falsy value, the socket will be destroyed instead of persisting
it for use with the next request.</p>
<p>The <code>socket</code> argument can be an instance of <a href="#all_net_class-netsocket" class="type"><net.Socket></a>, a subclass of
<a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>.</p>
<h4><code>agent.reuseSocket(socket, request)</code><span><a class="mark" href="#all_http_agentreusesocketsocket-request" id="all_http_agentreusesocketsocket-request">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_reusesocket_socket_request"></a></h4>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
<li><code>request</code> <a href="#all_http_class-httpclientrequest" class="type"><http.ClientRequest></a></li>
</ul>
<p>Called when <code>socket</code> is attached to <code>request</code> after being persisted because of
the keep-alive options. Default behavior is to:</p>
<pre><code class="language-js">socket.<span class="hljs-title function_">ref</span>();</code> <button class="copy-button">copy</button></pre>
<p>This method can be overridden by a particular <code>Agent</code> subclass.</p>
<p>The <code>socket</code> argument can be an instance of <a href="#all_net_class-netsocket" class="type"><net.Socket></a>, a subclass of
<a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>.</p>
<h4><code>agent.destroy()</code><span><a class="mark" href="#all_http_agentdestroy" id="all_http_agentdestroy">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_destroy"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<p>Destroy any sockets that are currently in use by the agent.</p>
<p>It is usually not necessary to do this. However, if using an
agent with <code>keepAlive</code> enabled, then it is best to explicitly shut down
the agent when it is no longer needed. Otherwise,
sockets might stay open for quite a long time before the server
terminates them.</p>
<h4><code>agent.freeSockets</code><span><a class="mark" href="#all_http_agentfreesockets" id="all_http_agentfreesockets">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_freesockets"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>The property now has a <code>null</code> prototype.</p></td></tr>
<tr><td>v0.11.4</td>
<td><p><span>Added in: v0.11.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>An object which contains arrays of sockets currently awaiting use by
the agent when <code>keepAlive</code> is enabled. Do not modify.</p>
<p>Sockets in the <code>freeSockets</code> list will be automatically destroyed and
removed from the array on <code>'timeout'</code>.</p>
<h4><code>agent.getName([options])</code><span><a class="mark" href="#all_http_agentgetnameoptions" id="all_http_agentgetnameoptions">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_getname_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>v17.7.0, v16.15.0</td>
<td><p>The <code>options</code> parameter is now optional.</p></td></tr>
<tr><td>v0.11.4</td>
<td><p><span>Added in: v0.11.4</span></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> A set of options providing information for name generation
<ul>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A domain name or IP address of the server to issue the
request to</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port of remote server</li>
<li><code>localAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Local interface to bind for network connections
when issuing the request</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Must be 4 or 6 if this doesn't equal <code>undefined</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Get a unique name for a set of request options, to determine whether a
connection can be reused. For an HTTP agent, this returns
<code>host:port:localAddress</code> or <code>host:port:localAddress:family</code>. For an HTTPS agent,
the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options
that determine socket reusability.</p>
<h4><code>agent.maxFreeSockets</code><span><a class="mark" href="#all_http_agentmaxfreesockets" id="all_http_agentmaxfreesockets">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_maxfreesockets"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.7</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>By default set to 256. For agents with <code>keepAlive</code> enabled, this
sets the maximum number of sockets that will be left open in the free
state.</p>
<h4><code>agent.maxSockets</code><span><a class="mark" href="#all_http_agentmaxsockets" id="all_http_agentmaxsockets">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_maxsockets"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.6</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>By default set to <code>Infinity</code>. Determines how many concurrent sockets the agent
can have open per origin. Origin is the returned value of <a href="#all_http_agentgetnameoptions"><code>agent.getName()</code></a>.</p>
<h4><code>agent.maxTotalSockets</code><span><a class="mark" href="#all_http_agentmaxtotalsockets" id="all_http_agentmaxtotalsockets">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_maxtotalsockets"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.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>By default set to <code>Infinity</code>. Determines how many concurrent sockets the agent
can have open. Unlike <code>maxSockets</code>, this parameter applies across all origins.</p>
<h4><code>agent.requests</code><span><a class="mark" href="#all_http_agentrequests" id="all_http_agentrequests">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_requests"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>The property now has a <code>null</code> prototype.</p></td></tr>
<tr><td>v0.5.9</td>
<td><p><span>Added in: v0.5.9</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>An object which contains queues of requests that have not yet been assigned to
sockets. Do not modify.</p>
<h4><code>agent.sockets</code><span><a class="mark" href="#all_http_agentsockets" id="all_http_agentsockets">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_sockets"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>The property now has a <code>null</code> prototype.</p></td></tr>
<tr><td>v0.3.6</td>
<td><p><span>Added in: v0.3.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>An object which contains arrays of sockets currently in use by the
agent. Do not modify.</p>
</section><section><h3>Class: <code>http.ClientRequest</code><span><a class="mark" href="#all_http_class-httpclientrequest" id="all_http_class-httpclientrequest">#</a></span><a aria-hidden="true" class="legacy" id="http_class_http_clientrequest"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<ul>
<li>Extends: <a href="#all_http_class-httpoutgoingmessage" class="type"><http.OutgoingMessage></a></li>
</ul>
<p>This object is created internally and returned from <a href="#all_http_httprequestoptions-callback"><code>http.request()</code></a>. It
represents an <em>in-progress</em> request whose header has already been queued. The
header is still mutable using the <a href="#all_http_requestsetheadername-value"><code>setHeader(name, value)</code></a>,
<a href="#all_http_requestgetheadername"><code>getHeader(name)</code></a>, <a href="#all_http_requestremoveheadername"><code>removeHeader(name)</code></a> API. The actual header will
be sent along with the first data chunk or when calling <a href="#all_http_requestenddata-encoding-callback"><code>request.end()</code></a>.</p>
<p>To get the response, add a listener for <a href="#all_http_event-response"><code>'response'</code></a> to the request object.
<a href="#all_http_event-response"><code>'response'</code></a> will be emitted from the request object when the response
headers have been received. The <a href="#all_http_event-response"><code>'response'</code></a> event is executed with one
argument which is an instance of <a href="#all_http_class-httpincomingmessage"><code>http.IncomingMessage</code></a>.</p>
<p>During the <a href="#all_http_event-response"><code>'response'</code></a> event, one can add listeners to the
response object; particularly to listen for the <code>'data'</code> event.</p>
<p>If no <a href="#all_http_event-response"><code>'response'</code></a> handler is added, then the response will be
entirely discarded. However, if a <a href="#all_http_event-response"><code>'response'</code></a> event handler is added,
then the data from the response object <strong>must</strong> be consumed, either by
calling <code>response.read()</code> whenever there is a <code>'readable'</code> event, or
by adding a <code>'data'</code> handler, or by calling the <code>.resume()</code> method.
Until the data is consumed, the <code>'end'</code> event will not fire. Also, until
the data is read it will consume memory that can eventually lead to a
'process out of memory' error.</p>
<p>For backward compatibility, <code>res</code> will only emit <code>'error'</code> if there is an
<code>'error'</code> listener registered.</p>
<p>Set <code>Content-Length</code> header to limit the response body size.
If <a href="#all_http_responsestrictcontentlength"><code>response.strictContentLength</code></a> is set to <code>true</code>, mismatching the
<code>Content-Length</code> header value will result in an <code>Error</code> being thrown,
identified by <code>code:</code> <a href="#all_errors_err_http_content_length_mismatch"><code>'ERR_HTTP_CONTENT_LENGTH_MISMATCH'</code></a>.</p>
<p><code>Content-Length</code> value should be in bytes, not characters. Use
<a href="#all_buffer_static-method-bufferbytelengthstring-encoding"><code>Buffer.byteLength()</code></a> to determine the length of the body in bytes.</p>
<h4>Event: <code>'abort'</code><span><a class="mark" href="#all_http_event-abort" id="all_http_event-abort">#</a></span><a aria-hidden="true" class="legacy" id="http_event_abort"></a></h4>
<div class="api_metadata">
<span>Added in: v1.4.1</span><span>Deprecated since: v17.0.0, v16.12.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Listen for the <code>'close'</code> event instead.</div><p></p>
<p>Emitted when the request has been aborted by the client. This event is only
emitted on the first call to <code>abort()</code>.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_http_event-close" id="all_http_event-close">#</a></span><a aria-hidden="true" class="legacy" id="http_event_close"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.4</span>
</div>
<p>Indicates that the request is completed, or its underlying connection was
terminated prematurely (before the response completion).</p>
<h4>Event: <code>'connect'</code><span><a class="mark" href="#all_http_event-connect" id="all_http_event-connect">#</a></span><a aria-hidden="true" class="legacy" id="http_event_connect"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>response</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a></li>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
<li><code>head</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Emitted each time a server responds to a request with a <code>CONNECT</code> method. If
this event is not being listened for, clients receiving a <code>CONNECT</code> method will
have their connections closed.</p>
<p>This event is guaranteed to be passed an instance of the <a href="#all_net_class-netsocket" class="type"><net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type"><net.Socket></a>.</p>
<p>A client and server pair demonstrating how to listen for the <code>'connect'</code> event:</p>
<pre class="with-50-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> { createServer, request } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-variable constant_">URL</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-comment">// Create an HTTP tunneling proxy</span>
<span class="hljs-keyword">const</span> proxy = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'okay'</span>);
});
proxy.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connect'</span>, <span class="hljs-function">(<span class="hljs-params">req, clientSocket, head</span>) =></span> {
<span class="hljs-comment">// Connect to an origin server</span>
<span class="hljs-keyword">const</span> { port, hostname } = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`http://<span class="hljs-subst">${req.url}</span>`</span>);
<span class="hljs-keyword">const</span> serverSocket = <span class="hljs-title function_">connect</span>(port || <span class="hljs-number">80</span>, hostname, <span class="hljs-function">() =></span> {
clientSocket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'HTTP/1.1 200 Connection Established\r\n'</span> +
<span class="hljs-string">'Proxy-agent: Node.js-Proxy\r\n'</span> +
<span class="hljs-string">'\r\n'</span>);
serverSocket.<span class="hljs-title function_">write</span>(head);
serverSocket.<span class="hljs-title function_">pipe</span>(clientSocket);
clientSocket.<span class="hljs-title function_">pipe</span>(serverSocket);
});
});
<span class="hljs-comment">// Now that proxy is running</span>
proxy.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Make a request to a tunneling proxy</span>
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">port</span>: <span class="hljs-number">1337</span>,
<span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
<span class="hljs-attr">method</span>: <span class="hljs-string">'CONNECT'</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'www.google.com:80'</span>,
};
<span class="hljs-keyword">const</span> req = <span class="hljs-title function_">request</span>(options);
req.<span class="hljs-title function_">end</span>();
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connect'</span>, <span class="hljs-function">(<span class="hljs-params">res, socket, head</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'got connected!'</span>);
<span class="hljs-comment">// Make a request over an HTTP tunnel</span>
socket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'GET / HTTP/1.1\r\n'</span> +
<span class="hljs-string">'Host: www.google.com:80\r\n'</span> +
<span class="hljs-string">'Connection: close\r\n'</span> +
<span class="hljs-string">'\r\n'</span>);
socket.<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>());
});
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
proxy.<span class="hljs-title function_">close</span>();
});
});
});</code><code class="language-js cjs"><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> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-variable constant_">URL</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-comment">// Create an HTTP tunneling proxy</span>
<span class="hljs-keyword">const</span> proxy = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'okay'</span>);
});
proxy.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connect'</span>, <span class="hljs-function">(<span class="hljs-params">req, clientSocket, head</span>) =></span> {
<span class="hljs-comment">// Connect to an origin server</span>
<span class="hljs-keyword">const</span> { port, hostname } = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`http://<span class="hljs-subst">${req.url}</span>`</span>);
<span class="hljs-keyword">const</span> serverSocket = net.<span class="hljs-title function_">connect</span>(port || <span class="hljs-number">80</span>, hostname, <span class="hljs-function">() =></span> {
clientSocket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'HTTP/1.1 200 Connection Established\r\n'</span> +
<span class="hljs-string">'Proxy-agent: Node.js-Proxy\r\n'</span> +
<span class="hljs-string">'\r\n'</span>);
serverSocket.<span class="hljs-title function_">write</span>(head);
serverSocket.<span class="hljs-title function_">pipe</span>(clientSocket);
clientSocket.<span class="hljs-title function_">pipe</span>(serverSocket);
});
});
<span class="hljs-comment">// Now that proxy is running</span>
proxy.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Make a request to a tunneling proxy</span>
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">port</span>: <span class="hljs-number">1337</span>,
<span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
<span class="hljs-attr">method</span>: <span class="hljs-string">'CONNECT'</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'www.google.com:80'</span>,
};
<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options);
req.<span class="hljs-title function_">end</span>();
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connect'</span>, <span class="hljs-function">(<span class="hljs-params">res, socket, head</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'got connected!'</span>);
<span class="hljs-comment">// Make a request over an HTTP tunnel</span>
socket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'GET / HTTP/1.1\r\n'</span> +
<span class="hljs-string">'Host: www.google.com:80\r\n'</span> +
<span class="hljs-string">'Connection: close\r\n'</span> +
<span class="hljs-string">'\r\n'</span>);
socket.<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>());
});
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
proxy.<span class="hljs-title function_">close</span>();
});
});
});</code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'continue'</code><span><a class="mark" href="#all_http_event-continue" id="all_http_event-continue">#</a></span><a aria-hidden="true" class="legacy" id="http_event_continue"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div>
<p>Emitted when the server sends a '100 Continue' HTTP response, usually because
the request contained 'Expect: 100-continue'. This is an instruction that
the client should send the request body.</p>
<h4>Event: <code>'finish'</code><span><a class="mark" href="#all_http_event-finish" id="all_http_event-finish">#</a></span><a aria-hidden="true" class="legacy" id="http_event_finish"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div>
<p>Emitted when the request has been sent. More specifically, this event is emitted
when the last segment of the response headers and body have been handed off to
the operating system for transmission over the network. It does not imply that
the server has received anything yet.</p>
<h4>Event: <code>'information'</code><span><a class="mark" href="#all_http_event-information" id="all_http_event-information">#</a></span><a aria-hidden="true" class="legacy" id="http_event_information"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>info</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>httpVersion</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>httpVersionMajor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>httpVersionMinor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>statusMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>rawHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
</li>
</ul>
<p>Emitted when the server sends a 1xx intermediate response (excluding 101
Upgrade). The listeners of this event will receive an object containing the
HTTP version, status code, status message, key-value headers object,
and array with the raw header names followed by their respective values.</p>
<pre class="with-36-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> { request } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">8080</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/length_request'</span>,
};
<span class="hljs-comment">// Make a request</span>
<span class="hljs-keyword">const</span> req = <span class="hljs-title function_">request</span>(options);
req.<span class="hljs-title function_">end</span>();
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'information'</span>, <span class="hljs-function">(<span class="hljs-params">info</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Got information prior to main response: <span class="hljs-subst">${info.statusCode}</span>`</span>);
});</code><code class="language-js cjs"><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> options = {
<span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">8080</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/length_request'</span>,
};
<span class="hljs-comment">// Make a request</span>
<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options);
req.<span class="hljs-title function_">end</span>();
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'information'</span>, <span class="hljs-function">(<span class="hljs-params">info</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Got information prior to main response: <span class="hljs-subst">${info.statusCode}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<p>101 Upgrade statuses do not fire this event due to their break from the
traditional HTTP request/response chain, such as web sockets, in-place TLS
upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the
<a href="#all_http_event-upgrade"><code>'upgrade'</code></a> event instead.</p>
<h4>Event: <code>'response'</code><span><a class="mark" href="#all_http_event-response" id="all_http_event-response">#</a></span><a aria-hidden="true" class="legacy" id="http_event_response"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.0</span>
</div>
<ul>
<li><code>response</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a></li>
</ul>
<p>Emitted when a response is received to this request. This event is emitted only
once.</p>
<h4>Event: <code>'socket'</code><span><a class="mark" href="#all_http_event-socket" id="all_http_event-socket">#</a></span><a aria-hidden="true" class="legacy" id="http_event_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.3</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>This event is guaranteed to be passed an instance of the <a href="#all_net_class-netsocket" class="type"><net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type"><net.Socket></a>.</p>
<h4>Event: <code>'timeout'</code><span><a class="mark" href="#all_http_event-timeout" id="all_http_event-timeout">#</a></span><a aria-hidden="true" class="legacy" id="http_event_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.8</span>
</div>
<p>Emitted when the underlying socket times out from inactivity. This only notifies
that the socket has been idle. The request must be destroyed manually.</p>
<p>See also: <a href="#all_http_requestsettimeouttimeout-callback"><code>request.setTimeout()</code></a>.</p>
<h4>Event: <code>'upgrade'</code><span><a class="mark" href="#all_http_event-upgrade" id="all_http_event-upgrade">#</a></span><a aria-hidden="true" class="legacy" id="http_event_upgrade"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div>
<ul>
<li><code>response</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a></li>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
<li><code>head</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Emitted each time a server responds to a request with an upgrade. If this
event is not being listened for and the response status code is 101 Switching
Protocols, clients receiving an upgrade header will have their connections
closed.</p>
<p>This event is guaranteed to be passed an instance of the <a href="#all_net_class-netsocket" class="type"><net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type"><net.Socket></a>.</p>
<p>A client server pair demonstrating how to listen for the <code>'upgrade'</code> event.</p>
<pre class="with-35-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> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-comment">// Create an HTTP server</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> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'okay'</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'upgrade'</span>, <span class="hljs-function">(<span class="hljs-params">req, socket, head</span>) =></span> {
socket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'HTTP/1.1 101 Web Socket Protocol Handshake\r\n'</span> +
<span class="hljs-string">'Upgrade: WebSocket\r\n'</span> +
<span class="hljs-string">'Connection: Upgrade\r\n'</span> +
<span class="hljs-string">'\r\n'</span>);
socket.<span class="hljs-title function_">pipe</span>(socket); <span class="hljs-comment">// echo back</span>
});
<span class="hljs-comment">// Now that server is running</span>
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// make a request</span>
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">port</span>: <span class="hljs-number">1337</span>,
<span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
<span class="hljs-attr">headers</span>: {
<span class="hljs-string">'Connection'</span>: <span class="hljs-string">'Upgrade'</span>,
<span class="hljs-string">'Upgrade'</span>: <span class="hljs-string">'websocket'</span>,
},
};
<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options);
req.<span class="hljs-title function_">end</span>();
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'upgrade'</span>, <span class="hljs-function">(<span class="hljs-params">res, socket, upgradeHead</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'got upgraded!'</span>);
socket.<span class="hljs-title function_">end</span>();
process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">0</span>);
});
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-comment">// Create an HTTP server</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> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'okay'</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'upgrade'</span>, <span class="hljs-function">(<span class="hljs-params">req, socket, head</span>) =></span> {
socket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'HTTP/1.1 101 Web Socket Protocol Handshake\r\n'</span> +
<span class="hljs-string">'Upgrade: WebSocket\r\n'</span> +
<span class="hljs-string">'Connection: Upgrade\r\n'</span> +
<span class="hljs-string">'\r\n'</span>);
socket.<span class="hljs-title function_">pipe</span>(socket); <span class="hljs-comment">// echo back</span>
});
<span class="hljs-comment">// Now that server is running</span>
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// make a request</span>
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">port</span>: <span class="hljs-number">1337</span>,
<span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
<span class="hljs-attr">headers</span>: {
<span class="hljs-string">'Connection'</span>: <span class="hljs-string">'Upgrade'</span>,
<span class="hljs-string">'Upgrade'</span>: <span class="hljs-string">'websocket'</span>,
},
};
<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options);
req.<span class="hljs-title function_">end</span>();
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'upgrade'</span>, <span class="hljs-function">(<span class="hljs-params">res, socket, upgradeHead</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'got upgraded!'</span>);
socket.<span class="hljs-title function_">end</span>();
process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">0</span>);
});
});</code><button class="copy-button">copy</button></pre>
<h4><code>request.abort()</code><span><a class="mark" href="#all_http_requestabort" id="all_http_requestabort">#</a></span><a aria-hidden="true" class="legacy" id="http_request_abort"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.8</span><span>Deprecated since: v14.1.0, v13.14.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_http_requestdestroyerror"><code>request.destroy()</code></a> instead.</div><p></p>
<p>Marks the request as aborting. Calling this will cause remaining data
in the response to be dropped and the socket to be destroyed.</p>
<h4><code>request.aborted</code><span><a class="mark" href="#all_http_requestaborted" id="all_http_requestaborted">#</a></span><a aria-hidden="true" class="legacy" id="http_request_aborted"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p><span>Deprecated since: v17.0.0, v16.12.0</span></p></td></tr>
<tr><td>v11.0.0</td>
<td><p>The <code>aborted</code> property is no longer a timestamp number.</p></td></tr>
<tr><td>v0.11.14</td>
<td><p><span>Added in: v0.11.14</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Check <a href="#all_http_requestdestroyed"><code>request.destroyed</code></a> instead.</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>The <code>request.aborted</code> property will be <code>true</code> if the request has
been aborted.</p>
<h4><code>request.connection</code><span><a class="mark" href="#all_http_requestconnection" id="all_http_requestconnection">#</a></span><a aria-hidden="true" class="legacy" id="http_request_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span><span>Deprecated since: v13.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http_requestsocket"><code>request.socket</code></a>.</div><p></p>
<ul>
<li><a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>See <a href="#all_http_requestsocket"><code>request.socket</code></a>.</p>
<h4><code>request.cork()</code><span><a class="mark" href="#all_http_requestcork" id="all_http_requestcork">#</a></span><a aria-hidden="true" class="legacy" id="http_request_cork"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>See <a href="#all_stream_writablecork"><code>writable.cork()</code></a>.</p>
<h4><code>request.end([data[, encoding]][, callback])</code><span><a class="mark" href="#all_http_requestenddata-encoding-callback" id="all_http_requestenddata-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_request_end_data_encoding_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>v15.0.0</td>
<td><p>The <code>data</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>This method now returns a reference to <code>ClientRequest</code>.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></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>Finishes sending the request. If any parts of the body are
unsent, it will flush them to the stream. If the request is
chunked, this will send the terminating <code>'0\r\n\r\n'</code>.</p>
<p>If <code>data</code> is specified, it is equivalent to calling
<a href="#all_http_requestwritechunk-encoding-callback"><code>request.write(data, encoding)</code></a> followed by <code>request.end(callback)</code>.</p>
<p>If <code>callback</code> is specified, it will be called when the request stream
is finished.</p>
<h4><code>request.destroy([error])</code><span><a class="mark" href="#all_http_requestdestroyerror" id="all_http_requestdestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="http_request_destroy_error"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0</td>
<td><p>The function returns <code>this</code> for consistency with other Readable streams.</p></td></tr>
<tr><td>v0.3.0</td>
<td><p><span>Added in: v0.3.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 request. Optionally emit an <code>'error'</code> event,
and emit a <code>'close'</code> event. Calling this will cause remaining data
in the response to be dropped and the socket to be destroyed.</p>
<p>See <a href="#all_stream_writabledestroyerror"><code>writable.destroy()</code></a> for further details.</p>
<h5><code>request.destroyed</code><span><a class="mark" href="#all_http_requestdestroyed" id="all_http_requestdestroyed">#</a></span><a aria-hidden="true" class="legacy" id="http_request_destroyed"></a></h5>
<div class="api_metadata">
<span>Added in: v14.1.0, v13.14.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="#all_http_requestdestroyerror"><code>request.destroy()</code></a> has been called.</p>
<p>See <a href="#all_stream_writabledestroyed"><code>writable.destroyed</code></a> for further details.</p>
<h4><code>request.finished</code><span><a class="mark" href="#all_http_requestfinished" id="all_http_requestfinished">#</a></span><a aria-hidden="true" class="legacy" id="http_request_finished"></a></h4>
<div class="api_metadata">
<span>Added in: v0.0.1</span><span>Deprecated since: v13.4.0, v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http_requestwritableended"><code>request.writableEnded</code></a>.</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>The <code>request.finished</code> property will be <code>true</code> if <a href="#all_http_requestenddata-encoding-callback"><code>request.end()</code></a>
has been called. <code>request.end()</code> will automatically be called if the
request was initiated via <a href="#all_http_httpgetoptions-callback"><code>http.get()</code></a>.</p>
<h4><code>request.flushHeaders()</code><span><a class="mark" href="#all_http_requestflushheaders" id="all_http_requestflushheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_request_flushheaders"></a></h4>
<div class="api_metadata">
<span>Added in: v1.6.0</span>
</div>
<p>Flushes the request headers.</p>
<p>For efficiency reasons, Node.js normally buffers the request headers until
<code>request.end()</code> is called or the first chunk of request data is written. It
then tries to pack the request headers and data into a single TCP packet.</p>
<p>That's usually desired (it saves a TCP round-trip), but not when the first
data is not sent until possibly much later. <code>request.flushHeaders()</code> bypasses
the optimization and kickstarts the request.</p>
<h4><code>request.getHeader(name)</code><span><a class="mark" href="#all_http_requestgetheadername" id="all_http_requestgetheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_request_getheader_name"></a></h4>
<div class="api_metadata">
<span>Added in: v1.6.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Reads out a header on the request. The name is case-insensitive.
The type of the return value depends on the arguments provided to
<a href="#all_http_requestsetheadername-value"><code>request.setHeader()</code></a>.</p>
<pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'content-type'</span>, <span class="hljs-string">'text/html'</span>);
request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Length'</span>, <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(body));
request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]);
<span class="hljs-keyword">const</span> contentType = request.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'Content-Type'</span>);
<span class="hljs-comment">// 'contentType' is 'text/html'</span>
<span class="hljs-keyword">const</span> contentLength = request.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'Content-Length'</span>);
<span class="hljs-comment">// 'contentLength' is of type number</span>
<span class="hljs-keyword">const</span> cookie = request.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'Cookie'</span>);
<span class="hljs-comment">// 'cookie' is of type string[]</span></code> <button class="copy-button">copy</button></pre>
<h4><code>request.getHeaderNames()</code><span><a class="mark" href="#all_http_requestgetheadernames" id="all_http_requestgetheadernames">#</a></span><a aria-hidden="true" class="legacy" id="http_request_getheadernames"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>Returns an array containing the unique names of the current outgoing headers.
All header names are lowercase.</p>
<pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);
<span class="hljs-keyword">const</span> headerNames = request.<span class="hljs-title function_">getHeaderNames</span>();
<span class="hljs-comment">// headerNames === ['foo', 'cookie']</span></code> <button class="copy-button">copy</button></pre>
<h4><code>request.getHeaders()</code><span><a class="mark" href="#all_http_requestgetheaders" id="all_http_requestgetheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_request_getheaders"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns a shallow copy of the current outgoing headers. Since a shallow copy
is used, array values may be mutated without additional calls to various
header-related http module methods. The keys of the returned object are the
header names and the values are the respective header values. All header names
are lowercase.</p>
<p>The object returned by the <code>request.getHeaders()</code> method <em>does not</em>
prototypically inherit from the JavaScript <code>Object</code>. This means that typical
<code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others
are not defined and <em>will not work</em>.</p>
<pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);
<span class="hljs-keyword">const</span> headers = request.<span class="hljs-title function_">getHeaders</span>();
<span class="hljs-comment">// headers === { foo: 'bar', 'cookie': ['foo=bar', 'bar=baz'] }</span></code> <button class="copy-button">copy</button></pre>
<h4><code>request.getRawHeaderNames()</code><span><a class="mark" href="#all_http_requestgetrawheadernames" id="all_http_requestgetrawheadernames">#</a></span><a aria-hidden="true" class="legacy" id="http_request_getrawheadernames"></a></h4>
<div class="api_metadata">
<span>Added in: v15.13.0, v14.17.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>Returns an array containing the unique names of the current outgoing raw
headers. Header names are returned with their exact casing being set.</p>
<pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);
<span class="hljs-keyword">const</span> headerNames = request.<span class="hljs-title function_">getRawHeaderNames</span>();
<span class="hljs-comment">// headerNames === ['Foo', 'Set-Cookie']</span></code> <button class="copy-button">copy</button></pre>
<h4><code>request.hasHeader(name)</code><span><a class="mark" href="#all_http_requesthasheadername" id="all_http_requesthasheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_request_hasheader_name"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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 <code>true</code> if the header identified by <code>name</code> is currently set in the
outgoing headers. The header name matching is case-insensitive.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> hasContentType = request.<span class="hljs-title function_">hasHeader</span>(<span class="hljs-string">'content-type'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>request.maxHeadersCount</code><span><a class="mark" href="#all_http_requestmaxheaderscount" id="all_http_requestmaxheaderscount">#</a></span><a aria-hidden="true" class="legacy" id="http_request_maxheaderscount"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>2000</code></li>
</ul>
<p>Limits maximum response headers count. If set to 0, no limit will be applied.</p>
<h4><code>request.path</code><span><a class="mark" href="#all_http_requestpath" id="all_http_requestpath">#</a></span><a aria-hidden="true" class="legacy" id="http_request_path"></a></h4>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The request path.</li>
</ul>
<h4><code>request.method</code><span><a class="mark" href="#all_http_requestmethod" id="all_http_requestmethod">#</a></span><a aria-hidden="true" class="legacy" id="http_request_method"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.97</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The request method.</li>
</ul>
<h4><code>request.host</code><span><a class="mark" href="#all_http_requesthost" id="all_http_requesthost">#</a></span><a aria-hidden="true" class="legacy" id="http_request_host"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The request host.</li>
</ul>
<h4><code>request.protocol</code><span><a class="mark" href="#all_http_requestprotocol" id="all_http_requestprotocol">#</a></span><a aria-hidden="true" class="legacy" id="http_request_protocol"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The request protocol.</li>
</ul>
<h4><code>request.removeHeader(name)</code><span><a class="mark" href="#all_http_requestremoveheadername" id="all_http_requestremoveheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_request_removeheader_name"></a></h4>
<div class="api_metadata">
<span>Added in: v1.6.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Removes a header that's already defined into headers object.</p>
<pre><code class="language-js">request.<span class="hljs-title function_">removeHeader</span>(<span class="hljs-string">'Content-Type'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>request.reusedSocket</code><span><a class="mark" href="#all_http_requestreusedsocket" id="all_http_requestreusedsocket">#</a></span><a aria-hidden="true" class="legacy" id="http_request_reusedsocket"></a></h4>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the request is send through a reused socket.</li>
</ul>
<p>When sending request through a keep-alive enabled agent, the underlying socket
might be reused. But if server closes connection at unfortunate time, client
may run into a 'ECONNRESET' error.</p>
<pre class="with-34-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> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-comment">// Server has a 5 seconds keep-alive timeout by default</span>
http
.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello\n'</span>);
res.<span class="hljs-title function_">end</span>();
})
.<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);
<span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// Adapting a keep-alive agent</span>
http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:3000'</span>, { agent }, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-comment">// Do nothing</span>
});
});
}, <span class="hljs-number">5000</span>); <span class="hljs-comment">// Sending request on 5s interval so it's easy to hit idle timeout</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-comment">// Server has a 5 seconds keep-alive timeout by default</span>
http
.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello\n'</span>);
res.<span class="hljs-title function_">end</span>();
})
.<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);
<span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// Adapting a keep-alive agent</span>
http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:3000'</span>, { agent }, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-comment">// Do nothing</span>
});
});
}, <span class="hljs-number">5000</span>); <span class="hljs-comment">// Sending request on 5s interval so it's easy to hit idle timeout</span></code><button class="copy-button">copy</button></pre>
<p>By marking a request whether it reused socket or not, we can do
automatic error retry base on it.</p>
<pre class="with-50-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> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">const</span> agent = <span class="hljs-keyword">new</span> http.<span class="hljs-title class_">Agent</span>({ <span class="hljs-attr">keepAlive</span>: <span class="hljs-literal">true</span> });
<span class="hljs-keyword">function</span> <span class="hljs-title function_">retriableRequest</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> req = http
.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:3000'</span>, { agent }, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-comment">// ...</span>
})
.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-comment">// Check if retry is needed</span>
<span class="hljs-keyword">if</span> (req.<span class="hljs-property">reusedSocket</span> && err.<span class="hljs-property">code</span> === <span class="hljs-string">'ECONNRESET'</span>) {
<span class="hljs-title function_">retriableRequest</span>();
}
});
}
<span class="hljs-title function_">retriableRequest</span>();</code><code class="language-js cjs"><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> agent = <span class="hljs-keyword">new</span> http.<span class="hljs-title class_">Agent</span>({ <span class="hljs-attr">keepAlive</span>: <span class="hljs-literal">true</span> });
<span class="hljs-keyword">function</span> <span class="hljs-title function_">retriableRequest</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> req = http
.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:3000'</span>, { agent }, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-comment">// ...</span>
})
.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-comment">// Check if retry is needed</span>
<span class="hljs-keyword">if</span> (req.<span class="hljs-property">reusedSocket</span> && err.<span class="hljs-property">code</span> === <span class="hljs-string">'ECONNRESET'</span>) {
<span class="hljs-title function_">retriableRequest</span>();
}
});
}
<span class="hljs-title function_">retriableRequest</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>request.setHeader(name, value)</code><span><a class="mark" href="#all_http_requestsetheadername-value" id="all_http_requestsetheadername-value">#</a></span><a aria-hidden="true" class="legacy" id="http_request_setheader_name_value"></a></h4>
<div class="api_metadata">
<span>Added in: v1.6.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Sets a single header value for headers object. If this header already exists in
the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, <a href="#all_http_requestgetheadername"><code>request.getHeader()</code></a> may return
non-string values. However, the non-string values will be converted to strings
for network transmission.</p>
<pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'application/json'</span>);</code> <button class="copy-button">copy</button></pre>
<p>or</p>
<pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]);</code> <button class="copy-button">copy</button></pre>
<p>When the value is a string an exception will be thrown if it contains
characters outside the <code>latin1</code> encoding.</p>
<p>If you need to pass UTF-8 characters in the value please encode the value
using the <a href="https://www.rfc-editor.org/rfc/rfc8187.txt">RFC 8187</a> standard.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> filename = <span class="hljs-string">'Rock 🎵.txt'</span>;
request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Disposition'</span>, <span class="hljs-string">`attachment; filename*=utf-8''<span class="hljs-subst">${<span class="hljs-built_in">encodeURIComponent</span>(filename)}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>request.setNoDelay([noDelay])</code><span><a class="mark" href="#all_http_requestsetnodelaynodelay" id="all_http_requestsetnodelaynodelay">#</a></span><a aria-hidden="true" class="legacy" id="http_request_setnodelay_nodelay"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div>
<ul>
<li><code>noDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Once a socket is assigned to this request and is connected
<a href="#all_net_socketsetnodelaynodelay"><code>socket.setNoDelay()</code></a> will be called.</p>
<h4><code>request.setSocketKeepAlive([enable][, initialDelay])</code><span><a class="mark" href="#all_http_requestsetsocketkeepaliveenable-initialdelay" id="all_http_requestsetsocketkeepaliveenable-initialdelay">#</a></span><a aria-hidden="true" class="legacy" id="http_request_setsocketkeepalive_enable_initialdelay"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div>
<ul>
<li><code>enable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>initialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Once a socket is assigned to this request and is connected
<a href="#all_net_socketsetkeepaliveenable-initialdelay"><code>socket.setKeepAlive()</code></a> will be called.</p>
<h4><code>request.setTimeout(timeout[, callback])</code><span><a class="mark" href="#all_http_requestsettimeouttimeout-callback" id="all_http_requestsettimeouttimeout-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_request_settimeout_timeout_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>v9.0.0</td>
<td><p>Consistently set socket timeout only when the socket connects.</p></td></tr>
<tr><td>v0.5.9</td>
<td><p><span>Added in: v0.5.9</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Milliseconds before a request times out.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Optional function to be called when a timeout occurs.
Same as binding to the <code>'timeout'</code> event.</li>
<li>Returns: <a href="#all_http_class-httpclientrequest" class="type"><http.ClientRequest></a></li>
</ul>
<p>Once a socket is assigned to this request and is connected
<a href="#all_net_socketsettimeouttimeout-callback"><code>socket.setTimeout()</code></a> will be called.</p>
<h4><code>request.socket</code><span><a class="mark" href="#all_http_requestsocket" id="all_http_requestsocket">#</a></span><a aria-hidden="true" class="legacy" id="http_request_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit <code>'readable'</code> events
because of how the protocol parser attaches to the socket.</p>
<pre class="with-34-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> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">host</span>: <span class="hljs-string">'www.google.com'</span>,
};
<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">get</span>(options);
req.<span class="hljs-title function_">end</span>();
req.<span class="hljs-title function_">once</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-keyword">const</span> ip = req.<span class="hljs-property">socket</span>.<span class="hljs-property">localAddress</span>;
<span class="hljs-keyword">const</span> port = req.<span class="hljs-property">socket</span>.<span class="hljs-property">localPort</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>);
<span class="hljs-comment">// Consume response object</span>
});</code><code class="language-js cjs"><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> options = {
<span class="hljs-attr">host</span>: <span class="hljs-string">'www.google.com'</span>,
};
<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">get</span>(options);
req.<span class="hljs-title function_">end</span>();
req.<span class="hljs-title function_">once</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-keyword">const</span> ip = req.<span class="hljs-property">socket</span>.<span class="hljs-property">localAddress</span>;
<span class="hljs-keyword">const</span> port = req.<span class="hljs-property">socket</span>.<span class="hljs-property">localPort</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>);
<span class="hljs-comment">// Consume response object</span>
});</code><button class="copy-button">copy</button></pre>
<p>This property is guaranteed to be an instance of the <a href="#all_net_class-netsocket" class="type"><net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>, unless the user specified a socket
type other than <a href="#all_net_class-netsocket" class="type"><net.Socket></a>.</p>
<h4><code>request.uncork()</code><span><a class="mark" href="#all_http_requestuncork" id="all_http_requestuncork">#</a></span><a aria-hidden="true" class="legacy" id="http_request_uncork"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>See <a href="#all_stream_writableuncork"><code>writable.uncork()</code></a>.</p>
<h4><code>request.writableEnded</code><span><a class="mark" href="#all_http_requestwritableended" id="all_http_requestwritableended">#</a></span><a aria-hidden="true" class="legacy" id="http_request_writableended"></a></h4>
<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="#all_http_requestenddata-encoding-callback"><code>request.end()</code></a> has been called. This property
does not indicate whether the data has been flushed, for this use
<a href="#all_http_requestwritablefinished"><code>request.writableFinished</code></a> instead.</p>
<h4><code>request.writableFinished</code><span><a class="mark" href="#all_http_requestwritablefinished" id="all_http_requestwritablefinished">#</a></span><a aria-hidden="true" class="legacy" id="http_request_writablefinished"></a></h4>
<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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Is <code>true</code> if all data has been flushed to the underlying system, immediately
before the <a href="#all_http_event-finish"><code>'finish'</code></a> event is emitted.</p>
<h4><code>request.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#all_http_requestwritechunk-encoding-callback" id="all_http_requestwritechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_request_write_chunk_encoding_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>v15.0.0</td>
<td><p>The <code>chunk</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v0.1.29</td>
<td><p><span>Added in: v0.1.29</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="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></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>Sends a chunk of the body. This method can be called multiple times. If no
<code>Content-Length</code> is set, data will automatically be encoded in HTTP Chunked
transfer encoding, so that server knows when the data ends. The
<code>Transfer-Encoding: chunked</code> header is added. Calling <a href="#all_http_requestenddata-encoding-callback"><code>request.end()</code></a>
is necessary to finish sending the request.</p>
<p>The <code>encoding</code> argument is optional and only applies when <code>chunk</code> is a string.
Defaults to <code>'utf8'</code>.</p>
<p>The <code>callback</code> argument is optional and will be called when this chunk of data
is flushed, but only if the chunk is non-empty.</p>
<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
buffer. Returns <code>false</code> if all or part of the data was queued in user memory.
<code>'drain'</code> will be emitted when the buffer is free again.</p>
<p>When <code>write</code> function is called with empty string or buffer, it does
nothing and waits for more input.</p>
</section><section><h3>Class: <code>http.Server</code><span><a class="mark" href="#all_http_class-httpserver" id="all_http_class-httpserver">#</a></span><a aria-hidden="true" class="legacy" id="http_class_http_server"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<ul>
<li>Extends: <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<h4>Event: <code>'checkContinue'</code><span><a class="mark" href="#all_http_event-checkcontinue" id="all_http_event-checkcontinue">#</a></span><a aria-hidden="true" class="legacy" id="http_event_checkcontinue"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a></li>
<li><code>response</code> <a href="#all_http_class-httpserverresponse" class="type"><http.ServerResponse></a></li>
</ul>
<p>Emitted each time a request with an HTTP <code>Expect: 100-continue</code> is received.
If this event is not listened for, the server will automatically respond
with a <code>100 Continue</code> as appropriate.</p>
<p>Handling this event involves calling <a href="#all_http_responsewritecontinue"><code>response.writeContinue()</code></a> if the
client should continue to send the request body, or generating an appropriate
HTTP response (e.g. 400 Bad Request) if the client should not continue to send
the request body.</p>
<p>When this event is emitted and handled, the <a href="#all_http_event-request"><code>'request'</code></a> event will
not be emitted.</p>
<h4>Event: <code>'checkExpectation'</code><span><a class="mark" href="#all_http_event-checkexpectation" id="all_http_event-checkexpectation">#</a></span><a aria-hidden="true" class="legacy" id="http_event_checkexpectation"></a></h4>
<div class="api_metadata">
<span>Added in: v5.5.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a></li>
<li><code>response</code> <a href="#all_http_class-httpserverresponse" class="type"><http.ServerResponse></a></li>
</ul>
<p>Emitted each time a request with an HTTP <code>Expect</code> header is received, where the
value is not <code>100-continue</code>. If this event is not listened for, the server will
automatically respond with a <code>417 Expectation Failed</code> as appropriate.</p>
<p>When this event is emitted and handled, the <a href="#all_http_event-request"><code>'request'</code></a> event will
not be emitted.</p>
<h4>Event: <code>'clientError'</code><span><a class="mark" href="#all_http_event-clienterror" id="all_http_event-clienterror">#</a></span><a aria-hidden="true" class="legacy" id="http_event_clienterror"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>The default behavior will return a 431 Request Header Fields Too Large if a HPE_HEADER_OVERFLOW error occurs.</p></td></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>rawPacket</code> is the current buffer that just parsed. Adding this buffer to the error object of <code>'clientError'</code> event is to make it possible that developers can log the broken packet.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The default action of calling <code>.destroy()</code> on the <code>socket</code> will no longer take place if there are listeners attached for <code>'clientError'</code>.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>exception</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>If a client connection emits an <code>'error'</code> event, it will be forwarded here.
Listener of this event is responsible for closing/destroying the underlying
socket. For example, one may wish to more gracefully close the socket with a
custom HTTP response instead of abruptly severing the connection. The socket
<strong>must be closed or destroyed</strong> before the listener ends.</p>
<p>This event is guaranteed to be passed an instance of the <a href="#all_net_class-netsocket" class="type"><net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type"><net.Socket></a>.</p>
<p>Default behavior is to try close the socket with a HTTP '400 Bad Request',
or a HTTP '431 Request Header Fields Too Large' in the case of a
<a href="#all_errors_hpe_header_overflow"><code>HPE_HEADER_OVERFLOW</code></a> error. If the socket is not writable or headers
of the current attached <a href="#all_http_class-httpserverresponse"><code>http.ServerResponse</code></a> has been sent, it is
immediately destroyed.</p>
<p><code>socket</code> is the <a href="#all_net_class-netsocket"><code>net.Socket</code></a> object that the error originated from.</p>
<pre class="with-34-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> http <span class="hljs-keyword">from</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> {
res.<span class="hljs-title function_">end</span>();
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'clientError'</span>, <span class="hljs-function">(<span class="hljs-params">err, socket</span>) =></span> {
socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'HTTP/1.1 400 Bad Request\r\n\r\n'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><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> {
res.<span class="hljs-title function_">end</span>();
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'clientError'</span>, <span class="hljs-function">(<span class="hljs-params">err, socket</span>) =></span> {
socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'HTTP/1.1 400 Bad Request\r\n\r\n'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>
<p>When the <code>'clientError'</code> event occurs, there is no <code>request</code> or <code>response</code>
object, so any HTTP response sent, including response headers and payload,
<em>must</em> be written directly to the <code>socket</code> object. Care must be taken to
ensure the response is a properly formatted HTTP response message.</p>
<p><code>err</code> is an instance of <code>Error</code> with two extra columns:</p>
<ul>
<li><code>bytesParsed</code>: the bytes count of request packet that Node.js may have parsed
correctly;</li>
<li><code>rawPacket</code>: the raw packet of current request.</li>
</ul>
<p>In some cases, the client has already received the response and/or the socket
has already been destroyed, like in case of <code>ECONNRESET</code> errors. Before
trying to send data to the socket, it is better to check that it is still
writable.</p>
<pre><code class="language-js">server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'clientError'</span>, <span class="hljs-function">(<span class="hljs-params">err, socket</span>) =></span> {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'ECONNRESET'</span> || !socket.<span class="hljs-property">writable</span>) {
<span class="hljs-keyword">return</span>;
}
socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'HTTP/1.1 400 Bad Request\r\n\r\n'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_http_event-close_1" id="all_http_event-close_1">#</a></span><a aria-hidden="true" class="legacy" id="http_event_close_1"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.4</span>
</div>
<p>Emitted when the server closes.</p>
<h4>Event: <code>'connect'</code><span><a class="mark" href="#all_http_event-connect_1" id="all_http_event-connect_1">#</a></span><a aria-hidden="true" class="legacy" id="http_event_connect_1"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a> Arguments for the HTTP request, as it is in
the <a href="#all_http_event-request"><code>'request'</code></a> event</li>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a> Network socket between the server and client</li>
<li><code>head</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The first packet of the tunneling stream (may be empty)</li>
</ul>
<p>Emitted each time a client requests an HTTP <code>CONNECT</code> method. If this event is
not listened for, then clients requesting a <code>CONNECT</code> method will have their
connections closed.</p>
<p>This event is guaranteed to be passed an instance of the <a href="#all_net_class-netsocket" class="type"><net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type"><net.Socket></a>.</p>
<p>After this event is emitted, the request's socket will not have a <code>'data'</code>
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.</p>
<h4>Event: <code>'connection'</code><span><a class="mark" href="#all_http_event-connection" id="all_http_event-connection">#</a></span><a aria-hidden="true" class="legacy" id="http_event_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.0</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>This event is emitted when a new TCP stream is established. <code>socket</code> is
typically an object of type <a href="#all_net_class-netsocket"><code>net.Socket</code></a>. Usually users will not want to
access this event. In particular, the socket will not emit <code>'readable'</code> events
because of how the protocol parser attaches to the socket. The <code>socket</code> can
also be accessed at <code>request.socket</code>.</p>
<p>This event can also be explicitly emitted by users to inject connections
into the HTTP server. In that case, any <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> stream can be passed.</p>
<p>If <code>socket.setTimeout()</code> is called here, the timeout will be replaced with
<code>server.keepAliveTimeout</code> when the socket has served a request (if
<code>server.keepAliveTimeout</code> is non-zero).</p>
<p>This event is guaranteed to be passed an instance of the <a href="#all_net_class-netsocket" class="type"><net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type"><net.Socket></a>.</p>
<h4>Event: <code>'dropRequest'</code><span><a class="mark" href="#all_http_event-droprequest" id="all_http_event-droprequest">#</a></span><a aria-hidden="true" class="legacy" id="http_event_droprequest"></a></h4>
<div class="api_metadata">
<span>Added in: v18.7.0, v16.17.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a> Arguments for the HTTP request, as it is in
the <a href="#all_http_event-request"><code>'request'</code></a> event</li>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a> Network socket between the server and client</li>
</ul>
<p>When the number of requests on a socket reaches the threshold of
<code>server.maxRequestsPerSocket</code>, the server will drop new requests
and emit <code>'dropRequest'</code> event instead, then send <code>503</code> to client.</p>
<h4>Event: <code>'request'</code><span><a class="mark" href="#all_http_event-request" id="all_http_event-request">#</a></span><a aria-hidden="true" class="legacy" id="http_event_request"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a></li>
<li><code>response</code> <a href="#all_http_class-httpserverresponse" class="type"><http.ServerResponse></a></li>
</ul>
<p>Emitted each time there is a request. There may be multiple requests
per connection (in the case of HTTP Keep-Alive connections).</p>
<h4>Event: <code>'upgrade'</code><span><a class="mark" href="#all_http_event-upgrade_1" id="all_http_event-upgrade_1">#</a></span><a aria-hidden="true" class="legacy" id="http_event_upgrade_1"></a></h4>
<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>Not listening to this event no longer causes the socket to be destroyed if a client sends an Upgrade header.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a> Arguments for the HTTP request, as it is in
the <a href="#all_http_event-request"><code>'request'</code></a> event</li>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a> Network socket between the server and client</li>
<li><code>head</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The first packet of the upgraded stream (may be empty)</li>
</ul>
<p>Emitted each time a client requests an HTTP upgrade. Listening to this event
is optional and clients cannot insist on a protocol change.</p>
<p>After this event is emitted, the request's socket will not have a <code>'data'</code>
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.</p>
<p>This event is guaranteed to be passed an instance of the <a href="#all_net_class-netsocket" class="type"><net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type"><net.Socket></a>.</p>
<h4><code>server.close([callback])</code><span><a class="mark" href="#all_http_serverclosecallback" id="all_http_serverclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="http_server_close_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.0.0</td>
<td><p>The method closes idle connections before returning.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</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></li>
</ul>
<p>Stops the server from accepting new connections and closes all connections
connected to this server which are not sending a request or waiting for
a response.
See <a href="#all_net_serverclosecallback"><code>net.Server.close()</code></a>.</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-attr">keepAliveTimeout</span>: <span class="hljs-number">60000</span> }, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
<span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
}));
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
<span class="hljs-comment">// Close the server after 10 seconds</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
server.<span class="hljs-title function_">close</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server on port 8000 closed successfully'</span>);
});
}, <span class="hljs-number">10000</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>server.closeAllConnections()</code><span><a class="mark" href="#all_http_servercloseallconnections" id="all_http_servercloseallconnections">#</a></span><a aria-hidden="true" class="legacy" id="http_server_closeallconnections"></a></h4>
<div class="api_metadata">
<span>Added in: v18.2.0</span>
</div>
<p>Closes all established HTTP(S) connections connected to this server, including
active connections connected to this server which are sending a request or
waiting for a response. This does <em>not</em> destroy sockets upgraded to a different
protocol, such as WebSocket or HTTP/2.</p>
<blockquote>
<p>This is a forceful way of closing all connections and should be used with
caution. Whenever using this in conjunction with <code>server.close</code>, calling this
<em>after</em> <code>server.close</code> is recommended as to avoid race conditions where new
connections are created between a call to this and a call to <code>server.close</code>.</p>
</blockquote>
<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-attr">keepAliveTimeout</span>: <span class="hljs-number">60000</span> }, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
<span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
}));
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
<span class="hljs-comment">// Close the server after 10 seconds</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
server.<span class="hljs-title function_">close</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server on port 8000 closed successfully'</span>);
});
<span class="hljs-comment">// Closes all connections, ensuring the server closes successfully</span>
server.<span class="hljs-title function_">closeAllConnections</span>();
}, <span class="hljs-number">10000</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>server.closeIdleConnections()</code><span><a class="mark" href="#all_http_servercloseidleconnections" id="all_http_servercloseidleconnections">#</a></span><a aria-hidden="true" class="legacy" id="http_server_closeidleconnections"></a></h4>
<div class="api_metadata">
<span>Added in: v18.2.0</span>
</div>
<p>Closes all connections connected to this server which are not sending a request
or waiting for a response.</p>
<blockquote>
<p>Starting with Node.js 19.0.0, there's no need for calling this method in
conjunction with <code>server.close</code> to reap <code>keep-alive</code> connections. Using it
won't cause any harm though, and it can be useful to ensure backwards
compatibility for libraries and applications that need to support versions
older than 19.0.0. Whenever using this in conjunction with <code>server.close</code>,
calling this <em>after</em> <code>server.close</code> is recommended as to avoid race
conditions where new connections are created between a call to this and a
call to <code>server.close</code>.</p>
</blockquote>
<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-attr">keepAliveTimeout</span>: <span class="hljs-number">60000</span> }, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
<span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
}));
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
<span class="hljs-comment">// Close the server after 10 seconds</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
server.<span class="hljs-title function_">close</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server on port 8000 closed successfully'</span>);
});
<span class="hljs-comment">// Closes idle connections, such as keep-alive connections. Server will close</span>
<span class="hljs-comment">// once remaining active connections are terminated</span>
server.<span class="hljs-title function_">closeIdleConnections</span>();
}, <span class="hljs-number">10000</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>server.headersTimeout</code><span><a class="mark" href="#all_http_serverheaderstimeout" id="all_http_serverheaderstimeout">#</a></span><a aria-hidden="true" class="legacy" id="http_server_headerstimeout"></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.4.0, v18.14.0</td>
<td><p>The default is now set to the minimum between 60000 (60 seconds) or <code>requestTimeout</code>.</p></td></tr>
<tr><td>v11.3.0, v10.14.0</td>
<td><p><span>Added in: v11.3.0, v10.14.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> The minimum between <a href="#all_http_serverrequesttimeout"><code>server.requestTimeout</code></a> or <code>60000</code>.</li>
</ul>
<p>Limit the amount of time the parser will wait to receive the complete HTTP
headers.</p>
<p>If the timeout expires, the server responds with status 408 without
forwarding the request to the request listener and then closes the connection.</p>
<p>It must be set to a non-zero value (e.g. 120 seconds) to protect against
potential Denial-of-Service attacks in case the server is deployed without a
reverse proxy in front.</p>
<h4><code>server.listen()</code><span><a class="mark" href="#all_http_serverlisten" id="all_http_serverlisten">#</a></span><a aria-hidden="true" class="legacy" id="http_server_listen"></a></h4>
<p>Starts the HTTP server listening for connections.
This method is identical to <a href="#all_net_serverlisten"><code>server.listen()</code></a> from <a href="#all_net_class-netserver"><code>net.Server</code></a>.</p>
<h4><code>server.listening</code><span><a class="mark" href="#all_http_serverlistening" id="all_http_serverlistening">#</a></span><a aria-hidden="true" class="legacy" id="http_server_listening"></a></h4>
<div class="api_metadata">
<span>Added in: v5.7.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether or not the server is listening for connections.</li>
</ul>
<h4><code>server.maxHeadersCount</code><span><a class="mark" href="#all_http_servermaxheaderscount" id="all_http_servermaxheaderscount">#</a></span><a aria-hidden="true" class="legacy" id="http_server_maxheaderscount"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>2000</code></li>
</ul>
<p>Limits maximum incoming headers count. If set to 0, no limit will be applied.</p>
<h4><code>server.requestTimeout</code><span><a class="mark" href="#all_http_serverrequesttimeout" id="all_http_serverrequesttimeout">#</a></span><a aria-hidden="true" class="legacy" id="http_server_requesttimeout"></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</td>
<td><p>The default request timeout changed from no timeout to 300s (5 minutes).</p></td></tr>
<tr><td>v14.11.0</td>
<td><p><span>Added in: v14.11.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>300000</code></li>
</ul>
<p>Sets the timeout value in milliseconds for receiving the entire request from
the client.</p>
<p>If the timeout expires, the server responds with status 408 without
forwarding the request to the request listener and then closes the connection.</p>
<p>It must be set to a non-zero value (e.g. 120 seconds) to protect against
potential Denial-of-Service attacks in case the server is deployed without a
reverse proxy in front.</p>
<h4><code>server.setTimeout([msecs][, callback])</code><span><a class="mark" href="#all_http_serversettimeoutmsecs-callback" id="all_http_serversettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_server_settimeout_msecs_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>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</p></td></tr>
<tr><td>v0.9.12</td>
<td><p><span>Added in: v0.9.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> 0 (no timeout)</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_http_class-httpserver" class="type"><http.Server></a></li>
</ul>
<p>Sets the timeout value for sockets, and emits a <code>'timeout'</code> event on
the Server object, passing the socket as an argument, if a timeout
occurs.</p>
<p>If there is a <code>'timeout'</code> event listener on the Server object, then it
will be called with the timed-out socket as an argument.</p>
<p>By default, the Server does not timeout sockets. However, if a callback
is assigned to the Server's <code>'timeout'</code> event, timeouts must be handled
explicitly.</p>
<h4><code>server.maxRequestsPerSocket</code><span><a class="mark" href="#all_http_servermaxrequestspersocket" id="all_http_servermaxrequestspersocket">#</a></span><a aria-hidden="true" class="legacy" id="http_server_maxrequestspersocket"></a></h4>
<div class="api_metadata">
<span>Added in: v16.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Requests per socket. <strong>Default:</strong> 0 (no limit)</li>
</ul>
<p>The maximum number of requests socket can handle
before closing keep alive connection.</p>
<p>A value of <code>0</code> will disable the limit.</p>
<p>When the limit is reached it will set the <code>Connection</code> header value to <code>close</code>,
but will not actually close the connection, subsequent requests sent
after the limit is reached will get <code>503 Service Unavailable</code> as a response.</p>
<h4><code>server.timeout</code><span><a class="mark" href="#all_http_servertimeout" id="all_http_servertimeout">#</a></span><a aria-hidden="true" class="legacy" id="http_server_timeout"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</p></td></tr>
<tr><td>v0.9.12</td>
<td><p><span>Added in: v0.9.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Timeout in milliseconds. <strong>Default:</strong> 0 (no timeout)</li>
</ul>
<p>The number of milliseconds of inactivity before a socket is presumed
to have timed out.</p>
<p>A value of <code>0</code> will disable the timeout behavior on incoming connections.</p>
<p>The socket timeout logic is set up on connection, so changing this
value only affects new connections to the server, not any existing connections.</p>
<h4><code>server.keepAliveTimeout</code><span><a class="mark" href="#all_http_serverkeepalivetimeout" id="all_http_serverkeepalivetimeout">#</a></span><a aria-hidden="true" class="legacy" id="http_server_keepalivetimeout"></a></h4>
<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#Number_type" class="type"><number></a> Timeout in milliseconds. <strong>Default:</strong> <code>5000</code> (5 seconds).</li>
</ul>
<p>The number of milliseconds of inactivity a server needs to wait for additional
incoming data, after it has finished writing the last response, before a socket
will be destroyed. If the server receives new data before the keep-alive
timeout has fired, it will reset the regular inactivity timeout, i.e.,
<a href="#all_http_servertimeout"><code>server.timeout</code></a>.</p>
<p>A value of <code>0</code> will disable the keep-alive timeout behavior on incoming
connections.
A value of <code>0</code> makes the http server behave similarly to Node.js versions prior
to 8.0.0, which did not have a keep-alive timeout.</p>
<p>The socket timeout logic is set up on connection, so changing this value only
affects new connections to the server, not any existing connections.</p>
<h4><code>server[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_http_serversymbolasyncdispose" id="all_http_serversymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="http_server_symbol_asyncdispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_http_serverclosecallback"><code>server.close()</code></a> and returns a promise that fulfills when the
server has closed.</p>
</section><section><h3>Class: <code>http.ServerResponse</code><span><a class="mark" href="#all_http_class-httpserverresponse" id="all_http_class-httpserverresponse">#</a></span><a aria-hidden="true" class="legacy" id="http_class_http_serverresponse"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<ul>
<li>Extends: <a href="#all_http_class-httpoutgoingmessage" class="type"><http.OutgoingMessage></a></li>
</ul>
<p>This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the <a href="#all_http_event-request"><code>'request'</code></a> event.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_http_event-close_2" id="all_http_event-close_2">#</a></span><a aria-hidden="true" class="legacy" id="http_event_close_2"></a></h4>
<div class="api_metadata">
<span>Added in: v0.6.7</span>
</div>
<p>Indicates that the response is completed, or its underlying connection was
terminated prematurely (before the response completion).</p>
<h4>Event: <code>'finish'</code><span><a class="mark" href="#all_http_event-finish_1" id="all_http_event-finish_1">#</a></span><a aria-hidden="true" class="legacy" id="http_event_finish_1"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div>
<p>Emitted when the response has been sent. More specifically, this event is
emitted when the last segment of the response headers and body have been
handed off to the operating system for transmission over the network. It
does not imply that the client has received anything yet.</p>
<h4><code>response.addTrailers(headers)</code><span><a class="mark" href="#all_http_responseaddtrailersheaders" id="all_http_responseaddtrailersheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_response_addtrailers_headers"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>This method adds HTTP trailing headers (a header but at the end of the
message) to the response.</p>
<p>Trailers will <strong>only</strong> be emitted if chunked encoding is used for the
response; if it is not (e.g. if the request was HTTP/1.0), they will
be silently discarded.</p>
<p>HTTP requires the <code>Trailer</code> header to be sent in order to
emit trailers, with a list of the header fields in its value. E.g.,</p>
<pre><code class="language-js">response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span>,
<span class="hljs-string">'Trailer'</span>: <span class="hljs-string">'Content-MD5'</span> });
response.<span class="hljs-title function_">write</span>(fileData);
response.<span class="hljs-title function_">addTrailers</span>({ <span class="hljs-string">'Content-MD5'</span>: <span class="hljs-string">'7895bf4b8828b55ceaf47747b4bca667'</span> });
response.<span class="hljs-title function_">end</span>();</code> <button class="copy-button">copy</button></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
<h4><code>response.connection</code><span><a class="mark" href="#all_http_responseconnection" id="all_http_responseconnection">#</a></span><a aria-hidden="true" class="legacy" id="http_response_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span><span>Deprecated since: v13.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http_responsesocket"><code>response.socket</code></a>.</div><p></p>
<ul>
<li><a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>See <a href="#all_http_responsesocket"><code>response.socket</code></a>.</p>
<h4><code>response.cork()</code><span><a class="mark" href="#all_http_responsecork" id="all_http_responsecork">#</a></span><a aria-hidden="true" class="legacy" id="http_response_cork"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>See <a href="#all_stream_writablecork"><code>writable.cork()</code></a>.</p>
<h4><code>response.end([data[, encoding]][, callback])</code><span><a class="mark" href="#all_http_responseenddata-encoding-callback" id="all_http_responseenddata-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_response_end_data_encoding_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>v15.0.0</td>
<td><p>The <code>data</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>This method now returns a reference to <code>ServerResponse</code>.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></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>This method signals to the server that all of the response headers and body
have been sent; that server should consider this message complete.
The method, <code>response.end()</code>, MUST be called on each response.</p>
<p>If <code>data</code> is specified, it is similar in effect to calling
<a href="#all_http_responsewritechunk-encoding-callback"><code>response.write(data, encoding)</code></a> followed by <code>response.end(callback)</code>.</p>
<p>If <code>callback</code> is specified, it will be called when the response stream
is finished.</p>
<h4><code>response.finished</code><span><a class="mark" href="#all_http_responsefinished" id="all_http_responsefinished">#</a></span><a aria-hidden="true" class="legacy" id="http_response_finished"></a></h4>
<div class="api_metadata">
<span>Added in: v0.0.2</span><span>Deprecated since: v13.4.0, v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http_responsewritableended"><code>response.writableEnded</code></a>.</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>The <code>response.finished</code> property will be <code>true</code> if <a href="#all_http_responseenddata-encoding-callback"><code>response.end()</code></a>
has been called.</p>
<h4><code>response.flushHeaders()</code><span><a class="mark" href="#all_http_responseflushheaders" id="all_http_responseflushheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_response_flushheaders"></a></h4>
<div class="api_metadata">
<span>Added in: v1.6.0</span>
</div>
<p>Flushes the response headers. See also: <a href="#all_http_requestflushheaders"><code>request.flushHeaders()</code></a>.</p>
<h4><code>response.getHeader(name)</code><span><a class="mark" href="#all_http_responsegetheadername" id="all_http_responsegetheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_response_getheader_name"></a></h4>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Reads out a header that's already been queued but not sent to the client.
The name is case-insensitive. The type of the return value depends
on the arguments provided to <a href="#all_http_responsesetheadername-value"><code>response.setHeader()</code></a>.</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Length'</span>, <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(body));
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]);
<span class="hljs-keyword">const</span> contentType = response.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'content-type'</span>);
<span class="hljs-comment">// contentType is 'text/html'</span>
<span class="hljs-keyword">const</span> contentLength = response.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'Content-Length'</span>);
<span class="hljs-comment">// contentLength is of type number</span>
<span class="hljs-keyword">const</span> setCookie = response.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'set-cookie'</span>);
<span class="hljs-comment">// setCookie is of type string[]</span></code> <button class="copy-button">copy</button></pre>
<h4><code>response.getHeaderNames()</code><span><a class="mark" href="#all_http_responsegetheadernames" id="all_http_responsegetheadernames">#</a></span><a aria-hidden="true" class="legacy" id="http_response_getheadernames"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>Returns an array containing the unique names of the current outgoing headers.
All header names are lowercase.</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);
<span class="hljs-keyword">const</span> headerNames = response.<span class="hljs-title function_">getHeaderNames</span>();
<span class="hljs-comment">// headerNames === ['foo', 'set-cookie']</span></code> <button class="copy-button">copy</button></pre>
<h4><code>response.getHeaders()</code><span><a class="mark" href="#all_http_responsegetheaders" id="all_http_responsegetheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_response_getheaders"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns a shallow copy of the current outgoing headers. Since a shallow copy
is used, array values may be mutated without additional calls to various
header-related http module methods. The keys of the returned object are the
header names and the values are the respective header values. All header names
are lowercase.</p>
<p>The object returned by the <code>response.getHeaders()</code> method <em>does not</em>
prototypically inherit from the JavaScript <code>Object</code>. This means that typical
<code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others
are not defined and <em>will not work</em>.</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);
<span class="hljs-keyword">const</span> headers = response.<span class="hljs-title function_">getHeaders</span>();
<span class="hljs-comment">// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }</span></code> <button class="copy-button">copy</button></pre>
<h4><code>response.hasHeader(name)</code><span><a class="mark" href="#all_http_responsehasheadername" id="all_http_responsehasheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_response_hasheader_name"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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 <code>true</code> if the header identified by <code>name</code> is currently set in the
outgoing headers. The header name matching is case-insensitive.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> hasContentType = response.<span class="hljs-title function_">hasHeader</span>(<span class="hljs-string">'content-type'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>response.headersSent</code><span><a class="mark" href="#all_http_responseheaderssent" id="all_http_responseheaderssent">#</a></span><a aria-hidden="true" class="legacy" id="http_response_headerssent"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.3</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>Boolean (read-only). True if headers were sent, false otherwise.</p>
<h4><code>response.removeHeader(name)</code><span><a class="mark" href="#all_http_responseremoveheadername" id="all_http_responseremoveheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_response_removeheader_name"></a></h4>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Removes a header that's queued for implicit sending.</p>
<pre><code class="language-js">response.<span class="hljs-title function_">removeHeader</span>(<span class="hljs-string">'Content-Encoding'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>response.req</code><span><a class="mark" href="#all_http_responsereq" id="all_http_responsereq">#</a></span><a aria-hidden="true" class="legacy" id="http_response_req"></a></h4>
<div class="api_metadata">
<span>Added in: v15.7.0</span>
</div>
<ul>
<li><a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a></li>
</ul>
<p>A reference to the original HTTP <code>request</code> object.</p>
<h4><code>response.sendDate</code><span><a class="mark" href="#all_http_responsesenddate" id="all_http_responsesenddate">#</a></span><a aria-hidden="true" class="legacy" id="http_response_senddate"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.5</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>When true, the Date header will be automatically generated and sent in
the response if it is not already present in the headers. Defaults to true.</p>
<p>This should only be disabled for testing; HTTP requires the Date header
in responses.</p>
<h4><code>response.setHeader(name, value)</code><span><a class="mark" href="#all_http_responsesetheadername-value" id="all_http_responsesetheadername-value">#</a></span><a aria-hidden="true" class="legacy" id="http_response_setheader_name_value"></a></h4>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>value</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="#all_http_class-httpserverresponse" class="type"><http.ServerResponse></a></li>
</ul>
<p>Returns the response object.</p>
<p>Sets a single header value for implicit headers. If this header already exists
in the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, <a href="#all_http_responsegetheadername"><code>response.getHeader()</code></a> may return
non-string values. However, the non-string values will be converted to strings
for network transmission. The same response object is returned to the caller,
to enable call chaining.</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);</code> <button class="copy-button">copy</button></pre>
<p>or</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]);</code> <button class="copy-button">copy</button></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
<p>When headers have been set with <a href="#all_http_responsesetheadername-value"><code>response.setHeader()</code></a>, they will be merged
with any headers passed to <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a>, with the headers passed
to <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="language-js"><span class="hljs-comment">// Returns content-type = text/plain</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> {
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>);
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>If <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> method is called and this method has not been
called, it will directly write the supplied header values onto the network
channel without caching internally, and the <a href="#all_http_responsegetheadername"><code>response.getHeader()</code></a> on the
header will not yield the expected result. If progressive population of headers
is desired with potential future retrieval and modification, use
<a href="#all_http_responsesetheadername-value"><code>response.setHeader()</code></a> instead of <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a>.</p>
<h4><code>response.setTimeout(msecs[, callback])</code><span><a class="mark" href="#all_http_responsesettimeoutmsecs-callback" id="all_http_responsesettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_response_settimeout_msecs_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.12</span>
</div>
<ul>
<li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_http_class-httpserverresponse" class="type"><http.ServerResponse></a></li>
</ul>
<p>Sets the Socket's timeout value to <code>msecs</code>. If a callback is
provided, then it is added as a listener on the <code>'timeout'</code> event on
the response object.</p>
<p>If no <code>'timeout'</code> listener is added to the request, the response, or
the server, then sockets are destroyed when they time out. If a handler is
assigned to the request, the response, or the server's <code>'timeout'</code> events,
timed out sockets must be handled explicitly.</p>
<h4><code>response.socket</code><span><a class="mark" href="#all_http_responsesocket" id="all_http_responsesocket">#</a></span><a aria-hidden="true" class="legacy" id="http_response_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit <code>'readable'</code> events
because of how the protocol parser attaches to the socket. After
<code>response.end()</code>, the property is nulled.</p>
<pre class="with-48-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> http <span class="hljs-keyword">from</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-keyword">const</span> ip = res.<span class="hljs-property">socket</span>.<span class="hljs-property">remoteAddress</span>;
<span class="hljs-keyword">const</span> port = res.<span class="hljs-property">socket</span>.<span class="hljs-property">remotePort</span>;
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><code class="language-js cjs"><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-keyword">const</span> ip = res.<span class="hljs-property">socket</span>.<span class="hljs-property">remoteAddress</span>;
<span class="hljs-keyword">const</span> port = res.<span class="hljs-property">socket</span>.<span class="hljs-property">remotePort</span>;
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><button class="copy-button">copy</button></pre>
<p>This property is guaranteed to be an instance of the <a href="#all_net_class-netsocket" class="type"><net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>, unless the user specified a socket
type other than <a href="#all_net_class-netsocket" class="type"><net.Socket></a>.</p>
<h4><code>response.statusCode</code><span><a class="mark" href="#all_http_responsestatuscode" id="all_http_responsestatuscode">#</a></span><a aria-hidden="true" class="legacy" id="http_response_statuscode"></a></h4>
<div class="api_metadata">
<span>Added in: v0.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> <strong>Default:</strong> <code>200</code></li>
</ul>
<p>When using implicit headers (not calling <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> explicitly),
this property controls the status code that will be sent to the client when
the headers get flushed.</p>
<pre><code class="language-js">response.<span class="hljs-property">statusCode</span> = <span class="hljs-number">404</span>;</code> <button class="copy-button">copy</button></pre>
<p>After response header was sent to the client, this property indicates the
status code which was sent out.</p>
<h4><code>response.statusMessage</code><span><a class="mark" href="#all_http_responsestatusmessage" id="all_http_responsestatusmessage">#</a></span><a aria-hidden="true" class="legacy" id="http_response_statusmessage"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>When using implicit headers (not calling <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> explicitly),
this property controls the status message that will be sent to the client when
the headers get flushed. If this is left as <code>undefined</code> then the standard
message for the status code will be used.</p>
<pre><code class="language-js">response.<span class="hljs-property">statusMessage</span> = <span class="hljs-string">'Not found'</span>;</code> <button class="copy-button">copy</button></pre>
<p>After response header was sent to the client, this property indicates the
status message which was sent out.</p>
<h4><code>response.strictContentLength</code><span><a class="mark" href="#all_http_responsestrictcontentlength" id="all_http_responsestrictcontentlength">#</a></span><a aria-hidden="true" class="legacy" id="http_response_strictcontentlength"></a></h4>
<div class="api_metadata">
<span>Added in: v18.10.0, v16.18.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li>
</ul>
<p>If set to <code>true</code>, Node.js will check whether the <code>Content-Length</code>
header value and the size of the body, in bytes, are equal.
Mismatching the <code>Content-Length</code> header value will result
in an <code>Error</code> being thrown, identified by <code>code:</code> <a href="#all_errors_err_http_content_length_mismatch"><code>'ERR_HTTP_CONTENT_LENGTH_MISMATCH'</code></a>.</p>
<h4><code>response.uncork()</code><span><a class="mark" href="#all_http_responseuncork" id="all_http_responseuncork">#</a></span><a aria-hidden="true" class="legacy" id="http_response_uncork"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>See <a href="#all_stream_writableuncork"><code>writable.uncork()</code></a>.</p>
<h4><code>response.writableEnded</code><span><a class="mark" href="#all_http_responsewritableended" id="all_http_responsewritableended">#</a></span><a aria-hidden="true" class="legacy" id="http_response_writableended"></a></h4>
<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="#all_http_responseenddata-encoding-callback"><code>response.end()</code></a> has been called. This property
does not indicate whether the data has been flushed, for this use
<a href="#all_http_responsewritablefinished"><code>response.writableFinished</code></a> instead.</p>
<h4><code>response.writableFinished</code><span><a class="mark" href="#all_http_responsewritablefinished" id="all_http_responsewritablefinished">#</a></span><a aria-hidden="true" class="legacy" id="http_response_writablefinished"></a></h4>
<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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Is <code>true</code> if all data has been flushed to the underlying system, immediately
before the <a href="#all_http_event-finish"><code>'finish'</code></a> event is emitted.</p>
<h4><code>response.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#all_http_responsewritechunk-encoding-callback" id="all_http_responsewritechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_response_write_chunk_encoding_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>v15.0.0</td>
<td><p>The <code>chunk</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v0.1.29</td>
<td><p><span>Added in: v0.1.29</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="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></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> <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></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>If this method is called and <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> has not been called,
it will switch to implicit header mode and flush the implicit headers.</p>
<p>This sends a chunk of the response body. This method may
be called multiple times to provide successive parts of the body.</p>
<p>If <code>rejectNonStandardBodyWrites</code> is set to true in <code>createServer</code>
then writing to the body is not allowed when the request method or response
status do not support content. If an attempt is made to write to the body for a
HEAD request or as part of a <code>204</code> or <code>304</code>response, a synchronous <code>Error</code>
with the code <code>ERR_HTTP_BODY_NOT_ALLOWED</code> is thrown.</p>
<p><code>chunk</code> can be a string or a buffer. If <code>chunk</code> is a string,
the second parameter specifies how to encode it into a byte stream.
<code>callback</code> will be called when this chunk of data is flushed.</p>
<p>This is the raw HTTP body and has nothing to do with higher-level multi-part
body encodings that may be used.</p>
<p>The first time <a href="#all_http_responsewritechunk-encoding-callback"><code>response.write()</code></a> is called, it will send the buffered
header information and the first chunk of the body to the client. The second
time <a href="#all_http_responsewritechunk-encoding-callback"><code>response.write()</code></a> is called, Node.js assumes data will be streamed,
and sends the new data separately. That is, the response is buffered up to the
first chunk of the body.</p>
<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
buffer. Returns <code>false</code> if all or part of the data was queued in user memory.
<code>'drain'</code> will be emitted when the buffer is free again.</p>
<h4><code>response.writeContinue()</code><span><a class="mark" href="#all_http_responsewritecontinue" id="all_http_responsewritecontinue">#</a></span><a aria-hidden="true" class="legacy" id="http_response_writecontinue"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<p>Sends an HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the <a href="#all_http_event-checkcontinue"><code>'checkContinue'</code></a> event on
<code>Server</code>.</p>
<h4><code>response.writeEarlyHints(hints[, callback])</code><span><a class="mark" href="#all_http_responsewriteearlyhintshints-callback" id="all_http_responsewriteearlyhintshints-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_response_writeearlyhints_hints_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>v18.11.0</td>
<td><p>Allow passing hints as an object.</p></td></tr>
<tr><td>v18.11.0</td>
<td><p><span>Added in: v18.11.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>Sends an HTTP/1.1 103 Early Hints message to the client with a Link header,
indicating that the user agent can preload/preconnect the linked resources.
The <code>hints</code> is an object containing the values of headers to be sent with
early hints message. The optional <code>callback</code> argument will be called when
the response message has been written.</p>
<p><strong>Example</strong></p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> earlyHintsLink = <span class="hljs-string">'</styles.css>; rel=preload; as=style'</span>;
response.<span class="hljs-title function_">writeEarlyHints</span>({
<span class="hljs-string">'link'</span>: earlyHintsLink,
});
<span class="hljs-keyword">const</span> earlyHintsLinks = [
<span class="hljs-string">'</styles.css>; rel=preload; as=style'</span>,
<span class="hljs-string">'</scripts.js>; rel=preload; as=script'</span>,
];
response.<span class="hljs-title function_">writeEarlyHints</span>({
<span class="hljs-string">'link'</span>: earlyHintsLinks,
<span class="hljs-string">'x-trace-id'</span>: <span class="hljs-string">'id for diagnostics'</span>,
});
<span class="hljs-keyword">const</span> <span class="hljs-title function_">earlyHintsCallback</span> = (<span class="hljs-params"></span>) => <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'early hints message sent'</span>);
response.<span class="hljs-title function_">writeEarlyHints</span>({
<span class="hljs-string">'link'</span>: earlyHintsLinks,
}, earlyHintsCallback);</code> <button class="copy-button">copy</button></pre>
<h4><code>response.writeHead(statusCode[, statusMessage][, headers])</code><span><a class="mark" href="#all_http_responsewriteheadstatuscode-statusmessage-headers" id="all_http_responsewriteheadstatuscode-statusmessage-headers">#</a></span><a aria-hidden="true" class="legacy" id="http_response_writehead_statuscode_statusmessage_headers"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.14.0</td>
<td><p>Allow passing headers as an array.</p></td></tr>
<tr><td>v11.10.0, v10.17.0</td>
<td><p>Return <code>this</code> from <code>writeHead()</code> to allow chaining with <code>end()</code>.</p></td></tr>
<tr><td>v5.11.0, v4.4.5</td>
<td><p>A <code>RangeError</code> is thrown if <code>statusCode</code> is not a number in the range <code>[100, 999]</code>.</p></td></tr>
<tr><td>v0.1.30</td>
<td><p><span>Added in: v0.1.30</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>statusMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
<li>Returns: <a href="#all_http_class-httpserverresponse" class="type"><http.ServerResponse></a></li>
</ul>
<p>Sends a response header to the request. The status code is a 3-digit HTTP
status code, like <code>404</code>. The last argument, <code>headers</code>, are the response headers.
Optionally one can give a human-readable <code>statusMessage</code> as the second
argument.</p>
<p><code>headers</code> may be an <code>Array</code> where the keys and values are in the same list.
It is <em>not</em> a list of tuples. So, the even-numbered offsets are key values,
and the odd-numbered offsets are the associated values. The array is in the same
format as <code>request.rawHeaders</code>.</p>
<p>Returns a reference to the <code>ServerResponse</code>, so that calls can be chained.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> body = <span class="hljs-string">'hello world'</span>;
response
.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, {
<span class="hljs-string">'Content-Length'</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(body),
<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span>,
})
.<span class="hljs-title function_">end</span>(body);</code> <button class="copy-button">copy</button></pre>
<p>This method must only be called once on a message and it must
be called before <a href="#all_http_responseenddata-encoding-callback"><code>response.end()</code></a> is called.</p>
<p>If <a href="#all_http_responsewritechunk-encoding-callback"><code>response.write()</code></a> or <a href="#all_http_responseenddata-encoding-callback"><code>response.end()</code></a> are called before calling
this, the implicit/mutable headers will be calculated and call this function.</p>
<p>When headers have been set with <a href="#all_http_responsesetheadername-value"><code>response.setHeader()</code></a>, they will be merged
with any headers passed to <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a>, with the headers passed
to <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> given precedence.</p>
<p>If this method is called and <a href="#all_http_responsesetheadername-value"><code>response.setHeader()</code></a> has not been called,
it will directly write the supplied header values onto the network channel
without caching internally, and the <a href="#all_http_responsegetheadername"><code>response.getHeader()</code></a> on the header
will not yield the expected result. If progressive population of headers is
desired with potential future retrieval and modification, use
<a href="#all_http_responsesetheadername-value"><code>response.setHeader()</code></a> instead.</p>
<pre><code class="language-js"><span class="hljs-comment">// Returns content-type = text/plain</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> {
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>);
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p><code>Content-Length</code> is read in bytes, not characters. Use
<a href="#all_buffer_static-method-bufferbytelengthstring-encoding"><code>Buffer.byteLength()</code></a> to determine the length of the body in bytes. Node.js
will check whether <code>Content-Length</code> and the length of the body which has
been transmitted are equal or not.</p>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a [<code>Error</code>][] being thrown.</p>
<h4><code>response.writeProcessing()</code><span><a class="mark" href="#all_http_responsewriteprocessing" id="all_http_responsewriteprocessing">#</a></span><a aria-hidden="true" class="legacy" id="http_response_writeprocessing"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>Sends a HTTP/1.1 102 Processing message to the client, indicating that
the request body should be sent.</p>
</section><section><h3>Class: <code>http.IncomingMessage</code><span><a class="mark" href="#all_http_class-httpincomingmessage" id="all_http_class-httpincomingmessage">#</a></span><a aria-hidden="true" class="legacy" id="http_class_http_incomingmessage"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.5.0</td>
<td><p>The <code>destroyed</code> value returns <code>true</code> after the incoming data is consumed.</p></td></tr>
<tr><td>v13.1.0, v12.16.0</td>
<td><p>The <code>readableHighWaterMark</code> value mirrors that of the socket.</p></td></tr>
<tr><td>v0.1.17</td>
<td><p><span>Added in: v0.1.17</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a></li>
</ul>
<p>An <code>IncomingMessage</code> object is created by <a href="#all_http_class-httpserver"><code>http.Server</code></a> or
<a href="#all_http_class-httpclientrequest"><code>http.ClientRequest</code></a> and passed as the first argument to the <a href="#all_http_event-request"><code>'request'</code></a>
and <a href="#all_http_event-response"><code>'response'</code></a> event respectively. It may be used to access response
status, headers, and data.</p>
<p>Different from its <code>socket</code> value which is a subclass of <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>, the
<code>IncomingMessage</code> itself extends <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a> and is created separately to
parse and emit the incoming HTTP headers and payload, as the underlying socket
may be reused multiple times in case of keep-alive.</p>
<h4>Event: <code>'aborted'</code><span><a class="mark" href="#all_http_event-aborted" id="all_http_event-aborted">#</a></span><a aria-hidden="true" class="legacy" id="http_event_aborted"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.8</span><span>Deprecated since: v17.0.0, v16.12.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Listen for <code>'close'</code> event instead.</div><p></p>
<p>Emitted when the request has been aborted.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_http_event-close_3" id="all_http_event-close_3">#</a></span><a aria-hidden="true" class="legacy" id="http_event_close_3"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>The close event is now emitted when the request has been completed and not when the underlying socket is closed.</p></td></tr>
<tr><td>v0.4.2</td>
<td><p><span>Added in: v0.4.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Emitted when the request has been completed.</p>
<h4><code>message.aborted</code><span><a class="mark" href="#all_http_messageaborted" id="all_http_messageaborted">#</a></span><a aria-hidden="true" class="legacy" id="http_message_aborted"></a></h4>
<div class="api_metadata">
<span>Added in: v10.1.0</span><span>Deprecated since: v17.0.0, v16.12.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Check <code>message.destroyed</code> from <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a>.</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>The <code>message.aborted</code> property will be <code>true</code> if the request has
been aborted.</p>
<h4><code>message.complete</code><span><a class="mark" href="#all_http_messagecomplete" id="all_http_messagecomplete">#</a></span><a aria-hidden="true" class="legacy" id="http_message_complete"></a></h4>
<div class="api_metadata">
<span>Added in: v0.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>The <code>message.complete</code> property will be <code>true</code> if a complete HTTP message has
been received and successfully parsed.</p>
<p>This property is particularly useful as a means of determining if a client or
server fully transmitted a message before a connection was terminated:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>({
<span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">8080</span>,
<span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
}, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
res.<span class="hljs-title function_">resume</span>();
res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">if</span> (!res.<span class="hljs-property">complete</span>)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(
<span class="hljs-string">'The connection was terminated while the message was still being sent'</span>);
});
});</code> <button class="copy-button">copy</button></pre>
<h4><code>message.connection</code><span><a class="mark" href="#all_http_messageconnection" id="all_http_messageconnection">#</a></span><a aria-hidden="true" class="legacy" id="http_message_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span><span>Deprecated since: v16.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http_messagesocket"><code>message.socket</code></a>.</div><p></p>
<p>Alias for <a href="#all_http_messagesocket"><code>message.socket</code></a>.</p>
<h4><code>message.destroy([error])</code><span><a class="mark" href="#all_http_messagedestroyerror" id="all_http_messagedestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="http_message_destroy_error"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>The function returns <code>this</code> for consistency with other Readable streams.</p></td></tr>
<tr><td>v0.3.0</td>
<td><p><span>Added in: v0.3.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>Calls <code>destroy()</code> on the socket that received the <code>IncomingMessage</code>. If <code>error</code>
is provided, an <code>'error'</code> event is emitted on the socket and <code>error</code> is passed
as an argument to any listeners on the event.</p>
<h4><code>message.headers</code><span><a class="mark" href="#all_http_messageheaders" id="all_http_messageheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_message_headers"></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>The <code>joinDuplicateHeaders</code> option in the <code>http.request()</code> and <code>http.createServer()</code> functions ensures that duplicate headers are not discarded, but rather combined using a comma separator, in accordance with RFC 9110 Section 5.3.</p></td></tr>
<tr><td>v15.1.0</td>
<td><p><code>message.headers</code> is now lazily computed using an accessor property on the prototype and is no longer enumerable.</p></td></tr>
<tr><td>v0.1.5</td>
<td><p><span>Added in: v0.1.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The request/response headers object.</p>
<p>Key-value pairs of header names and values. Header names are lower-cased.</p>
<pre><code class="language-js"><span class="hljs-comment">// Prints something like:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// { 'user-agent': 'curl/7.22.0',</span>
<span class="hljs-comment">// host: '127.0.0.1:8000',</span>
<span class="hljs-comment">// accept: '*/*' }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(request.<span class="hljs-property">headers</span>);</code> <button class="copy-button">copy</button></pre>
<p>Duplicates in raw headers are handled in the following ways, depending on the
header name:</p>
<ul>
<li>Duplicates of <code>age</code>, <code>authorization</code>, <code>content-length</code>, <code>content-type</code>,
<code>etag</code>, <code>expires</code>, <code>from</code>, <code>host</code>, <code>if-modified-since</code>, <code>if-unmodified-since</code>,
<code>last-modified</code>, <code>location</code>, <code>max-forwards</code>, <code>proxy-authorization</code>, <code>referer</code>,
<code>retry-after</code>, <code>server</code>, or <code>user-agent</code> are discarded.
To allow duplicate values of the headers listed above to be joined,
use the option <code>joinDuplicateHeaders</code> in <a href="#all_http_httprequestoptions-callback"><code>http.request()</code></a>
and <a href="#all_http_httpcreateserveroptions-requestlistener"><code>http.createServer()</code></a>. See RFC 9110 Section 5.3 for more
information.</li>
<li><code>set-cookie</code> is always an array. Duplicates are added to the array.</li>
<li>For duplicate <code>cookie</code> headers, the values are joined together with <code>; </code>.</li>
<li>For all other headers, the values are joined together with <code>, </code>.</li>
</ul>
<h4><code>message.headersDistinct</code><span><a class="mark" href="#all_http_messageheadersdistinct" id="all_http_messageheadersdistinct">#</a></span><a aria-hidden="true" class="legacy" id="http_message_headersdistinct"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Similar to <a href="#all_http_messageheaders"><code>message.headers</code></a>, but there is no join logic and the values are
always arrays of strings, even for headers received just once.</p>
<pre><code class="language-js"><span class="hljs-comment">// Prints something like:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// { 'user-agent': ['curl/7.22.0'],</span>
<span class="hljs-comment">// host: ['127.0.0.1:8000'],</span>
<span class="hljs-comment">// accept: ['*/*'] }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(request.<span class="hljs-property">headersDistinct</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>message.httpVersion</code><span><a class="mark" href="#all_http_messagehttpversion" id="all_http_messagehttpversion">#</a></span><a aria-hidden="true" class="legacy" id="http_message_httpversion"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.1</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>In case of server request, the HTTP version sent by the client. In the case of
client response, the HTTP version of the connected-to server.
Probably either <code>'1.1'</code> or <code>'1.0'</code>.</p>
<p>Also <code>message.httpVersionMajor</code> is the first integer and
<code>message.httpVersionMinor</code> is the second.</p>
<h4><code>message.method</code><span><a class="mark" href="#all_http_messagemethod" id="all_http_messagemethod">#</a></span><a aria-hidden="true" class="legacy" id="http_message_method"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.1</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p><strong>Only valid for request obtained from <a href="#all_http_class-httpserver"><code>http.Server</code></a>.</strong></p>
<p>The request method as a string. Read only. Examples: <code>'GET'</code>, <code>'DELETE'</code>.</p>
<h4><code>message.rawHeaders</code><span><a class="mark" href="#all_http_messagerawheaders" id="all_http_messagerawheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_message_rawheaders"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.6</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>The raw request/response headers list exactly as they were received.</p>
<p>The keys and values are in the same list. It is <em>not</em> a
list of tuples. So, the even-numbered offsets are key values, and the
odd-numbered offsets are the associated values.</p>
<p>Header names are not lowercased, and duplicates are not merged.</p>
<pre><code class="language-js"><span class="hljs-comment">// Prints something like:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// [ 'user-agent',</span>
<span class="hljs-comment">// 'this is invalid because there can be only one',</span>
<span class="hljs-comment">// 'User-Agent',</span>
<span class="hljs-comment">// 'curl/7.22.0',</span>
<span class="hljs-comment">// 'Host',</span>
<span class="hljs-comment">// '127.0.0.1:8000',</span>
<span class="hljs-comment">// 'ACCEPT',</span>
<span class="hljs-comment">// '*/*' ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(request.<span class="hljs-property">rawHeaders</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>message.rawTrailers</code><span><a class="mark" href="#all_http_messagerawtrailers" id="all_http_messagerawtrailers">#</a></span><a aria-hidden="true" class="legacy" id="http_message_rawtrailers"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.6</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>The raw request/response trailer keys and values exactly as they were
received. Only populated at the <code>'end'</code> event.</p>
<h4><code>message.setTimeout(msecs[, callback])</code><span><a class="mark" href="#all_http_messagesettimeoutmsecs-callback" id="all_http_messagesettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_message_settimeout_msecs_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div>
<ul>
<li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a></li>
</ul>
<p>Calls <code>message.socket.setTimeout(msecs, callback)</code>.</p>
<h4><code>message.socket</code><span><a class="mark" href="#all_http_messagesocket" id="all_http_messagesocket">#</a></span><a aria-hidden="true" class="legacy" id="http_message_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>The <a href="#all_net_class-netsocket"><code>net.Socket</code></a> object associated with the connection.</p>
<p>With HTTPS support, use <a href="#all_tls_tlssocketgetpeercertificatedetailed"><code>request.socket.getPeerCertificate()</code></a> to obtain the
client's authentication details.</p>
<p>This property is guaranteed to be an instance of the <a href="#all_net_class-netsocket" class="type"><net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>, unless the user specified a socket
type other than <a href="#all_net_class-netsocket" class="type"><net.Socket></a> or internally nulled.</p>
<h4><code>message.statusCode</code><span><a class="mark" href="#all_http_messagestatuscode" id="all_http_messagestatuscode">#</a></span><a aria-hidden="true" class="legacy" id="http_message_statuscode"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.1</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><strong>Only valid for response obtained from <a href="#all_http_class-httpclientrequest"><code>http.ClientRequest</code></a>.</strong></p>
<p>The 3-digit HTTP response status code. E.G. <code>404</code>.</p>
<h4><code>message.statusMessage</code><span><a class="mark" href="#all_http_messagestatusmessage" id="all_http_messagestatusmessage">#</a></span><a aria-hidden="true" class="legacy" id="http_message_statusmessage"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.10</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p><strong>Only valid for response obtained from <a href="#all_http_class-httpclientrequest"><code>http.ClientRequest</code></a>.</strong></p>
<p>The HTTP response status message (reason phrase). E.G. <code>OK</code> or <code>Internal Server Error</code>.</p>
<h4><code>message.trailers</code><span><a class="mark" href="#all_http_messagetrailers" id="all_http_messagetrailers">#</a></span><a aria-hidden="true" class="legacy" id="http_message_trailers"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The request/response trailers object. Only populated at the <code>'end'</code> event.</p>
<h4><code>message.trailersDistinct</code><span><a class="mark" href="#all_http_messagetrailersdistinct" id="all_http_messagetrailersdistinct">#</a></span><a aria-hidden="true" class="legacy" id="http_message_trailersdistinct"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Similar to <a href="#all_http_messagetrailers"><code>message.trailers</code></a>, but there is no join logic and the values are
always arrays of strings, even for headers received just once.
Only populated at the <code>'end'</code> event.</p>
<h4><code>message.url</code><span><a class="mark" href="#all_http_messageurl" id="all_http_messageurl">#</a></span><a aria-hidden="true" class="legacy" id="http_message_url"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p><strong>Only valid for request obtained from <a href="#all_http_class-httpserver"><code>http.Server</code></a>.</strong></p>
<p>Request URL string. This contains only the URL that is present in the actual
HTTP request. Take the following request:</p>
<pre><code class="language-http"><span class="hljs-keyword">GET</span> <span class="hljs-string">/status?name=ryan</span> <span class="hljs-meta">HTTP/1.1</span>
<span class="hljs-attribute">Accept</span><span class="hljs-punctuation">: </span>text/plain</code> <button class="copy-button">copy</button></pre>
<p>To parse the URL into its parts:</p>
<pre><code class="language-js"><span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`http://<span class="hljs-subst">${process.env.HOST ?? <span class="hljs-string">'localhost'</span>}</span><span class="hljs-subst">${request.url}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<p>When <code>request.url</code> is <code>'/status?name=ryan'</code> and <code>process.env.HOST</code> is undefined:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">new URL(`http://<span class="hljs-variable">${process.env.HOST ?? 'localhost'}</span><span class="hljs-variable">${request.url}</span>`);</span>
URL {
href: 'http://localhost/status?name=ryan',
origin: 'http://localhost',
protocol: 'http:',
username: '',
password: '',
host: 'localhost',
hostname: 'localhost',
port: '',
pathname: '/status',
search: '?name=ryan',
searchParams: URLSearchParams { 'name' => 'ryan' },
hash: ''
}</code> <button class="copy-button">copy</button></pre>
<p>Ensure that you set <code>process.env.HOST</code> to the server's host name, or consider
replacing this part entirely. If using <code>req.headers.host</code>, ensure proper
validation is used, as clients may specify a custom <code>Host</code> header.</p>
</section><section><h3>Class: <code>http.OutgoingMessage</code><span><a class="mark" href="#all_http_class-httpoutgoingmessage" id="all_http_class-httpoutgoingmessage">#</a></span><a aria-hidden="true" class="legacy" id="http_class_http_outgoingmessage"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_stream" class="type"><Stream></a></li>
</ul>
<p>This class serves as the parent class of <a href="#all_http_class-httpclientrequest"><code>http.ClientRequest</code></a>
and <a href="#all_http_class-httpserverresponse"><code>http.ServerResponse</code></a>. It is an abstract outgoing message from
the perspective of the participants of an HTTP transaction.</p>
<h4>Event: <code>'drain'</code><span><a class="mark" href="#all_http_event-drain" id="all_http_event-drain">#</a></span><a aria-hidden="true" class="legacy" id="http_event_drain"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div>
<p>Emitted when the buffer of the message is free again.</p>
<h4>Event: <code>'finish'</code><span><a class="mark" href="#all_http_event-finish_2" id="all_http_event-finish_2">#</a></span><a aria-hidden="true" class="legacy" id="http_event_finish_2"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<p>Emitted when the transmission is finished successfully.</p>
<h4>Event: <code>'prefinish'</code><span><a class="mark" href="#all_http_event-prefinish" id="all_http_event-prefinish">#</a></span><a aria-hidden="true" class="legacy" id="http_event_prefinish"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.6</span>
</div>
<p>Emitted after <code>outgoingMessage.end()</code> is called.
When the event is emitted, all data has been processed but not necessarily
completely flushed.</p>
<h4><code>outgoingMessage.addTrailers(headers)</code><span><a class="mark" href="#all_http_outgoingmessageaddtrailersheaders" id="all_http_outgoingmessageaddtrailersheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_addtrailers_headers"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Adds HTTP trailers (headers but at the end of the message) to the message.</p>
<p>Trailers will <strong>only</strong> be emitted if the message is chunked encoded. If not,
the trailers will be silently discarded.</p>
<p>HTTP requires the <code>Trailer</code> header to be sent to emit trailers,
with a list of header field names in its value, e.g.</p>
<pre><code class="language-js">message.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span>,
<span class="hljs-string">'Trailer'</span>: <span class="hljs-string">'Content-MD5'</span> });
message.<span class="hljs-title function_">write</span>(fileData);
message.<span class="hljs-title function_">addTrailers</span>({ <span class="hljs-string">'Content-MD5'</span>: <span class="hljs-string">'7895bf4b8828b55ceaf47747b4bca667'</span> });
message.<span class="hljs-title function_">end</span>();</code> <button class="copy-button">copy</button></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <code>TypeError</code> being thrown.</p>
<h4><code>outgoingMessage.appendHeader(name, value)</code><span><a class="mark" href="#all_http_outgoingmessageappendheadername-value" id="all_http_outgoingmessageappendheadername-value">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_appendheader_name_value"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Header name</li>
<li><code>value</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#String_type" class="type"><string[]></a> Header value</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>Append a single header value to the header object.</p>
<p>If the value is an array, this is equivalent to calling this method multiple
times.</p>
<p>If there were no previous values for the header, this is equivalent to calling
<a href="#all_http_outgoingmessagesetheadername-value"><code>outgoingMessage.setHeader(name, value)</code></a>.</p>
<p>Depending of the value of <code>options.uniqueHeaders</code> when the client request or the
server were created, this will end up in the header being sent multiple times or
a single time with values joined using <code>; </code>.</p>
<h4><code>outgoingMessage.connection</code><span><a class="mark" href="#all_http_outgoingmessageconnection" id="all_http_outgoingmessageconnection">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span><span>Deprecated since: v15.12.0, v14.17.1</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_http_outgoingmessagesocket"><code>outgoingMessage.socket</code></a> instead.</div><p></p>
<p>Alias of <a href="#all_http_outgoingmessagesocket"><code>outgoingMessage.socket</code></a>.</p>
<h4><code>outgoingMessage.cork()</code><span><a class="mark" href="#all_http_outgoingmessagecork" id="all_http_outgoingmessagecork">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_cork"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>See <a href="#all_stream_writablecork"><code>writable.cork()</code></a>.</p>
<h4><code>outgoingMessage.destroy([error])</code><span><a class="mark" href="#all_http_outgoingmessagedestroyerror" id="all_http_outgoingmessagedestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_destroy_error"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</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>Destroys the message. Once a socket is associated with the message
and is connected, that socket will be destroyed as well.</p>
<h4><code>outgoingMessage.end(chunk[, encoding][, callback])</code><span><a class="mark" href="#all_http_outgoingmessageendchunk-encoding-callback" id="all_http_outgoingmessageendchunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_end_chunk_encoding_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>v15.0.0</td>
<td><p>The <code>chunk</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v0.11.6</td>
<td><p>add <code>callback</code> argument.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</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="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></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> Optional, <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> Optional</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>Finishes the outgoing message. If any parts of the body are unsent, it will
flush them to the underlying system. If the message is chunked, it will
send the terminating chunk <code>0\r\n\r\n</code>, and send the trailers (if any).</p>
<p>If <code>chunk</code> is specified, it is equivalent to calling
<code>outgoingMessage.write(chunk, encoding)</code>, followed by
<code>outgoingMessage.end(callback)</code>.</p>
<p>If <code>callback</code> is provided, it will be called when the message is finished
(equivalent to a listener of the <code>'finish'</code> event).</p>
<h4><code>outgoingMessage.flushHeaders()</code><span><a class="mark" href="#all_http_outgoingmessageflushheaders" id="all_http_outgoingmessageflushheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_flushheaders"></a></h4>
<div class="api_metadata">
<span>Added in: v1.6.0</span>
</div>
<p>Flushes the message headers.</p>
<p>For efficiency reason, Node.js normally buffers the message headers
until <code>outgoingMessage.end()</code> is called or the first chunk of message data
is written. It then tries to pack the headers and data into a single TCP
packet.</p>
<p>It is usually desired (it saves a TCP round-trip), but not when the first
data is not sent until possibly much later. <code>outgoingMessage.flushHeaders()</code>
bypasses the optimization and kickstarts the message.</p>
<h4><code>outgoingMessage.getHeader(name)</code><span><a class="mark" href="#all_http_outgoingmessagegetheadername" id="all_http_outgoingmessagegetheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_getheader_name"></a></h4>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of header</li>
<li>Returns: <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#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>Gets the value of the HTTP header with the given name. If that header is not
set, the returned value will be <code>undefined</code>.</p>
<h4><code>outgoingMessage.getHeaderNames()</code><span><a class="mark" href="#all_http_outgoingmessagegetheadernames" id="all_http_outgoingmessagegetheadernames">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_getheadernames"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>Returns an array containing the unique names of the current outgoing headers.
All names are lowercase.</p>
<h4><code>outgoingMessage.getHeaders()</code><span><a class="mark" href="#all_http_outgoingmessagegetheaders" id="all_http_outgoingmessagegetheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_getheaders"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns a shallow copy of the current outgoing headers. Since a shallow
copy is used, array values may be mutated without additional calls to
various header-related HTTP module methods. The keys of the returned
object are the header names and the values are the respective header
values. All header names are lowercase.</p>
<p>The object returned by the <code>outgoingMessage.getHeaders()</code> method does
not prototypically inherit from the JavaScript <code>Object</code>. This means that
typical <code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>,
and others are not defined and will not work.</p>
<pre><code class="language-js">outgoingMessage.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
outgoingMessage.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);
<span class="hljs-keyword">const</span> headers = outgoingMessage.<span class="hljs-title function_">getHeaders</span>();
<span class="hljs-comment">// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }</span></code> <button class="copy-button">copy</button></pre>
<h4><code>outgoingMessage.hasHeader(name)</code><span><a class="mark" href="#all_http_outgoingmessagehasheadername" id="all_http_outgoingmessagehasheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_hasheader_name"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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 <code>true</code> if the header identified by <code>name</code> is currently set in the
outgoing headers. The header name is case-insensitive.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> hasContentType = outgoingMessage.<span class="hljs-title function_">hasHeader</span>(<span class="hljs-string">'content-type'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>outgoingMessage.headersSent</code><span><a class="mark" href="#all_http_outgoingmessageheaderssent" id="all_http_outgoingmessageheaderssent">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_headerssent"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.3</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>Read-only. <code>true</code> if the headers were sent, otherwise <code>false</code>.</p>
<h4><code>outgoingMessage.pipe()</code><span><a class="mark" href="#all_http_outgoingmessagepipe" id="all_http_outgoingmessagepipe">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_pipe"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span>
</div>
<p>Overrides the <code>stream.pipe()</code> method inherited from the legacy <code>Stream</code> class
which is the parent class of <code>http.OutgoingMessage</code>.</p>
<p>Calling this method will throw an <code>Error</code> because <code>outgoingMessage</code> is a
write-only stream.</p>
<h4><code>outgoingMessage.removeHeader(name)</code><span><a class="mark" href="#all_http_outgoingmessageremoveheadername" id="all_http_outgoingmessageremoveheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_removeheader_name"></a></h4>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Header name</li>
</ul>
<p>Removes a header that is queued for implicit sending.</p>
<pre><code class="language-js">outgoingMessage.<span class="hljs-title function_">removeHeader</span>(<span class="hljs-string">'Content-Encoding'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>outgoingMessage.setHeader(name, value)</code><span><a class="mark" href="#all_http_outgoingmessagesetheadername-value" id="all_http_outgoingmessagesetheadername-value">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_setheader_name_value"></a></h4>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Header name</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Header value</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>Sets a single header value. If the header already exists in the to-be-sent
headers, its value will be replaced. Use an array of strings to send multiple
headers with the same name.</p>
<h4><code>outgoingMessage.setHeaders(headers)</code><span><a class="mark" href="#all_http_outgoingmessagesetheadersheaders" id="all_http_outgoingmessagesetheadersheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_setheaders_headers"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/Headers" class="type"><Headers></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type"><Map></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>Sets multiple header values for implicit headers.
<code>headers</code> must be an instance of <a href="#all_globals_class-headers"><code>Headers</code></a> or <code>Map</code>,
if a header already exists in the to-be-sent headers,
its value will be replaced.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> headers = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Headers</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span> });
outgoingMessage.<span class="hljs-title function_">setHeaders</span>(headers);</code> <button class="copy-button">copy</button></pre>
<p>or</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> headers = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>([[<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>]]);
outgoingMessage.<span class="hljs-title function_">setHeaders</span>(headers);</code> <button class="copy-button">copy</button></pre>
<p>When headers have been set with <a href="#all_http_outgoingmessagesetheadersheaders"><code>outgoingMessage.setHeaders()</code></a>,
they will be merged with any headers passed to <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a>,
with the headers passed to <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="language-js"><span class="hljs-comment">// Returns content-type = text/plain</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> headers = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Headers</span>({ <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/html'</span> });
res.<span class="hljs-title function_">setHeaders</span>(headers);
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>outgoingMessage.setTimeout(msesc[, callback])</code><span><a class="mark" href="#all_http_outgoingmessagesettimeoutmsesc-callback" id="all_http_outgoingmessagesettimeoutmsesc-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_settimeout_msesc_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.12</span>
</div>
<ul>
<li><code>msesc</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Optional function to be called when a timeout
occurs. Same as binding to the <code>timeout</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>Once a socket is associated with the message and is connected,
<a href="#all_net_socketsettimeouttimeout-callback"><code>socket.setTimeout()</code></a> will be called with <code>msecs</code> as the first parameter.</p>
<h4><code>outgoingMessage.socket</code><span><a class="mark" href="#all_http_outgoingmessagesocket" id="all_http_outgoingmessagesocket">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>Reference to the underlying socket. Usually, users will not want to access
this property.</p>
<p>After calling <code>outgoingMessage.end()</code>, this property will be nulled.</p>
<h4><code>outgoingMessage.uncork()</code><span><a class="mark" href="#all_http_outgoingmessageuncork" id="all_http_outgoingmessageuncork">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_uncork"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>See <a href="#all_stream_writableuncork"><code>writable.uncork()</code></a></p>
<h4><code>outgoingMessage.writableCorked</code><span><a class="mark" href="#all_http_outgoingmessagewritablecorked" id="all_http_outgoingmessagewritablecorked">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_writablecorked"></a></h4>
<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"><number></a></li>
</ul>
<p>The number of times <code>outgoingMessage.cork()</code> has been called.</p>
<h4><code>outgoingMessage.writableEnded</code><span><a class="mark" href="#all_http_outgoingmessagewritableended" id="all_http_outgoingmessagewritableended">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_writableended"></a></h4>
<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> if <code>outgoingMessage.end()</code> has been called. This property does
not indicate whether the data has been flushed. For that purpose, use
<code>message.writableFinished</code> instead.</p>
<h4><code>outgoingMessage.writableFinished</code><span><a class="mark" href="#all_http_outgoingmessagewritablefinished" id="all_http_outgoingmessagewritablefinished">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_writablefinished"></a></h4>
<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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Is <code>true</code> if all data has been flushed to the underlying system.</p>
<h4><code>outgoingMessage.writableHighWaterMark</code><span><a class="mark" href="#all_http_outgoingmessagewritablehighwatermark" id="all_http_outgoingmessagewritablehighwatermark">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_writablehighwatermark"></a></h4>
<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#Number_type" class="type"><number></a></li>
</ul>
<p>The <code>highWaterMark</code> of the underlying socket if assigned. Otherwise, the default
buffer level when <a href="#all_stream_writablewritechunk-encoding-callback"><code>writable.write()</code></a> starts returning false (<code>16384</code>).</p>
<h4><code>outgoingMessage.writableLength</code><span><a class="mark" href="#all_http_outgoingmessagewritablelength" id="all_http_outgoingmessagewritablelength">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_writablelength"></a></h4>
<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#Number_type" class="type"><number></a></li>
</ul>
<p>The number of buffered bytes.</p>
<h4><code>outgoingMessage.writableObjectMode</code><span><a class="mark" href="#all_http_outgoingmessagewritableobjectmode" id="all_http_outgoingmessagewritableobjectmode">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_writableobjectmode"></a></h4>
<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>Always <code>false</code>.</p>
<h4><code>outgoingMessage.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#all_http_outgoingmessagewritechunk-encoding-callback" id="all_http_outgoingmessagewritechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_write_chunk_encoding_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>v15.0.0</td>
<td><p>The <code>chunk</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v0.11.6</td>
<td><p>The <code>callback</code> argument was added.</p></td></tr>
<tr><td>v0.1.29</td>
<td><p><span>Added in: v0.1.29</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="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></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> <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></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>Sends a chunk of the body. This method can be called multiple times.</p>
<p>The <code>encoding</code> argument is only relevant when <code>chunk</code> is a string. Defaults to
<code>'utf8'</code>.</p>
<p>The <code>callback</code> argument is optional and will be called when this chunk of data
is flushed.</p>
<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
buffer. Returns <code>false</code> if all or part of the data was queued in the user
memory. The <code>'drain'</code> event will be emitted when the buffer is free again.</p>
</section><section><h3><code>http.METHODS</code><span><a class="mark" href="#all_http_httpmethods" id="all_http_httpmethods">#</a></span><a aria-hidden="true" class="legacy" id="http_http_methods"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>A list of the HTTP methods that are supported by the parser.</p>
</section><section><h3><code>http.STATUS_CODES</code><span><a class="mark" href="#all_http_httpstatus_codes" id="all_http_httpstatus_codes">#</a></span><a aria-hidden="true" class="legacy" id="http_http_status_codes"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.22</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>A collection of all the standard HTTP response status codes, and the
short description of each. For example, <code>http.STATUS_CODES[404] === 'Not Found'</code>.</p>
</section><section><h3><code>http.createServer([options][, requestListener])</code><span><a class="mark" href="#all_http_httpcreateserveroptions-requestlistener" id="all_http_httpcreateserveroptions-requestlistener">#</a></span><a aria-hidden="true" class="legacy" id="http_http_createserver_options_requestlistener"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>The <code>highWaterMark</code> option is supported now.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>requestTimeout</code>, <code>headersTimeout</code>, <code>keepAliveTimeout</code>, and <code>connectionsCheckingInterval</code> options are supported now.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>noDelay</code> option now defaults to <code>true</code>.</p></td></tr>
<tr><td>v17.7.0, v16.15.0</td>
<td><p>The <code>noDelay</code>, <code>keepAlive</code> and <code>keepAliveInitialDelay</code> options are supported now.</p></td></tr>
<tr><td>v13.3.0</td>
<td><p>The <code>maxHeaderSize</code> option is supported now.</p></td></tr>
<tr><td>v13.8.0, v12.15.0, v10.19.0</td>
<td><p>The <code>insecureHTTPParser</code> option is supported now.</p></td></tr>
<tr><td>v9.6.0, v8.12.0</td>
<td><p>The <code>options</code> argument is supported now.</p></td></tr>
<tr><td>v0.1.13</td>
<td><p><span>Added in: v0.1.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p>
<ul>
<li><code>connectionsCheckingInterval</code>: Sets the interval value in milliseconds to
check for request and headers timeout in incomplete requests.
<strong>Default:</strong> <code>30000</code>.</li>
<li><code>headersTimeout</code>: Sets the timeout value in milliseconds for receiving
the complete HTTP headers from the client.
See <a href="#all_http_serverheaderstimeout"><code>server.headersTimeout</code></a> for more information.
<strong>Default:</strong> <code>60000</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> Optionally overrides all <code>socket</code>s'
<code>readableHighWaterMark</code> and <code>writableHighWaterMark</code>. This affects
<code>highWaterMark</code> property of both <code>IncomingMessage</code> and <code>ServerResponse</code>.
<strong>Default:</strong> See <a href="#all_stream_streamgetdefaulthighwatermarkobjectmode"><code>stream.getDefaultHighWaterMark()</code></a>.</li>
<li><code>insecureHTTPParser</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, it will use a HTTP parser
with leniency flags enabled. Using the insecure parser should be avoided.
See <a href="#all_cli_--insecure-http-parser"><code>--insecure-http-parser</code></a> for more information.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>IncomingMessage</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a> Specifies the <code>IncomingMessage</code>
class to be used. Useful for extending the original <code>IncomingMessage</code>.
<strong>Default:</strong> <code>IncomingMessage</code>.</li>
<li><code>joinDuplicateHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, this option allows
joining the field line values of multiple headers in a request with
a comma (<code>, </code>) instead of discarding the duplicates.
For more information, refer to <a href="#all_http_messageheaders"><code>message.headers</code></a>.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>keepAlive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, it enables keep-alive functionality
on the socket immediately after a new incoming connection is received,
similarly on what is done in [<code>socket.setKeepAlive([enable][, initialDelay])</code>][<code>socket.setKeepAlive(enable, initialDelay)</code>].
<strong>Default:</strong> <code>false</code>.</li>
<li><code>keepAliveInitialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If set to a positive number, it sets the
initial delay before the first keepalive probe is sent on an idle socket.
<strong>Default:</strong> <code>0</code>.</li>
<li><code>keepAliveTimeout</code>: The number of milliseconds of inactivity a server
needs to wait for additional incoming data, after it has finished writing
the last response, before a socket will be destroyed.
See <a href="#all_http_serverkeepalivetimeout"><code>server.keepAliveTimeout</code></a> for more information.
<strong>Default:</strong> <code>5000</code>.</li>
<li><code>maxHeaderSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optionally overrides the value of
<a href="#all_cli_--max-http-header-sizesize"><code>--max-http-header-size</code></a> for requests received by this server, i.e.
the maximum length of request headers in bytes.
<strong>Default:</strong> 16384 (16 KiB).</li>
<li><code>noDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, it disables the use of Nagle's
algorithm immediately after a new incoming connection is received.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>requestTimeout</code>: Sets the timeout value in milliseconds for receiving
the entire request from the client.
See <a href="#all_http_serverrequesttimeout"><code>server.requestTimeout</code></a> for more information.
<strong>Default:</strong> <code>300000</code>.</li>
<li><code>requireHostHeader</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, it forces the server to
respond with a 400 (Bad Request) status code to any HTTP/1.1
request message that lacks a Host header
(as mandated by the specification).
<strong>Default:</strong> <code>true</code>.</li>
<li><code>ServerResponse</code> <a href="#all_http_class-httpserverresponse" class="type"><http.ServerResponse></a> Specifies the <code>ServerResponse</code> class
to be used. Useful for extending the original <code>ServerResponse</code>. <strong>Default:</strong>
<code>ServerResponse</code>.</li>
<li><code>uniqueHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> A list of response headers that should be sent only
once. If the header's value is an array, the items will be joined
using <code>; </code>.</li>
<li><code>rejectNonStandardBodyWrites</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, an error is thrown
when writing to an HTTP response which does not have a body.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>
<p><code>requestListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p>
</li>
<li>
<p>Returns: <a href="#all_http_class-httpserver" class="type"><http.Server></a></p>
</li>
</ul>
<p>Returns a new instance of <a href="#all_http_class-httpserver"><code>http.Server</code></a>.</p>
<p>The <code>requestListener</code> is a function which is automatically
added to the <a href="#all_http_event-request"><code>'request'</code></a> event.</p>
<pre class="with-34-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> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-comment">// Create a local server to receive data from</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> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
<span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
}));
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-comment">// Create a local server to receive data from</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> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
<span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
}));
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>
<pre class="with-34-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> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-comment">// Create a local server to receive data from</span>
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>();
<span class="hljs-comment">// Listen to the request event</span>
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'request'</span>, <span class="hljs-function">(<span class="hljs-params">request, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
<span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
}));
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-comment">// Create a local server to receive data from</span>
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>();
<span class="hljs-comment">// Listen to the request event</span>
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'request'</span>, <span class="hljs-function">(<span class="hljs-params">request, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
<span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
}));
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>http.get(options[, callback])</code><span><a class="mark" href="#all_http_httpgetoptions-callback" id="all_http_httpgetoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_http_get_options_callback"></a></h3>
</section><section><h3><code>http.get(url[, options][, callback])</code><span><a class="mark" href="#all_http_httpgeturl-options-callback" id="all_http_httpgeturl-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_http_get_url_options_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr>
<tr><td>v7.5.0</td>
<td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr>
<tr><td>v0.3.6</td>
<td><p><span>Added in: v0.3.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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> Accepts the same <code>options</code> as
<a href="#all_http_httprequestoptions-callback"><code>http.request()</code></a>, with the method set to GET by default.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_http_class-httpclientrequest" class="type"><http.ClientRequest></a></li>
</ul>
<p>Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and
<a href="#all_http_httprequestoptions-callback"><code>http.request()</code></a> is that it sets the method to GET by default and calls <code>req.end()</code>
automatically. The callback must take care to consume the response
data for reasons stated in <a href="#all_http_class-httpclientrequest"><code>http.ClientRequest</code></a> section.</p>
<p>The <code>callback</code> is invoked with a single argument that is an instance of
<a href="#all_http_class-httpincomingmessage"><code>http.IncomingMessage</code></a>.</p>
<p>JSON fetching example:</p>
<pre><code class="language-js">http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8000/'</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-keyword">const</span> { statusCode } = res;
<span class="hljs-keyword">const</span> contentType = res.<span class="hljs-property">headers</span>[<span class="hljs-string">'content-type'</span>];
<span class="hljs-keyword">let</span> error;
<span class="hljs-comment">// Any 2xx status code signals a successful response but</span>
<span class="hljs-comment">// here we're only checking for 200.</span>
<span class="hljs-keyword">if</span> (statusCode !== <span class="hljs-number">200</span>) {
error = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Request Failed.\n'</span> +
<span class="hljs-string">`Status Code: <span class="hljs-subst">${statusCode}</span>`</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (!<span class="hljs-regexp">/^application\/json/</span>.<span class="hljs-title function_">test</span>(contentType)) {
error = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Invalid content-type.\n'</span> +
<span class="hljs-string">`Expected application/json but received <span class="hljs-subst">${contentType}</span>`</span>);
}
<span class="hljs-keyword">if</span> (error) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error.<span class="hljs-property">message</span>);
<span class="hljs-comment">// Consume response data to free up memory</span>
res.<span class="hljs-title function_">resume</span>();
<span class="hljs-keyword">return</span>;
}
res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
<span class="hljs-keyword">let</span> rawData = <span class="hljs-string">''</span>;
res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { rawData += chunk; });
res.<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> parsedData = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(rawData);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(parsedData);
} <span class="hljs-keyword">catch</span> (e) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e.<span class="hljs-property">message</span>);
}
});
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Got error: <span class="hljs-subst">${e.message}</span>`</span>);
});
<span class="hljs-comment">// Create a local server to receive data from</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> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
<span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
}));
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>http.globalAgent</code><span><a class="mark" href="#all_http_httpglobalagent" id="all_http_httpglobalagent">#</a></span><a aria-hidden="true" class="legacy" id="http_http_globalagent"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>The agent now uses HTTP Keep-Alive and a 5 second timeout by default.</p></td></tr>
<tr><td>v0.5.9</td>
<td><p><span>Added in: v0.5.9</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="#all_http_class-httpagent" class="type"><http.Agent></a></li>
</ul>
<p>Global instance of <code>Agent</code> which is used as the default for all HTTP client
requests. Diverges from a default <code>Agent</code> configuration by having <code>keepAlive</code>
enabled and a <code>timeout</code> of 5 seconds.</p>
</section><section><h3><code>http.maxHeaderSize</code><span><a class="mark" href="#all_http_httpmaxheadersize" id="all_http_httpmaxheadersize">#</a></span><a aria-hidden="true" class="legacy" id="http_http_maxheadersize"></a></h3>
<div class="api_metadata">
<span>Added in: v11.6.0, v10.15.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>Read-only property specifying the maximum allowed size of HTTP headers in bytes.
Defaults to 16 KiB. Configurable using the <a href="#all_cli_--max-http-header-sizesize"><code>--max-http-header-size</code></a> CLI
option.</p>
<p>This can be overridden for servers and client requests by passing the
<code>maxHeaderSize</code> option.</p>
</section><section><h3><code>http.request(options[, callback])</code><span><a class="mark" href="#all_http_httprequestoptions-callback" id="all_http_httprequestoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_http_request_options_callback"></a></h3>
</section><section><h3><code>http.request(url[, options][, callback])</code><span><a class="mark" href="#all_http_httprequesturl-options-callback" id="all_http_httprequesturl-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_http_request_url_options_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.7.0, v14.18.0</td>
<td><p>When using a <code>URL</code> object parsed username and password will now be properly URI decoded.</p></td></tr>
<tr><td>v15.3.0, v14.17.0</td>
<td><p>It is possible to abort a request with an AbortSignal.</p></td></tr>
<tr><td>v13.3.0</td>
<td><p>The <code>maxHeaderSize</code> option is supported now.</p></td></tr>
<tr><td>v13.8.0, v12.15.0, v10.19.0</td>
<td><p>The <code>insecureHTTPParser</code> option is supported now.</p></td></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr>
<tr><td>v7.5.0</td>
<td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr>
<tr><td>v0.3.6</td>
<td><p><span>Added in: v0.3.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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>agent</code> <a href="#all_http_class-httpagent" class="type"><http.Agent></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Controls <a href="#all_http_class-httpagent"><code>Agent</code></a> behavior. Possible
values:
<ul>
<li><code>undefined</code> (default): use <a href="#all_http_httpglobalagent"><code>http.globalAgent</code></a> for this host and port.</li>
<li><code>Agent</code> object: explicitly use the passed in <code>Agent</code>.</li>
<li><code>false</code>: causes a new <code>Agent</code> with default values to be used.</li>
</ul>
</li>
<li><code>auth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Basic authentication (<code>'user:password'</code>) to compute an
Authorization header.</li>
<li><code>createConnection</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A function that produces a socket/stream to
use for the request when the <code>agent</code> option is not used. This can be used to
avoid creating a custom <code>Agent</code> class just to override the default
<code>createConnection</code> function. See <a href="#all_http_agentcreateconnectionoptions-callback"><code>agent.createConnection()</code></a> for more
details. Any <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> stream is a valid return value.</li>
<li><code>defaultPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Default port for the protocol. <strong>Default:</strong>
<code>agent.defaultPort</code> if an <code>Agent</code> is used, else <code>undefined</code>.</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> IP address family to use when resolving <code>host</code> or
<code>hostname</code>. Valid values are <code>4</code> or <code>6</code>. When unspecified, both IP v4 and
v6 will be used.</li>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing request headers.</li>
<li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optional <a href="#all_dns_supported-getaddrinfo-flags"><code>dns.lookup()</code> hints</a>.</li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A domain name or IP address of the server to issue the
request to. <strong>Default:</strong> <code>'localhost'</code>.</li>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Alias for <code>host</code>. To support <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a>,
<code>hostname</code> will be used if both <code>host</code> and <code>hostname</code> are specified.</li>
<li><code>insecureHTTPParser</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, it will use a HTTP parser
with leniency flags enabled. Using the insecure parser should be avoided.
See <a href="#all_cli_--insecure-http-parser"><code>--insecure-http-parser</code></a> for more information.
<strong>Default:</strong> <code>false</code></li>
<li><code>joinDuplicateHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> It joins the field line values of
multiple headers in a request with <code>, </code> instead of discarding
the duplicates. See <a href="#all_http_messageheaders"><code>message.headers</code></a> for more information.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>localAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Local interface to bind for network connections.</li>
<li><code>localPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Local port to connect from.</li>
<li><code>lookup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Custom lookup function. <strong>Default:</strong> <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</li>
<li><code>maxHeaderSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optionally overrides the value of
<a href="#all_cli_--max-http-header-sizesize"><code>--max-http-header-size</code></a> (the maximum length of response headers in
bytes) for responses received from the server.
<strong>Default:</strong> 16384 (16 KiB).</li>
<li><code>method</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string specifying the HTTP request method. <strong>Default:</strong>
<code>'GET'</code>.</li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Request path. Should include query string if any.
E.G. <code>'/index.html?page=12'</code>. An exception is thrown when the request path
contains illegal characters. Currently, only spaces are rejected but that
may change in the future. <strong>Default:</strong> <code>'/'</code>.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port of remote server. <strong>Default:</strong> <code>defaultPort</code> if set,
else <code>80</code>.</li>
<li><code>protocol</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Protocol to use. <strong>Default:</strong> <code>'http:'</code>.</li>
<li><code>setHost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a>: Specifies whether or not to automatically add the
<code>Host</code> header. Defaults to <code>true</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a>: An AbortSignal that may be used to abort an ongoing
request.</li>
<li><code>socketPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Unix domain socket. Cannot be used if one of <code>host</code>
or <code>port</code> is specified, as those specify a TCP Socket.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a>: A number specifying the socket timeout in milliseconds.
This will set the timeout before the socket is connected.</li>
<li><code>uniqueHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> A list of request headers that should be sent
only once. If the header's value is an array, the items will be joined
using <code>; </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></li>
<li>Returns: <a href="#all_http_class-httpclientrequest" class="type"><http.ClientRequest></a></li>
</ul>
<p><code>options</code> in <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect()</code></a> are also supported.</p>
<p>Node.js maintains several connections per server to make HTTP requests.
This function allows one to transparently issue requests.</p>
<p><code>url</code> can be a string or a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a> object. If <code>url</code> is a
string, it is automatically parsed with <a href="#all_url_new-urlinput-base"><code>new URL()</code></a>. If it is a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a>
object, it will be automatically converted to an ordinary <code>options</code> object.</p>
<p>If both <code>url</code> and <code>options</code> are specified, the objects are merged, with the
<code>options</code> properties taking precedence.</p>
<p>The optional <code>callback</code> parameter will be added as a one-time listener for
the <a href="#all_http_event-response"><code>'response'</code></a> event.</p>
<p><code>http.request()</code> returns an instance of the <a href="#all_http_class-httpclientrequest"><code>http.ClientRequest</code></a>
class. The <code>ClientRequest</code> instance is a writable stream. If one needs to
upload a file with a POST request, then write to the <code>ClientRequest</code> object.</p>
<pre class="with-37-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> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> postData = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
<span class="hljs-string">'msg'</span>: <span class="hljs-string">'Hello World!'</span>,
});
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">hostname</span>: <span class="hljs-string">'www.google.com'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/upload'</span>,
<span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
<span class="hljs-attr">headers</span>: {
<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
<span class="hljs-string">'Content-Length'</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(postData),
},
};
<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`STATUS: <span class="hljs-subst">${res.statusCode}</span>`</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`HEADERS: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(res.headers)}</span>`</span>);
res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
res.<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">`BODY: <span class="hljs-subst">${chunk}</span>`</span>);
});
res.<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">'No more data in response.'</span>);
});
});
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`problem with request: <span class="hljs-subst">${e.message}</span>`</span>);
});
<span class="hljs-comment">// Write data to request body</span>
req.<span class="hljs-title function_">write</span>(postData);
req.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><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> postData = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
<span class="hljs-string">'msg'</span>: <span class="hljs-string">'Hello World!'</span>,
});
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">hostname</span>: <span class="hljs-string">'www.google.com'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/upload'</span>,
<span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
<span class="hljs-attr">headers</span>: {
<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
<span class="hljs-string">'Content-Length'</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(postData),
},
};
<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`STATUS: <span class="hljs-subst">${res.statusCode}</span>`</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`HEADERS: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(res.headers)}</span>`</span>);
res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
res.<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">`BODY: <span class="hljs-subst">${chunk}</span>`</span>);
});
res.<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">'No more data in response.'</span>);
});
});
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`problem with request: <span class="hljs-subst">${e.message}</span>`</span>);
});
<span class="hljs-comment">// Write data to request body</span>
req.<span class="hljs-title function_">write</span>(postData);
req.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<p>In the example <code>req.end()</code> was called. With <code>http.request()</code> one
must always call <code>req.end()</code> to signify the end of the request -
even if there is no data being written to the request body.</p>
<p>If any error is encountered during the request (be that with DNS resolution,
TCP level errors, or actual HTTP parse errors) an <code>'error'</code> event is emitted
on the returned request object. As with all <code>'error'</code> events, if no listeners
are registered the error will be thrown.</p>
<p>There are a few special headers that should be noted.</p>
<ul>
<li>
<p>Sending a 'Connection: keep-alive' will notify Node.js that the connection to
the server should be persisted until the next request.</p>
</li>
<li>
<p>Sending a 'Content-Length' header will disable the default chunked encoding.</p>
</li>
<li>
<p>Sending an 'Expect' header will immediately send the request headers.
Usually, when sending 'Expect: 100-continue', both a timeout and a listener
for the <code>'continue'</code> event should be set. See RFC 2616 Section 8.2.3 for more
information.</p>
</li>
<li>
<p>Sending an Authorization header will override using the <code>auth</code> option
to compute basic authentication.</p>
</li>
</ul>
<p>Example using a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a> as <code>options</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> options = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'http://abc:xyz@example.com'</span>);
<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-comment">// ...</span>
});</code> <button class="copy-button">copy</button></pre>
<p>In a successful request, the following events will be emitted in the following
order:</p>
<ul>
<li><code>'socket'</code></li>
<li><code>'response'</code>
<ul>
<li><code>'data'</code> any number of times, on the <code>res</code> object
(<code>'data'</code> will not be emitted at all if the response body is empty, for
instance, in most redirects)</li>
<li><code>'end'</code> on the <code>res</code> object</li>
</ul>
</li>
<li><code>'close'</code></li>
</ul>
<p>In the case of a connection error, the following events will be emitted:</p>
<ul>
<li><code>'socket'</code></li>
<li><code>'error'</code></li>
<li><code>'close'</code></li>
</ul>
<p>In the case of a premature connection close before the response is received,
the following events will be emitted in the following order:</p>
<ul>
<li><code>'socket'</code></li>
<li><code>'error'</code> with an error with message <code>'Error: socket hang up'</code> and code
<code>'ECONNRESET'</code></li>
<li><code>'close'</code></li>
</ul>
<p>In the case of a premature connection close after the response is received,
the following events will be emitted in the following order:</p>
<ul>
<li><code>'socket'</code></li>
<li><code>'response'</code>
<ul>
<li><code>'data'</code> any number of times, on the <code>res</code> object</li>
</ul>
</li>
<li>(connection closed here)</li>
<li><code>'aborted'</code> on the <code>res</code> object</li>
<li><code>'close'</code></li>
<li><code>'error'</code> on the <code>res</code> object with an error with message
<code>'Error: aborted'</code> and code <code>'ECONNRESET'</code></li>
<li><code>'close'</code> on the <code>res</code> object</li>
</ul>
<p>If <code>req.destroy()</code> is called before a socket is assigned, the following
events will be emitted in the following order:</p>
<ul>
<li>(<code>req.destroy()</code> called here)</li>
<li><code>'error'</code> with an error with message <code>'Error: socket hang up'</code> and code
<code>'ECONNRESET'</code>, or the error with which <code>req.destroy()</code> was called</li>
<li><code>'close'</code></li>
</ul>
<p>If <code>req.destroy()</code> is called before the connection succeeds, the following
events will be emitted in the following order:</p>
<ul>
<li><code>'socket'</code></li>
<li>(<code>req.destroy()</code> called here)</li>
<li><code>'error'</code> with an error with message <code>'Error: socket hang up'</code> and code
<code>'ECONNRESET'</code>, or the error with which <code>req.destroy()</code> was called</li>
<li><code>'close'</code></li>
</ul>
<p>If <code>req.destroy()</code> is called after the response is received, the following
events will be emitted in the following order:</p>
<ul>
<li><code>'socket'</code></li>
<li><code>'response'</code>
<ul>
<li><code>'data'</code> any number of times, on the <code>res</code> object</li>
</ul>
</li>
<li>(<code>req.destroy()</code> called here)</li>
<li><code>'aborted'</code> on the <code>res</code> object</li>
<li><code>'close'</code></li>
<li><code>'error'</code> on the <code>res</code> object with an error with message <code>'Error: aborted'</code>
and code <code>'ECONNRESET'</code>, or the error with which <code>req.destroy()</code> was called</li>
<li><code>'close'</code> on the <code>res</code> object</li>
</ul>
<p>If <code>req.abort()</code> is called before a socket is assigned, the following
events will be emitted in the following order:</p>
<ul>
<li>(<code>req.abort()</code> called here)</li>
<li><code>'abort'</code></li>
<li><code>'close'</code></li>
</ul>
<p>If <code>req.abort()</code> is called before the connection succeeds, the following
events will be emitted in the following order:</p>
<ul>
<li><code>'socket'</code></li>
<li>(<code>req.abort()</code> called here)</li>
<li><code>'abort'</code></li>
<li><code>'error'</code> with an error with message <code>'Error: socket hang up'</code> and code
<code>'ECONNRESET'</code></li>
<li><code>'close'</code></li>
</ul>
<p>If <code>req.abort()</code> is called after the response is received, the following
events will be emitted in the following order:</p>
<ul>
<li><code>'socket'</code></li>
<li><code>'response'</code>
<ul>
<li><code>'data'</code> any number of times, on the <code>res</code> object</li>
</ul>
</li>
<li>(<code>req.abort()</code> called here)</li>
<li><code>'abort'</code></li>
<li><code>'aborted'</code> on the <code>res</code> object</li>
<li><code>'error'</code> on the <code>res</code> object with an error with message
<code>'Error: aborted'</code> and code <code>'ECONNRESET'</code>.</li>
<li><code>'close'</code></li>
<li><code>'close'</code> on the <code>res</code> object</li>
</ul>
<p>Setting the <code>timeout</code> option or using the <code>setTimeout()</code> function will
not abort the request or do anything besides add a <code>'timeout'</code> event.</p>
<p>Passing an <code>AbortSignal</code> and then calling <code>abort()</code> on the corresponding
<code>AbortController</code> will behave the same way as calling <code>.destroy()</code> on the
request. Specifically, the <code>'error'</code> event will be emitted with an error with
the message <code>'AbortError: The operation was aborted'</code>, the code <code>'ABORT_ERR'</code>
and the <code>cause</code>, if one was provided.</p>
</section><section><h3><code>http.validateHeaderName(name[, label])</code><span><a class="mark" href="#all_http_httpvalidateheadernamename-label" id="all_http_httpvalidateheadernamename-label">#</a></span><a aria-hidden="true" class="legacy" id="http_http_validateheadername_name_label"></a></h3>
<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>The <code>label</code> parameter is added.</p></td></tr>
<tr><td>v14.3.0</td>
<td><p><span>Added in: v14.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Label for error message. <strong>Default:</strong> <code>'Header name'</code>.</li>
</ul>
<p>Performs the low-level validations on the provided <code>name</code> that are done when
<code>res.setHeader(name, value)</code> is called.</p>
<p>Passing illegal value as <code>name</code> will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown,
identified by <code>code: 'ERR_INVALID_HTTP_TOKEN'</code>.</p>
<p>It is not necessary to use this method before passing headers to an HTTP request
or response. The HTTP module will automatically validate such headers.</p>
<p>Example:</p>
<pre class="with-52-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> { validateHeaderName } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">validateHeaderName</span>(<span class="hljs-string">''</span>);
} <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-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>); <span class="hljs-comment">// --> true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span>); <span class="hljs-comment">// --> 'ERR_INVALID_HTTP_TOKEN'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>); <span class="hljs-comment">// --> 'Header name must be a valid HTTP token [""]'</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { validateHeaderName } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">validateHeaderName</span>(<span class="hljs-string">''</span>);
} <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-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>); <span class="hljs-comment">// --> true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span>); <span class="hljs-comment">// --> 'ERR_INVALID_HTTP_TOKEN'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>); <span class="hljs-comment">// --> 'Header name must be a valid HTTP token [""]'</span>
}</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>http.validateHeaderValue(name, value)</code><span><a class="mark" href="#all_http_httpvalidateheadervaluename-value" id="all_http_httpvalidateheadervaluename-value">#</a></span><a aria-hidden="true" class="legacy" id="http_http_validateheadervalue_name_value"></a></h3>
<div class="api_metadata">
<span>Added in: v14.3.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Performs the low-level validations on the provided <code>value</code> that are done when
<code>res.setHeader(name, value)</code> is called.</p>
<p>Passing illegal value as <code>value</code> will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
<ul>
<li>Undefined value error is identified by <code>code: 'ERR_HTTP_INVALID_HEADER_VALUE'</code>.</li>
<li>Invalid value character error is identified by <code>code: 'ERR_INVALID_CHAR'</code>.</li>
</ul>
<p>It is not necessary to use this method before passing headers to an HTTP request
or response. The HTTP module will automatically validate such headers.</p>
<p>Examples:</p>
<pre class="with-53-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> { validateHeaderValue } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">validateHeaderValue</span>(<span class="hljs-string">'x-my-header'</span>, <span class="hljs-literal">undefined</span>);
} <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-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>); <span class="hljs-comment">// --> true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span> === <span class="hljs-string">'ERR_HTTP_INVALID_HEADER_VALUE'</span>); <span class="hljs-comment">// --> true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>); <span class="hljs-comment">// --> 'Invalid value "undefined" for header "x-my-header"'</span>
}
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">validateHeaderValue</span>(<span class="hljs-string">'x-my-header'</span>, <span class="hljs-string">'oʊmɪɡə'</span>);
} <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-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>); <span class="hljs-comment">// --> true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span> === <span class="hljs-string">'ERR_INVALID_CHAR'</span>); <span class="hljs-comment">// --> true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>); <span class="hljs-comment">// --> 'Invalid character in header content ["x-my-header"]'</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { validateHeaderValue } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">validateHeaderValue</span>(<span class="hljs-string">'x-my-header'</span>, <span class="hljs-literal">undefined</span>);
} <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-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>); <span class="hljs-comment">// --> true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span> === <span class="hljs-string">'ERR_HTTP_INVALID_HEADER_VALUE'</span>); <span class="hljs-comment">// --> true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>); <span class="hljs-comment">// --> 'Invalid value "undefined" for header "x-my-header"'</span>
}
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">validateHeaderValue</span>(<span class="hljs-string">'x-my-header'</span>, <span class="hljs-string">'oʊmɪɡə'</span>);
} <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-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>); <span class="hljs-comment">// --> true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span> === <span class="hljs-string">'ERR_INVALID_CHAR'</span>); <span class="hljs-comment">// --> true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>); <span class="hljs-comment">// --> 'Invalid character in header content ["x-my-header"]'</span>
}</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>http.setMaxIdleHTTPParsers(max)</code><span><a class="mark" href="#all_http_httpsetmaxidlehttpparsersmax" id="all_http_httpsetmaxidlehttpparsersmax">#</a></span><a aria-hidden="true" class="legacy" id="http_http_setmaxidlehttpparsers_max"></a></h3>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<ul>
<li><code>max</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>1000</code>.</li>
</ul>
<p>Set the maximum number of idle HTTP parsers.</p></section>
</section>
<section><h2>HTTP/2<span><a class="mark" href="#all_http2_http2" id="all_http2_http2">#</a></span><a aria-hidden="true" class="legacy" id="http2_http_2"></a></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Requests with the <code>host</code> header (with or without <code>:authority</code>) can now be sent/received.</p></td></tr>
<tr><td>v15.3.0, v14.17.0</td>
<td><p>It is possible to abort a request with an AbortSignal.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>HTTP/2 is now Stable. Previously, it had been Experimental.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/http2.js">lib/http2.js</a></p>
<p>The <code>node:http2</code> module provides an implementation of the <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a> protocol.
It can be accessed using:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);</code> <button class="copy-button">copy</button></pre>
<section><h3>Determining if crypto support is unavailable<span><a class="mark" href="#all_http2_determining-if-crypto-support-is-unavailable" id="all_http2_determining-if-crypto-support-is-unavailable">#</a></span><a aria-hidden="true" class="legacy" id="http2_determining_if_crypto_support_is_unavailable"></a></h3>
<p>It is possible for Node.js to be built without including support for the
<code>node:crypto</code> module. In such cases, attempting to <code>import</code> from <code>node:http2</code> or
calling <code>require('node:http2')</code> will result in an error being thrown.</p>
<p>When using CommonJS, the error thrown can be caught using try/catch:</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">let</span> http2;
<span class="hljs-keyword">try</span> {
http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'http2 support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>When using the lexical ESM <code>import</code> keyword, the error can only be
caught if a handler for <code>process.on('uncaughtException')</code> is registered
<em>before</em> any attempt to load the module is made (using, for instance,
a preload module).</p>
<p>When using ESM, if there is a chance that the code may be run on a build
of Node.js where crypto support is not enabled, consider using the
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import"><code>import()</code></a> function instead of the lexical <code>import</code> keyword:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">let</span> http2;
<span class="hljs-keyword">try</span> {
http2 = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:http2'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'http2 support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Core API<span><a class="mark" href="#all_http2_core-api" id="all_http2_core-api">#</a></span><a aria-hidden="true" class="legacy" id="http2_core_api"></a></h3>
<p>The Core API provides a low-level interface designed specifically around
support for HTTP/2 protocol features. It is specifically <em>not</em> designed for
compatibility with the existing <a href="http.html">HTTP/1</a> module API. However,
the <a href="#all_http2_compatibility-api">Compatibility API</a> is.</p>
<p>The <code>http2</code> Core API is much more symmetric between client and server than the
<code>http</code> API. For instance, most events, like <code>'error'</code>, <code>'connect'</code> and
<code>'stream'</code>, can be emitted either by client-side code or server-side code.</p>
<h4>Server-side example<span><a class="mark" href="#all_http2_server-side-example" id="all_http2_server-side-example">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_side_example"></a></h4>
<p>The following illustrates a simple HTTP/2 server using the Core API.
Since there are no browsers known that support
<a href="https://http2.github.io/faq/#does-http2-require-encryption">unencrypted HTTP/2</a>, the use of
<a href="#all_http2_http2createsecureserveroptions-onrequesthandler"><code>http2.createSecureServer()</code></a> is necessary when communicating
with browser clients.</p>
<pre class="with-48-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> { createSecureServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>({
<span class="hljs-attr">key</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'localhost-privkey.pem'</span>),
<span class="hljs-attr">cert</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'localhost-cert.pem'</span>),
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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));
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
<span class="hljs-comment">// stream is a Duplex</span>
stream.<span class="hljs-title function_">respond</span>({
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
<span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
});
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'<h1>Hello World</h1>'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8443</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</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> server = http2.<span class="hljs-title function_">createSecureServer</span>({
<span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'localhost-privkey.pem'</span>),
<span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'localhost-cert.pem'</span>),
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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));
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
<span class="hljs-comment">// stream is a Duplex</span>
stream.<span class="hljs-title function_">respond</span>({
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
<span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
});
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'<h1>Hello World</h1>'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8443</span>);</code><button class="copy-button">copy</button></pre>
<p>To generate the certificate and key for this example, run:</p>
<pre><code class="language-bash">openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj <span class="hljs-string">'/CN=localhost'</span> \
-keyout localhost-privkey.pem -out localhost-cert.pem</code> <button class="copy-button">copy</button></pre>
<h4>Client-side example<span><a class="mark" href="#all_http2_client-side-example" id="all_http2_client-side-example">#</a></span><a aria-hidden="true" class="legacy" id="http2_client_side_example"></a></h4>
<p>The following illustrates an HTTP/2 client:</p>
<pre class="with-39-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> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost:8443'</span>, {
<span class="hljs-attr">ca</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'localhost-cert.pem'</span>),
});
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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));
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> name <span class="hljs-keyword">in</span> headers) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${name}</span>: <span class="hljs-subst">${headers[name]}</span>`</span>);
}
});
req.<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>;
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> { data += chunk; });
req.<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">`\n<span class="hljs-subst">${data}</span>`</span>);
client.<span class="hljs-title function_">close</span>();
});
req.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</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> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost:8443'</span>, {
<span class="hljs-attr">ca</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'localhost-cert.pem'</span>),
});
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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));
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> name <span class="hljs-keyword">in</span> headers) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${name}</span>: <span class="hljs-subst">${headers[name]}</span>`</span>);
}
});
req.<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>;
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> { data += chunk; });
req.<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">`\n<span class="hljs-subst">${data}</span>`</span>);
client.<span class="hljs-title function_">close</span>();
});
req.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>Http2Session</code><span><a class="mark" href="#all_http2_class-http2session" id="all_http2_class-http2session">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_http2session"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>Instances of the <code>http2.Http2Session</code> class represent an active communications
session between an HTTP/2 client and server. Instances of this class are <em>not</em>
intended to be constructed directly by user code.</p>
<p>Each <code>Http2Session</code> instance will exhibit slightly different behaviors
depending on whether it is operating as a server or a client. The
<code>http2session.type</code> property can be used to determine the mode in which an
<code>Http2Session</code> is operating. On the server side, user code should rarely
have occasion to work with the <code>Http2Session</code> object directly, with most
actions typically taken through interactions with either the <code>Http2Server</code> or
<code>Http2Stream</code> objects.</p>
<p>User code will not create <code>Http2Session</code> instances directly. Server-side
<code>Http2Session</code> instances are created by the <code>Http2Server</code> instance when a
new HTTP/2 connection is received. Client-side <code>Http2Session</code> instances are
created using the <code>http2.connect()</code> method.</p>
<h5><code>Http2Session</code> and sockets<span><a class="mark" href="#all_http2_http2session-and-sockets" id="all_http2_http2session-and-sockets">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_and_sockets"></a></h5>
<p>Every <code>Http2Session</code> instance is associated with exactly one <a href="#all_net_class-netsocket"><code>net.Socket</code></a> or
<a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a> when it is created. When either the <code>Socket</code> or the
<code>Http2Session</code> are destroyed, both will be destroyed.</p>
<p>Because of the specific serialization and processing requirements imposed
by the HTTP/2 protocol, it is not recommended for user code to read data from
or write data to a <code>Socket</code> instance bound to a <code>Http2Session</code>. Doing so can
put the HTTP/2 session into an indeterminate state causing the session and
the socket to become unusable.</p>
<p>Once a <code>Socket</code> has been bound to an <code>Http2Session</code>, user code should rely
solely on the API of the <code>Http2Session</code>.</p>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_http2_event-close" id="all_http2_event-close">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_close"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'close'</code> event is emitted once the <code>Http2Session</code> has been destroyed. Its
listener does not expect any arguments.</p>
<h5>Event: <code>'connect'</code><span><a class="mark" href="#all_http2_event-connect" id="all_http2_event-connect">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_connect"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>session</code> <a href="#all_http2_class-http2session" class="type"><Http2Session></a></li>
<li><code>socket</code> <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
</ul>
<p>The <code>'connect'</code> event is emitted once the <code>Http2Session</code> has been successfully
connected to the remote peer and communication may begin.</p>
<p>User code will typically not listen for this event directly.</p>
<h5>Event: <code>'error'</code><span><a class="mark" href="#all_http2_event-error" id="all_http2_event-error">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_error"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</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>
</ul>
<p>The <code>'error'</code> event is emitted when an error occurs during the processing of
an <code>Http2Session</code>.</p>
<h5>Event: <code>'frameError'</code><span><a class="mark" href="#all_http2_event-frameerror" id="all_http2_event-frameerror">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_frameerror"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The frame type.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The error code.</li>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The stream id (or <code>0</code> if the frame isn't associated with a
stream).</li>
</ul>
<p>The <code>'frameError'</code> event is emitted when an error occurs while attempting to
send a frame on the session. If the frame that could not be sent is associated
with a specific <code>Http2Stream</code>, an attempt to emit a <code>'frameError'</code> event on the
<code>Http2Stream</code> is made.</p>
<p>If the <code>'frameError'</code> event is associated with a stream, the stream will be
closed and destroyed immediately following the <code>'frameError'</code> event. If the
event is not associated with a stream, the <code>Http2Session</code> will be shut down
immediately following the <code>'frameError'</code> event.</p>
<h5>Event: <code>'goaway'</code><span><a class="mark" href="#all_http2_event-goaway" id="all_http2_event-goaway">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_goaway"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>errorCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The HTTP/2 error code specified in the <code>GOAWAY</code> frame.</li>
<li><code>lastStreamID</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ID of the last stream the remote peer successfully
processed (or <code>0</code> if no ID is specified).</li>
<li><code>opaqueData</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> If additional opaque data was included in the <code>GOAWAY</code>
frame, a <code>Buffer</code> instance will be passed containing that data.</li>
</ul>
<p>The <code>'goaway'</code> event is emitted when a <code>GOAWAY</code> frame is received.</p>
<p>The <code>Http2Session</code> instance will be shut down automatically when the <code>'goaway'</code>
event is emitted.</p>
<h5>Event: <code>'localSettings'</code><span><a class="mark" href="#all_http2_event-localsettings" id="all_http2_event-localsettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_localsettings"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a> A copy of the <code>SETTINGS</code> frame received.</li>
</ul>
<p>The <code>'localSettings'</code> event is emitted when an acknowledgment <code>SETTINGS</code> frame
has been received.</p>
<p>When using <code>http2session.settings()</code> to submit new settings, the modified
settings do not take effect until the <code>'localSettings'</code> event is emitted.</p>
<pre><code class="language-js">session.<span class="hljs-title function_">settings</span>({ <span class="hljs-attr">enablePush</span>: <span class="hljs-literal">false</span> });
session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'localSettings'</span>, <span class="hljs-function">(<span class="hljs-params">settings</span>) =></span> {
<span class="hljs-comment">/* Use the new settings */</span>
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'ping'</code><span><a class="mark" href="#all_http2_event-ping" id="all_http2_event-ping">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_ping"></a></h5>
<div class="api_metadata">
<span>Added in: v10.12.0</span>
</div>
<ul>
<li><code>payload</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The <code>PING</code> frame 8-byte payload</li>
</ul>
<p>The <code>'ping'</code> event is emitted whenever a <code>PING</code> frame is received from the
connected peer.</p>
<h5>Event: <code>'remoteSettings'</code><span><a class="mark" href="#all_http2_event-remotesettings" id="all_http2_event-remotesettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_remotesettings"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a> A copy of the <code>SETTINGS</code> frame received.</li>
</ul>
<p>The <code>'remoteSettings'</code> event is emitted when a new <code>SETTINGS</code> frame is received
from the connected peer.</p>
<pre><code class="language-js">session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'remoteSettings'</span>, <span class="hljs-function">(<span class="hljs-params">settings</span>) =></span> {
<span class="hljs-comment">/* Use the new settings */</span>
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'stream'</code><span><a class="mark" href="#all_http2_event-stream" id="all_http2_event-stream">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_http2_class-http2stream" class="type"><Http2Stream></a> A reference to the stream</li>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a> An object describing the headers</li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The associated numeric flags</li>
<li><code>rawHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array containing the raw header names followed by
their respective values.</li>
</ul>
<p>The <code>'stream'</code> event is emitted when a new <code>Http2Stream</code> is created.</p>
<pre><code class="language-js">session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers, flags</span>) =></span> {
<span class="hljs-keyword">const</span> method = headers[<span class="hljs-string">':method'</span>];
<span class="hljs-keyword">const</span> path = headers[<span class="hljs-string">':path'</span>];
<span class="hljs-comment">// ...</span>
stream.<span class="hljs-title function_">respond</span>({
<span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
});
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello '</span>);
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>On the server side, user code will typically not listen for this event directly,
and would instead register a handler for the <code>'stream'</code> event emitted by the
<code>net.Server</code> or <code>tls.Server</code> instances returned by <code>http2.createServer()</code> and
<code>http2.createSecureServer()</code>, respectively, as in the example below:</p>
<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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-comment">// Create an unencrypted HTTP/2 server</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>({
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
<span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
});
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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));
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'<h1>Hello World</h1>'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-comment">// Create an unencrypted HTTP/2 server</span>
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>({
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
<span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
});
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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));
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'<h1>Hello World</h1>'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>
<p>Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence,
a network error will destroy each individual stream and must be handled on the
stream level, as shown above.</p>
<h5>Event: <code>'timeout'</code><span><a class="mark" href="#all_http2_event-timeout" id="all_http2_event-timeout">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_timeout"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>After the <code>http2session.setTimeout()</code> method is used to set the timeout period
for this <code>Http2Session</code>, the <code>'timeout'</code> event is emitted if there is no
activity on the <code>Http2Session</code> after the configured number of milliseconds.
Its listener does not expect any arguments.</p>
<pre><code class="language-js">session.<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">2000</span>);
session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'timeout'</span>, <span class="hljs-function">() =></span> { <span class="hljs-comment">/* .. */</span> });</code> <button class="copy-button">copy</button></pre>
<h5><code>http2session.alpnProtocol</code><span><a class="mark" href="#all_http2_http2sessionalpnprotocol" id="all_http2_http2sessionalpnprotocol">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_alpnprotocol"></a></h5>
<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#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>Value will be <code>undefined</code> if the <code>Http2Session</code> is not yet connected to a
socket, <code>h2c</code> if the <code>Http2Session</code> is not connected to a <code>TLSSocket</code>, or
will return the value of the connected <code>TLSSocket</code>'s own <code>alpnProtocol</code>
property.</p>
<h5><code>http2session.close([callback])</code><span><a class="mark" href="#all_http2_http2sessionclosecallback" id="all_http2_http2sessionclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_close_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v9.4.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></li>
</ul>
<p>Gracefully closes the <code>Http2Session</code>, allowing any existing streams to
complete on their own and preventing new <code>Http2Stream</code> instances from being
created. Once closed, <code>http2session.destroy()</code> <em>might</em> be called if there
are no open <code>Http2Stream</code> instances.</p>
<p>If specified, the <code>callback</code> function is registered as a handler for the
<code>'close'</code> event.</p>
<h5><code>http2session.closed</code><span><a class="mark" href="#all_http2_http2sessionclosed" id="all_http2_http2sessionclosed">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_closed"></a></h5>
<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>Will be <code>true</code> if this <code>Http2Session</code> instance has been closed, otherwise
<code>false</code>.</p>
<h5><code>http2session.connecting</code><span><a class="mark" href="#all_http2_http2sessionconnecting" id="all_http2_http2sessionconnecting">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_connecting"></a></h5>
<div class="api_metadata">
<span>Added in: v10.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>Will be <code>true</code> if this <code>Http2Session</code> instance is still connecting, will be set
to <code>false</code> before emitting <code>connect</code> event and/or calling the <code>http2.connect</code>
callback.</p>
<h5><code>http2session.destroy([error][, code])</code><span><a class="mark" href="#all_http2_http2sessiondestroyerror-code" id="all_http2_http2sessiondestroyerror-code">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_destroy_error_code"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</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> An <code>Error</code> object if the <code>Http2Session</code> is being destroyed
due to an error.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The HTTP/2 error code to send in the final <code>GOAWAY</code> frame.
If unspecified, and <code>error</code> is not undefined, the default is <code>INTERNAL_ERROR</code>,
otherwise defaults to <code>NO_ERROR</code>.</li>
</ul>
<p>Immediately terminates the <code>Http2Session</code> and the associated <code>net.Socket</code> or
<code>tls.TLSSocket</code>.</p>
<p>Once destroyed, the <code>Http2Session</code> will emit the <code>'close'</code> event. If <code>error</code>
is not undefined, an <code>'error'</code> event will be emitted immediately before the
<code>'close'</code> event.</p>
<p>If there are any remaining open <code>Http2Streams</code> associated with the
<code>Http2Session</code>, those will also be destroyed.</p>
<h5><code>http2session.destroyed</code><span><a class="mark" href="#all_http2_http2sessiondestroyed" id="all_http2_http2sessiondestroyed">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_destroyed"></a></h5>
<div class="api_metadata">
<span>Added in: v8.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>Will be <code>true</code> if this <code>Http2Session</code> instance has been destroyed and must no
longer be used, otherwise <code>false</code>.</p>
<h5><code>http2session.encrypted</code><span><a class="mark" href="#all_http2_http2sessionencrypted" id="all_http2_http2sessionencrypted">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_encrypted"></a></h5>
<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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>Value is <code>undefined</code> if the <code>Http2Session</code> session socket has not yet been
connected, <code>true</code> if the <code>Http2Session</code> is connected with a <code>TLSSocket</code>,
and <code>false</code> if the <code>Http2Session</code> is connected to any other kind of socket
or stream.</p>
<h5><code>http2session.goaway([code[, lastStreamID[, opaqueData]]])</code><span><a class="mark" href="#all_http2_http2sessiongoawaycode-laststreamid-opaquedata" id="all_http2_http2sessiongoawaycode-laststreamid-opaquedata">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_goaway_code_laststreamid_opaquedata"></a></h5>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> An HTTP/2 error code</li>
<li><code>lastStreamID</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The numeric ID of the last processed <code>Http2Stream</code></li>
<li><code>opaqueData</code> <a href="#all_buffer_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 <code>TypedArray</code> or <code>DataView</code>
instance containing additional data to be carried within the <code>GOAWAY</code> frame.</li>
</ul>
<p>Transmits a <code>GOAWAY</code> frame to the connected peer <em>without</em> shutting down the
<code>Http2Session</code>.</p>
<h5><code>http2session.localSettings</code><span><a class="mark" href="#all_http2_http2sessionlocalsettings" id="all_http2_http2sessionlocalsettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_localsettings"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a></li>
</ul>
<p>A prototype-less object describing the current local settings of this
<code>Http2Session</code>. The local settings are local to <em>this</em> <code>Http2Session</code> instance.</p>
<h5><code>http2session.originSet</code><span><a class="mark" href="#all_http2_http2sessionoriginset" id="all_http2_http2sessionoriginset">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_originset"></a></h5>
<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#String_type" class="type"><string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>If the <code>Http2Session</code> is connected to a <code>TLSSocket</code>, the <code>originSet</code> property
will return an <code>Array</code> of origins for which the <code>Http2Session</code> may be
considered authoritative.</p>
<p>The <code>originSet</code> property is only available when using a secure TLS connection.</p>
<h5><code>http2session.pendingSettingsAck</code><span><a class="mark" href="#all_http2_http2sessionpendingsettingsack" id="all_http2_http2sessionpendingsettingsack">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_pendingsettingsack"></a></h5>
<div class="api_metadata">
<span>Added in: v8.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>Indicates whether the <code>Http2Session</code> is currently waiting for acknowledgment of
a sent <code>SETTINGS</code> frame. Will be <code>true</code> after calling the
<code>http2session.settings()</code> method. Will be <code>false</code> once all sent <code>SETTINGS</code>
frames have been acknowledged.</p>
<h5><code>http2session.ping([payload, ]callback)</code><span><a class="mark" href="#all_http2_http2sessionpingpayload-callback" id="all_http2_http2sessionpingpayload-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_ping_payload_callback"></a></h5>
<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</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>v8.9.3</td>
<td><p><span>Added in: v8.9.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>payload</code> <a href="#all_buffer_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> Optional ping payload.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></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>Sends a <code>PING</code> frame to the connected HTTP/2 peer. A <code>callback</code> function must
be provided. The method will return <code>true</code> if the <code>PING</code> was sent, <code>false</code>
otherwise.</p>
<p>The maximum number of outstanding (unacknowledged) pings is determined by the
<code>maxOutstandingPings</code> configuration option. The default maximum is 10.</p>
<p>If provided, the <code>payload</code> must be a <code>Buffer</code>, <code>TypedArray</code>, or <code>DataView</code>
containing 8 bytes of data that will be transmitted with the <code>PING</code> and
returned with the ping acknowledgment.</p>
<p>The callback will be invoked with three arguments: an error argument that will
be <code>null</code> if the <code>PING</code> was successfully acknowledged, a <code>duration</code> argument
that reports the number of milliseconds elapsed since the ping was sent and the
acknowledgment was received, and a <code>Buffer</code> containing the 8-byte <code>PING</code>
payload.</p>
<pre><code class="language-js">session.<span class="hljs-title function_">ping</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'abcdefgh'</span>), <span class="hljs-function">(<span class="hljs-params">err, duration, payload</span>) =></span> {
<span class="hljs-keyword">if</span> (!err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Ping acknowledged in <span class="hljs-subst">${duration}</span> milliseconds`</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`With payload '<span class="hljs-subst">${payload.toString()}</span>'`</span>);
}
});</code> <button class="copy-button">copy</button></pre>
<p>If the <code>payload</code> argument is not specified, the default payload will be the
64-bit timestamp (little endian) marking the start of the <code>PING</code> duration.</p>
<h5><code>http2session.ref()</code><span><a class="mark" href="#all_http2_http2sessionref" id="all_http2_http2sessionref">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_ref"></a></h5>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<p>Calls <a href="#all_net_socketref"><code>ref()</code></a> on this <code>Http2Session</code>
instance's underlying <a href="#all_net_class-netsocket"><code>net.Socket</code></a>.</p>
<h5><code>http2session.remoteSettings</code><span><a class="mark" href="#all_http2_http2sessionremotesettings" id="all_http2_http2sessionremotesettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_remotesettings"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a></li>
</ul>
<p>A prototype-less object describing the current remote settings of this
<code>Http2Session</code>. The remote settings are set by the <em>connected</em> HTTP/2 peer.</p>
<h5><code>http2session.setLocalWindowSize(windowSize)</code><span><a class="mark" href="#all_http2_http2sessionsetlocalwindowsizewindowsize" id="all_http2_http2sessionsetlocalwindowsizewindowsize">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_setlocalwindowsize_windowsize"></a></h5>
<div class="api_metadata">
<span>Added in: v15.3.0, v14.18.0</span>
</div>
<ul>
<li><code>windowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Sets the local endpoint's window size.
The <code>windowSize</code> is the total window size to set, not
the delta.</p>
<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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
<span class="hljs-keyword">const</span> expectedWindowSize = <span class="hljs-number">2</span> ** <span class="hljs-number">20</span>;
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {
<span class="hljs-comment">// Set local window size to be 2 ** 20</span>
session.<span class="hljs-title function_">setLocalWindowSize</span>(expectedWindowSize);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
<span class="hljs-keyword">const</span> expectedWindowSize = <span class="hljs-number">2</span> ** <span class="hljs-number">20</span>;
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {
<span class="hljs-comment">// Set local window size to be 2 ** 20</span>
session.<span class="hljs-title function_">setLocalWindowSize</span>(expectedWindowSize);
});</code><button class="copy-button">copy</button></pre>
<p>For http2 clients the proper event is either <code>'connect'</code> or <code>'remoteSettings'</code>.</p>
<h5><code>http2session.setTimeout(msecs, callback)</code><span><a class="mark" href="#all_http2_http2sessionsettimeoutmsecs-callback" id="all_http2_http2sessionsettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_settimeout_msecs_callback"></a></h5>
<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</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>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>Used to set a callback function that is called when there is no activity on
the <code>Http2Session</code> after <code>msecs</code> milliseconds. The given <code>callback</code> is
registered as a listener on the <code>'timeout'</code> event.</p>
<h5><code>http2session.socket</code><span><a class="mark" href="#all_http2_http2sessionsocket" id="all_http2_http2sessionsocket">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_socket"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_net_class-netsocket" class="type"><net.Socket></a> | <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a></li>
</ul>
<p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but
limits available methods to ones safe to use with HTTP/2.</p>
<p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw
an error with code <code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See
<a href="#all_http2_http2session-and-sockets"><code>Http2Session</code> and Sockets</a> for more information.</p>
<p><code>setTimeout</code> method will be called on this <code>Http2Session</code>.</p>
<p>All other interactions will be routed directly to the socket.</p>
<h5><code>http2session.state</code><span><a class="mark" href="#all_http2_http2sessionstate" id="all_http2_http2sessionstate">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_state"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>Provides miscellaneous information about the current state of the
<code>Http2Session</code>.</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>effectiveLocalWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The current local (receive)
flow control window size for the <code>Http2Session</code>.</li>
<li><code>effectiveRecvDataLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The current number of bytes
that have been received since the last flow control <code>WINDOW_UPDATE</code>.</li>
<li><code>nextStreamID</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The numeric identifier to be used the
next time a new <code>Http2Stream</code> is created by this <code>Http2Session</code>.</li>
<li><code>localWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes that the remote peer can
send without receiving a <code>WINDOW_UPDATE</code>.</li>
<li><code>lastProcStreamID</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The numeric id of the <code>Http2Stream</code>
for which a <code>HEADERS</code> or <code>DATA</code> frame was most recently received.</li>
<li><code>remoteWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes that this <code>Http2Session</code>
may send without receiving a <code>WINDOW_UPDATE</code>.</li>
<li><code>outboundQueueSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of frames currently within the
outbound queue for this <code>Http2Session</code>.</li>
<li><code>deflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The current size in bytes of the
outbound header compression state table.</li>
<li><code>inflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The current size in bytes of the
inbound header compression state table.</li>
</ul>
</li>
</ul>
<p>An object describing the current status of this <code>Http2Session</code>.</p>
<h5><code>http2session.settings([settings][, callback])</code><span><a class="mark" href="#all_http2_http2sessionsettingssettings-callback" id="all_http2_http2sessionsettingssettings-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_settings_settings_callback"></a></h5>
<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</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>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a></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 that is called once the session is connected or
right away if the session is already connected.
<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 href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a></li>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a> The updated <code>settings</code> object.</li>
<li><code>duration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
</li>
</ul>
<p>Updates the current local settings for this <code>Http2Session</code> and sends a new
<code>SETTINGS</code> frame to the connected HTTP/2 peer.</p>
<p>Once called, the <code>http2session.pendingSettingsAck</code> property will be <code>true</code>
while the session is waiting for the remote peer to acknowledge the new
settings.</p>
<p>The new settings will not become effective until the <code>SETTINGS</code> acknowledgment
is received and the <code>'localSettings'</code> event is emitted. It is possible to send
multiple <code>SETTINGS</code> frames while acknowledgment is still pending.</p>
<h5><code>http2session.type</code><span><a class="mark" href="#all_http2_http2sessiontype" id="all_http2_http2sessiontype">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_type"></a></h5>
<div class="api_metadata">
<span>Added in: v8.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>The <code>http2session.type</code> will be equal to
<code>http2.constants.NGHTTP2_SESSION_SERVER</code> if this <code>Http2Session</code> instance is a
server, and <code>http2.constants.NGHTTP2_SESSION_CLIENT</code> if the instance is a
client.</p>
<h5><code>http2session.unref()</code><span><a class="mark" href="#all_http2_http2sessionunref" id="all_http2_http2sessionunref">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_unref"></a></h5>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<p>Calls <a href="#all_net_socketunref"><code>unref()</code></a> on this <code>Http2Session</code>
instance's underlying <a href="#all_net_class-netsocket"><code>net.Socket</code></a>.</p>
<h4>Class: <code>ServerHttp2Session</code><span><a class="mark" href="#all_http2_class-serverhttp2session" id="all_http2_class-serverhttp2session">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_serverhttp2session"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_http2_class-http2session" class="type"><Http2Session></a></li>
</ul>
<h5><code>serverhttp2session.altsvc(alt, originOrStream)</code><span><a class="mark" href="#all_http2_serverhttp2sessionaltsvcalt-originorstream" id="all_http2_serverhttp2sessionaltsvcalt-originorstream">#</a></span><a aria-hidden="true" class="legacy" id="http2_serverhttp2session_altsvc_alt_originorstream"></a></h5>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><code>alt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A description of the alternative service configuration as
defined by <a href="https://tools.ietf.org/html/rfc7838">RFC 7838</a>.</li>
<li><code>originOrStream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Either a URL string specifying
the origin (or an <code>Object</code> with an <code>origin</code> property) or the numeric
identifier of an active <code>Http2Stream</code> as given by the <code>http2stream.id</code>
property.</li>
</ul>
<p>Submits an <code>ALTSVC</code> frame (as defined by <a href="https://tools.ietf.org/html/rfc7838">RFC 7838</a>) to the connected client.</p>
<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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {
<span class="hljs-comment">// Set altsvc for origin https://example.org:80</span>
session.<span class="hljs-title function_">altsvc</span>(<span class="hljs-string">'h2=":8000"'</span>, <span class="hljs-string">'https://example.org:80'</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-comment">// Set altsvc for a specific stream</span>
stream.<span class="hljs-property">session</span>.<span class="hljs-title function_">altsvc</span>(<span class="hljs-string">'h2=":8000"'</span>, stream.<span class="hljs-property">id</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {
<span class="hljs-comment">// Set altsvc for origin https://example.org:80</span>
session.<span class="hljs-title function_">altsvc</span>(<span class="hljs-string">'h2=":8000"'</span>, <span class="hljs-string">'https://example.org:80'</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-comment">// Set altsvc for a specific stream</span>
stream.<span class="hljs-property">session</span>.<span class="hljs-title function_">altsvc</span>(<span class="hljs-string">'h2=":8000"'</span>, stream.<span class="hljs-property">id</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Sending an <code>ALTSVC</code> frame with a specific stream ID indicates that the alternate
service is associated with the origin of the given <code>Http2Stream</code>.</p>
<p>The <code>alt</code> and origin string <em>must</em> contain only ASCII bytes and are
strictly interpreted as a sequence of ASCII bytes. The special value <code>'clear'</code>
may be passed to clear any previously set alternative service for a given
domain.</p>
<p>When a string is passed for the <code>originOrStream</code> argument, it will be parsed as
a URL and the origin will be derived. For instance, the origin for the
HTTP URL <code>'https://example.org/foo/bar'</code> is the ASCII string
<code>'https://example.org'</code>. An error will be thrown if either the given string
cannot be parsed as a URL or if a valid origin cannot be derived.</p>
<p>A <code>URL</code> object, or any object with an <code>origin</code> property, may be passed as
<code>originOrStream</code>, in which case the value of the <code>origin</code> property will be
used. The value of the <code>origin</code> property <em>must</em> be a properly serialized
ASCII origin.</p>
<h5>Specifying alternative services<span><a class="mark" href="#all_http2_specifying-alternative-services" id="all_http2_specifying-alternative-services">#</a></span><a aria-hidden="true" class="legacy" id="http2_specifying_alternative_services"></a></h5>
<p>The format of the <code>alt</code> parameter is strictly defined by <a href="https://tools.ietf.org/html/rfc7838">RFC 7838</a> as an
ASCII string containing a comma-delimited list of "alternative" protocols
associated with a specific host and port.</p>
<p>For example, the value <code>'h2="example.org:81"'</code> indicates that the HTTP/2
protocol is available on the host <code>'example.org'</code> on TCP/IP port 81. The
host and port <em>must</em> be contained within the quote (<code>"</code>) characters.</p>
<p>Multiple alternatives may be specified, for instance: <code>'h2="example.org:81", h2=":82"'</code>.</p>
<p>The protocol identifier (<code>'h2'</code> in the examples) may be any valid
<a href="https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids">ALPN Protocol ID</a>.</p>
<p>The syntax of these values is not validated by the Node.js implementation and
are passed through as provided by the user or received from the peer.</p>
<h5><code>serverhttp2session.origin(...origins)</code><span><a class="mark" href="#all_http2_serverhttp2sessionoriginorigins" id="all_http2_serverhttp2sessionoriginorigins">#</a></span><a aria-hidden="true" class="legacy" id="http2_serverhttp2session_origin_origins"></a></h5>
<div class="api_metadata">
<span>Added in: v10.12.0</span>
</div>
<ul>
<li><code>origins</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> One or more URL Strings passed as
separate arguments.</li>
</ul>
<p>Submits an <code>ORIGIN</code> frame (as defined by <a href="https://tools.ietf.org/html/rfc8336">RFC 8336</a>) to the connected client
to advertise the set of origins for which the server is capable of providing
authoritative responses.</p>
<pre class="with-48-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> { createSecureServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> options = <span class="hljs-title function_">getSecureOptionsSomehow</span>();
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>();
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {
session.<span class="hljs-title function_">origin</span>(<span class="hljs-string">'https://example.com'</span>, <span class="hljs-string">'https://example.org'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> options = <span class="hljs-title function_">getSecureOptionsSomehow</span>();
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>();
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {
session.<span class="hljs-title function_">origin</span>(<span class="hljs-string">'https://example.com'</span>, <span class="hljs-string">'https://example.org'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>When a string is passed as an <code>origin</code>, it will be parsed as a URL and the
origin will be derived. For instance, the origin for the HTTP URL
<code>'https://example.org/foo/bar'</code> is the ASCII string
<code>'https://example.org'</code>. An error will be thrown if either the given string
cannot be parsed as a URL or if a valid origin cannot be derived.</p>
<p>A <code>URL</code> object, or any object with an <code>origin</code> property, may be passed as
an <code>origin</code>, in which case the value of the <code>origin</code> property will be
used. The value of the <code>origin</code> property <em>must</em> be a properly serialized
ASCII origin.</p>
<p>Alternatively, the <code>origins</code> option may be used when creating a new HTTP/2
server using the <code>http2.createSecureServer()</code> method:</p>
<pre class="with-48-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> { createSecureServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> options = <span class="hljs-title function_">getSecureOptionsSomehow</span>();
options.<span class="hljs-property">origins</span> = [<span class="hljs-string">'https://example.com'</span>, <span class="hljs-string">'https://example.org'</span>];
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>();
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> options = <span class="hljs-title function_">getSecureOptionsSomehow</span>();
options.<span class="hljs-property">origins</span> = [<span class="hljs-string">'https://example.com'</span>, <span class="hljs-string">'https://example.org'</span>];
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>();
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>ClientHttp2Session</code><span><a class="mark" href="#all_http2_class-clienthttp2session" id="all_http2_class-clienthttp2session">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_clienthttp2session"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_http2_class-http2session" class="type"><Http2Session></a></li>
</ul>
<h5>Event: <code>'altsvc'</code><span><a class="mark" href="#all_http2_event-altsvc" id="all_http2_event-altsvc">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_altsvc"></a></h5>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><code>alt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>origin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>streamId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The <code>'altsvc'</code> event is emitted whenever an <code>ALTSVC</code> frame is received by
the client. The event is emitted with the <code>ALTSVC</code> value, origin, and stream
ID. If no <code>origin</code> is provided in the <code>ALTSVC</code> frame, <code>origin</code> will
be an empty string.</p>
<pre class="with-52-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> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://example.org'</span>);
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'altsvc'</span>, <span class="hljs-function">(<span class="hljs-params">alt, origin, streamId</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(alt);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(origin);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(streamId);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://example.org'</span>);
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'altsvc'</span>, <span class="hljs-function">(<span class="hljs-params">alt, origin, streamId</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(alt);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(origin);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(streamId);
});</code><button class="copy-button">copy</button></pre>
<h5>Event: <code>'origin'</code><span><a class="mark" href="#all_http2_event-origin" id="all_http2_event-origin">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_origin"></a></h5>
<div class="api_metadata">
<span>Added in: v10.12.0</span>
</div>
<ul>
<li><code>origins</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>The <code>'origin'</code> event is emitted whenever an <code>ORIGIN</code> frame is received by
the client. The event is emitted with an array of <code>origin</code> strings. The
<code>http2session.originSet</code> will be updated to include the received
origins.</p>
<pre class="with-52-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> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://example.org'</span>);
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'origin'</span>, <span class="hljs-function">(<span class="hljs-params">origins</span>) =></span> {
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n < origins.<span class="hljs-property">length</span>; n++)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(origins[n]);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://example.org'</span>);
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'origin'</span>, <span class="hljs-function">(<span class="hljs-params">origins</span>) =></span> {
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n < origins.<span class="hljs-property">length</span>; n++)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(origins[n]);
});</code><button class="copy-button">copy</button></pre>
<p>The <code>'origin'</code> event is only emitted when using a secure TLS connection.</p>
<h5><code>clienthttp2session.request(headers[, options])</code><span><a class="mark" href="#all_http2_clienthttp2sessionrequestheaders-options" id="all_http2_clienthttp2sessionrequestheaders-options">#</a></span><a aria-hidden="true" class="legacy" id="http2_clienthttp2session_request_headers_options"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>
<p><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a></p>
</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p>
<ul>
<li><code>endStream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the <code>Http2Stream</code> <em>writable</em> side should
be closed initially, such as when sending a <code>GET</code> request that should not
expect a payload body.</li>
<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> and <code>parent</code> identifies a parent Stream,
the created stream is made the sole direct dependency of the parent, with
all other existing dependents made a dependent of the newly created stream.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the numeric identifier of a stream the newly
created stream is dependent on.</li>
<li><code>weight</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the relative dependency of a stream in relation
to other streams with the same <code>parent</code>. The value is a number between <code>1</code>
and <code>256</code> (inclusive).</li>
<li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the
<code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> An AbortSignal that may be used to abort an ongoing
request.</li>
</ul>
</li>
<li>
<p>Returns: <a href="#all_http2_class-clienthttp2stream" class="type"><ClientHttp2Stream></a></p>
</li>
</ul>
<p>For HTTP/2 Client <code>Http2Session</code> instances only, the <code>http2session.request()</code>
creates and returns an <code>Http2Stream</code> instance that can be used to send an
HTTP/2 request to the connected server.</p>
<p>When a <code>ClientHttp2Session</code> is first created, the socket may not yet be
connected. if <code>clienthttp2session.request()</code> is called during this time, the
actual request will be deferred until the socket is ready to go.
If the <code>session</code> is closed before the actual request be executed, an
<code>ERR_HTTP2_GOAWAY_SESSION</code> is thrown.</p>
<p>This method is only available if <code>http2session.type</code> is equal to
<code>http2.constants.NGHTTP2_SESSION_CLIENT</code>.</p>
<pre class="with-62-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> { connect, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> clientSession = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost:1234'</span>);
<span class="hljs-keyword">const</span> {
<span class="hljs-title class_">HTTP2</span>_HEADER_PATH,
<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS,
} = constants;
<span class="hljs-keyword">const</span> req = clientSession.<span class="hljs-title function_">request</span>({ [<span class="hljs-title class_">HTTP2</span>_HEADER_PATH]: <span class="hljs-string">'/'</span> });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS]);
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> { <span class="hljs-comment">/* .. */</span> });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { <span class="hljs-comment">/* .. */</span> });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> clientSession = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost:1234'</span>);
<span class="hljs-keyword">const</span> {
<span class="hljs-title class_">HTTP2</span>_HEADER_PATH,
<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS,
} = http2.<span class="hljs-property">constants</span>;
<span class="hljs-keyword">const</span> req = clientSession.<span class="hljs-title function_">request</span>({ [<span class="hljs-title class_">HTTP2</span>_HEADER_PATH]: <span class="hljs-string">'/'</span> });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS]);
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> { <span class="hljs-comment">/* .. */</span> });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { <span class="hljs-comment">/* .. */</span> });
});</code><button class="copy-button">copy</button></pre>
<p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event
is emitted immediately after queuing the last chunk of payload data to be sent.
The <code>http2stream.sendTrailers()</code> method can then be called to send trailing
headers to the peer.</p>
<p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically
close when the final <code>DATA</code> frame is transmitted. User code must call either
<code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the
<code>Http2Stream</code>.</p>
<p>When <code>options.signal</code> is set with an <code>AbortSignal</code> and then <code>abort</code> on the
corresponding <code>AbortController</code> is called, the request will emit an <code>'error'</code>
event with an <code>AbortError</code> error.</p>
<p>The <code>:method</code> and <code>:path</code> pseudo-headers are not specified within <code>headers</code>,
they respectively default to:</p>
<ul>
<li><code>:method</code> = <code>'GET'</code></li>
<li><code>:path</code> = <code>/</code></li>
</ul>
<h4>Class: <code>Http2Stream</code><span><a class="mark" href="#all_http2_class-http2stream" id="all_http2_class-http2stream">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_http2stream"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>Each instance of the <code>Http2Stream</code> class represents a bidirectional HTTP/2
communications stream over an <code>Http2Session</code> instance. Any single <code>Http2Session</code>
may have up to 2<sup>31</sup>-1 <code>Http2Stream</code> instances over its lifetime.</p>
<p>User code will not construct <code>Http2Stream</code> instances directly. Rather, these
are created, managed, and provided to user code through the <code>Http2Session</code>
instance. On the server, <code>Http2Stream</code> instances are created either in response
to an incoming HTTP request (and handed off to user code via the <code>'stream'</code>
event), or in response to a call to the <code>http2stream.pushStream()</code> method.
On the client, <code>Http2Stream</code> instances are created and returned when either the
<code>http2session.request()</code> method is called, or in response to an incoming
<code>'push'</code> event.</p>
<p>The <code>Http2Stream</code> class is a base for the <a href="#all_http2_class-serverhttp2stream"><code>ServerHttp2Stream</code></a> and
<a href="#all_http2_class-clienthttp2stream"><code>ClientHttp2Stream</code></a> classes, each of which is used specifically by either
the Server or Client side, respectively.</p>
<p>All <code>Http2Stream</code> instances are <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> streams. The <code>Writable</code> side of the
<code>Duplex</code> is used to send data to the connected peer, while the <code>Readable</code> side
is used to receive data sent by the connected peer.</p>
<p>The default text character encoding for an <code>Http2Stream</code> is UTF-8. When using an
<code>Http2Stream</code> to send text, use the <code>'content-type'</code> header to set the character
encoding.</p>
<pre><code class="language-js">stream.<span class="hljs-title function_">respond</span>({
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
<span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
});</code> <button class="copy-button">copy</button></pre>
<h5><code>Http2Stream</code> Lifecycle<span><a class="mark" href="#all_http2_http2stream-lifecycle" id="all_http2_http2stream-lifecycle">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_lifecycle"></a></h5>
<h6>Creation<span><a class="mark" href="#all_http2_creation" id="all_http2_creation">#</a></span><a aria-hidden="true" class="legacy" id="http2_creation"></a></h6>
<p>On the server side, instances of <a href="#all_http2_class-serverhttp2stream"><code>ServerHttp2Stream</code></a> are created either
when:</p>
<ul>
<li>A new HTTP/2 <code>HEADERS</code> frame with a previously unused stream ID is received;</li>
<li>The <code>http2stream.pushStream()</code> method is called.</li>
</ul>
<p>On the client side, instances of <a href="#all_http2_class-clienthttp2stream"><code>ClientHttp2Stream</code></a> are created when the
<code>http2session.request()</code> method is called.</p>
<p>On the client, the <code>Http2Stream</code> instance returned by <code>http2session.request()</code>
may not be immediately ready for use if the parent <code>Http2Session</code> has not yet
been fully established. In such cases, operations called on the <code>Http2Stream</code>
will be buffered until the <code>'ready'</code> event is emitted. User code should rarely,
if ever, need to handle the <code>'ready'</code> event directly. The ready status of an
<code>Http2Stream</code> can be determined by checking the value of <code>http2stream.id</code>. If
the value is <code>undefined</code>, the stream is not yet ready for use.</p>
<h6>Destruction<span><a class="mark" href="#all_http2_destruction" id="all_http2_destruction">#</a></span><a aria-hidden="true" class="legacy" id="http2_destruction"></a></h6>
<p>All <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> instances are destroyed either when:</p>
<ul>
<li>An <code>RST_STREAM</code> frame for the stream is received by the connected peer,
and (for client streams only) pending data has been read.</li>
<li>The <code>http2stream.close()</code> method is called, and (for client streams only)
pending data has been read.</li>
<li>The <code>http2stream.destroy()</code> or <code>http2session.destroy()</code> methods are called.</li>
</ul>
<p>When an <code>Http2Stream</code> instance is destroyed, an attempt will be made to send an
<code>RST_STREAM</code> frame to the connected peer.</p>
<p>When the <code>Http2Stream</code> instance is destroyed, the <code>'close'</code> event will
be emitted. Because <code>Http2Stream</code> is an instance of <code>stream.Duplex</code>, the
<code>'end'</code> event will also be emitted if the stream data is currently flowing.
The <code>'error'</code> event may also be emitted if <code>http2stream.destroy()</code> was called
with an <code>Error</code> passed as the first argument.</p>
<p>After the <code>Http2Stream</code> has been destroyed, the <code>http2stream.destroyed</code>
property will be <code>true</code> and the <code>http2stream.rstCode</code> property will specify the
<code>RST_STREAM</code> error code. The <code>Http2Stream</code> instance is no longer usable once
destroyed.</p>
<h5>Event: <code>'aborted'</code><span><a class="mark" href="#all_http2_event-aborted" id="all_http2_event-aborted">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_aborted"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'aborted'</code> event is emitted whenever a <code>Http2Stream</code> instance is
abnormally aborted in mid-communication.
Its listener does not expect any arguments.</p>
<p>The <code>'aborted'</code> event will only be emitted if the <code>Http2Stream</code> writable side
has not been ended.</p>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_http2_event-close_1" id="all_http2_event-close_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_close_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'close'</code> event is emitted when the <code>Http2Stream</code> is destroyed. Once
this event is emitted, the <code>Http2Stream</code> instance is no longer usable.</p>
<p>The HTTP/2 error code used when closing the stream can be retrieved using
the <code>http2stream.rstCode</code> property. If the code is any value other than
<code>NGHTTP2_NO_ERROR</code> (<code>0</code>), an <code>'error'</code> event will have also been emitted.</p>
<h5>Event: <code>'error'</code><span><a class="mark" href="#all_http2_event-error_1" id="all_http2_event-error_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_error_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</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>
</ul>
<p>The <code>'error'</code> event is emitted when an error occurs during the processing of
an <code>Http2Stream</code>.</p>
<h5>Event: <code>'frameError'</code><span><a class="mark" href="#all_http2_event-frameerror_1" id="all_http2_event-frameerror_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_frameerror_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The frame type.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The error code.</li>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The stream id (or <code>0</code> if the frame isn't associated with a
stream).</li>
</ul>
<p>The <code>'frameError'</code> event is emitted when an error occurs while attempting to
send a frame. When invoked, the handler function will receive an integer
argument identifying the frame type, and an integer argument identifying the
error code. The <code>Http2Stream</code> instance will be destroyed immediately after the
<code>'frameError'</code> event is emitted.</p>
<h5>Event: <code>'ready'</code><span><a class="mark" href="#all_http2_event-ready" id="all_http2_event-ready">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_ready"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'ready'</code> event is emitted when the <code>Http2Stream</code> has been opened, has
been assigned an <code>id</code>, and can be used. The listener does not expect any
arguments.</p>
<h5>Event: <code>'timeout'</code><span><a class="mark" href="#all_http2_event-timeout_1" id="all_http2_event-timeout_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_timeout_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'timeout'</code> event is emitted after no activity is received for this
<code>Http2Stream</code> within the number of milliseconds set using
<code>http2stream.setTimeout()</code>.
Its listener does not expect any arguments.</p>
<h5>Event: <code>'trailers'</code><span><a class="mark" href="#all_http2_event-trailers" id="all_http2_event-trailers">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_trailers"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a> An object describing the headers</li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The associated numeric flags</li>
</ul>
<p>The <code>'trailers'</code> event is emitted when a block of headers associated with
trailing header fields is received. The listener callback is passed the
<a href="#all_http2_headers-object">HTTP/2 Headers Object</a> and flags associated with the headers.</p>
<p>This event might not be emitted if <code>http2stream.end()</code> is called
before trailers are received and the incoming data is not being read or
listened for.</p>
<pre><code class="language-js">stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'trailers'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers);
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'wantTrailers'</code><span><a class="mark" href="#all_http2_event-wanttrailers" id="all_http2_event-wanttrailers">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_wanttrailers"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>The <code>'wantTrailers'</code> event is emitted when the <code>Http2Stream</code> has queued the
final <code>DATA</code> frame to be sent on a frame and the <code>Http2Stream</code> is ready to send
trailing headers. When initiating a request or response, the <code>waitForTrailers</code>
option must be set for this event to be emitted.</p>
<h5><code>http2stream.aborted</code><span><a class="mark" href="#all_http2_http2streamaborted" id="all_http2_http2streamaborted">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_aborted"></a></h5>
<div class="api_metadata">
<span>Added in: v8.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>Set to <code>true</code> if the <code>Http2Stream</code> instance was aborted abnormally. When set,
the <code>'aborted'</code> event will have been emitted.</p>
<h5><code>http2stream.bufferSize</code><span><a class="mark" href="#all_http2_http2streambuffersize" id="all_http2_http2streambuffersize">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_buffersize"></a></h5>
<div class="api_metadata">
<span>Added in: v11.2.0, v10.16.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 shows the number of characters currently buffered to be written.
See <a href="#all_net_socketbuffersize"><code>net.Socket.bufferSize</code></a> for details.</p>
<h5><code>http2stream.close(code[, callback])</code><span><a class="mark" href="#all_http2_http2streamclosecode-callback" id="all_http2_http2streamclosecode-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_close_code_callback"></a></h5>
<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</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>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Unsigned 32-bit integer identifying the error code.
<strong>Default:</strong> <code>http2.constants.NGHTTP2_NO_ERROR</code> (<code>0x00</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> An optional function registered to listen for the
<code>'close'</code> event.</li>
</ul>
<p>Closes the <code>Http2Stream</code> instance by sending an <code>RST_STREAM</code> frame to the
connected HTTP/2 peer.</p>
<h5><code>http2stream.closed</code><span><a class="mark" href="#all_http2_http2streamclosed" id="all_http2_http2streamclosed">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_closed"></a></h5>
<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>Set to <code>true</code> if the <code>Http2Stream</code> instance has been closed.</p>
<h5><code>http2stream.destroyed</code><span><a class="mark" href="#all_http2_http2streamdestroyed" id="all_http2_http2streamdestroyed">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_destroyed"></a></h5>
<div class="api_metadata">
<span>Added in: v8.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>Set to <code>true</code> if the <code>Http2Stream</code> instance has been destroyed and is no longer
usable.</p>
<h5><code>http2stream.endAfterHeaders</code><span><a class="mark" href="#all_http2_http2streamendafterheaders" id="all_http2_http2streamendafterheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_endafterheaders"></a></h5>
<div class="api_metadata">
<span>Added in: v10.11.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>Set to <code>true</code> if the <code>END_STREAM</code> flag was set in the request or response
HEADERS frame received, indicating that no additional data should be received
and the readable side of the <code>Http2Stream</code> will be closed.</p>
<h5><code>http2stream.id</code><span><a class="mark" href="#all_http2_http2streamid" id="all_http2_http2streamid">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_id"></a></h5>
<div class="api_metadata">
<span>Added in: v8.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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>The numeric stream identifier of this <code>Http2Stream</code> instance. Set to <code>undefined</code>
if the stream identifier has not yet been assigned.</p>
<h5><code>http2stream.pending</code><span><a class="mark" href="#all_http2_http2streampending" id="all_http2_http2streampending">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_pending"></a></h5>
<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>Set to <code>true</code> if the <code>Http2Stream</code> instance has not yet been assigned a
numeric stream identifier.</p>
<h5><code>http2stream.priority(options)</code><span><a class="mark" href="#all_http2_http2streampriorityoptions" id="all_http2_http2streampriorityoptions">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_priority_options"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.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>
<ul>
<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> and <code>parent</code> identifies a parent Stream,
this stream is made the sole direct dependency of the parent, with
all other existing dependents made a dependent of this stream. <strong>Default:</strong>
<code>false</code>.</li>
<li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the numeric identifier of a stream this stream
is dependent on.</li>
<li><code>weight</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the relative dependency of a stream in relation
to other streams with the same <code>parent</code>. The value is a number between <code>1</code>
and <code>256</code> (inclusive).</li>
<li><code>silent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, changes the priority locally without
sending a <code>PRIORITY</code> frame to the connected peer.</li>
</ul>
</li>
</ul>
<p>Updates the priority for this <code>Http2Stream</code> instance.</p>
<h5><code>http2stream.rstCode</code><span><a class="mark" href="#all_http2_http2streamrstcode" id="all_http2_http2streamrstcode">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_rstcode"></a></h5>
<div class="api_metadata">
<span>Added in: v8.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>Set to the <code>RST_STREAM</code> <a href="#all_http2_error-codes-for-rst_stream-and-goaway">error code</a> reported when the <code>Http2Stream</code> is
destroyed after either receiving an <code>RST_STREAM</code> frame from the connected peer,
calling <code>http2stream.close()</code>, or <code>http2stream.destroy()</code>. Will be
<code>undefined</code> if the <code>Http2Stream</code> has not been closed.</p>
<h5><code>http2stream.sentHeaders</code><span><a class="mark" href="#all_http2_http2streamsentheaders" id="all_http2_http2streamsentheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_sentheaders"></a></h5>
<div class="api_metadata">
<span>Added in: v9.5.0</span>
</div>
<ul>
<li><a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a></li>
</ul>
<p>An object containing the outbound headers sent for this <code>Http2Stream</code>.</p>
<h5><code>http2stream.sentInfoHeaders</code><span><a class="mark" href="#all_http2_http2streamsentinfoheaders" id="all_http2_http2streamsentinfoheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_sentinfoheaders"></a></h5>
<div class="api_metadata">
<span>Added in: v9.5.0</span>
</div>
<ul>
<li><a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object[]></a></li>
</ul>
<p>An array of objects containing the outbound informational (additional) headers
sent for this <code>Http2Stream</code>.</p>
<h5><code>http2stream.sentTrailers</code><span><a class="mark" href="#all_http2_http2streamsenttrailers" id="all_http2_http2streamsenttrailers">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_senttrailers"></a></h5>
<div class="api_metadata">
<span>Added in: v9.5.0</span>
</div>
<ul>
<li><a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a></li>
</ul>
<p>An object containing the outbound trailers sent for this <code>HttpStream</code>.</p>
<h5><code>http2stream.session</code><span><a class="mark" href="#all_http2_http2streamsession" id="all_http2_http2streamsession">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_session"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_http2_class-http2session" class="type"><Http2Session></a></li>
</ul>
<p>A reference to the <code>Http2Session</code> instance that owns this <code>Http2Stream</code>. The
value will be <code>undefined</code> after the <code>Http2Stream</code> instance is destroyed.</p>
<h5><code>http2stream.setTimeout(msecs, callback)</code><span><a class="mark" href="#all_http2_http2streamsettimeoutmsecs-callback" id="all_http2_http2streamsettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_settimeout_msecs_callback"></a></h5>
<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</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>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<pre class="with-56-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> { connect, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://example.org:8000'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">NGHTTP2</span>_CANCEL } = constants;
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });
<span class="hljs-comment">// Cancel the stream if there's no activity after 5 seconds</span>
req.<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">5000</span>, <span class="hljs-function">() =></span> req.<span class="hljs-title function_">close</span>(<span class="hljs-title class_">NGHTTP2</span>_CANCEL));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://example.org:8000'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">NGHTTP2</span>_CANCEL } = http2.<span class="hljs-property">constants</span>;
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });
<span class="hljs-comment">// Cancel the stream if there's no activity after 5 seconds</span>
req.<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">5000</span>, <span class="hljs-function">() =></span> req.<span class="hljs-title function_">close</span>(<span class="hljs-title class_">NGHTTP2</span>_CANCEL));</code><button class="copy-button">copy</button></pre>
<h5><code>http2stream.state</code><span><a class="mark" href="#all_http2_http2streamstate" id="all_http2_http2streamstate">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_state"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>Provides miscellaneous information about the current state of the
<code>Http2Stream</code>.</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>localWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes the connected peer may send
for this <code>Http2Stream</code> without receiving a <code>WINDOW_UPDATE</code>.</li>
<li><code>state</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A flag indicating the low-level current state of the
<code>Http2Stream</code> as determined by <code>nghttp2</code>.</li>
<li><code>localClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <code>1</code> if this <code>Http2Stream</code> has been closed locally.</li>
<li><code>remoteClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <code>1</code> if this <code>Http2Stream</code> has been closed
remotely.</li>
<li><code>sumDependencyWeight</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The sum weight of all <code>Http2Stream</code>
instances that depend on this <code>Http2Stream</code> as specified using
<code>PRIORITY</code> frames.</li>
<li><code>weight</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The priority weight of this <code>Http2Stream</code>.</li>
</ul>
</li>
</ul>
<p>A current state of this <code>Http2Stream</code>.</p>
<h5><code>http2stream.sendTrailers(headers)</code><span><a class="mark" href="#all_http2_http2streamsendtrailersheaders" id="all_http2_http2streamsendtrailersheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_sendtrailers_headers"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a></li>
</ul>
<p>Sends a trailing <code>HEADERS</code> frame to the connected HTTP/2 peer. This method
will cause the <code>Http2Stream</code> to be immediately closed and must only be
called after the <code>'wantTrailers'</code> event has been emitted. When sending a
request or sending a response, the <code>options.waitForTrailers</code> option must be set
in order to keep the <code>Http2Stream</code> open after the final <code>DATA</code> frame so that
trailers can be sent.</p>
<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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>(<span class="hljs-literal">undefined</span>, { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">xyz</span>: <span class="hljs-string">'abc'</span> });
});
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Hello World'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>(<span class="hljs-literal">undefined</span>, { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">xyz</span>: <span class="hljs-string">'abc'</span> });
});
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Hello World'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header
fields (e.g. <code>':method'</code>, <code>':path'</code>, etc).</p>
<h4>Class: <code>ClientHttp2Stream</code><span><a class="mark" href="#all_http2_class-clienthttp2stream" id="all_http2_class-clienthttp2stream">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_clienthttp2stream"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends <a href="#all_http2_class-http2stream" class="type"><Http2Stream></a></li>
</ul>
<p>The <code>ClientHttp2Stream</code> class is an extension of <code>Http2Stream</code> that is
used exclusively on HTTP/2 Clients. <code>Http2Stream</code> instances on the client
provide events such as <code>'response'</code> and <code>'push'</code> that are only relevant on
the client.</p>
<h5>Event: <code>'continue'</code><span><a class="mark" href="#all_http2_event-continue" id="all_http2_event-continue">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_continue"></a></h5>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>Emitted when the server sends a <code>100 Continue</code> status, usually because
the request contained <code>Expect: 100-continue</code>. This is an instruction that
the client should send the request body.</p>
<h5>Event: <code>'headers'</code><span><a class="mark" href="#all_http2_event-headers" id="all_http2_event-headers">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_headers"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a></li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The <code>'headers'</code> event is emitted when an additional block of headers is received
for a stream, such as when a block of <code>1xx</code> informational headers is received.
The listener callback is passed the <a href="#all_http2_headers-object">HTTP/2 Headers Object</a> and flags
associated with the headers.</p>
<pre><code class="language-js">stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'headers'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers);
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'push'</code><span><a class="mark" href="#all_http2_event-push" id="all_http2_event-push">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_push"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a></li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The <code>'push'</code> event is emitted when response headers for a Server Push stream
are received. The listener callback is passed the <a href="#all_http2_headers-object">HTTP/2 Headers Object</a> and
flags associated with the headers.</p>
<pre><code class="language-js">stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'push'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers);
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'response'</code><span><a class="mark" href="#all_http2_event-response" id="all_http2_event-response">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_response"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a></li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The <code>'response'</code> event is emitted when a response <code>HEADERS</code> frame has been
received for this stream from the connected HTTP/2 server. The listener is
invoked with two arguments: an <code>Object</code> containing the received
<a href="#all_http2_headers-object">HTTP/2 Headers Object</a>, and flags associated with the headers.</p>
<pre class="with-50-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> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost'</span>);
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[<span class="hljs-string">':status'</span>]);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost'</span>);
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[<span class="hljs-string">':status'</span>]);
});</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>ServerHttp2Stream</code><span><a class="mark" href="#all_http2_class-serverhttp2stream" id="all_http2_class-serverhttp2stream">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_serverhttp2stream"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_http2_class-http2stream" class="type"><Http2Stream></a></li>
</ul>
<p>The <code>ServerHttp2Stream</code> class is an extension of <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> that is
used exclusively on HTTP/2 Servers. <code>Http2Stream</code> instances on the server
provide additional methods such as <code>http2stream.pushStream()</code> and
<code>http2stream.respond()</code> that are only relevant on the server.</p>
<h5><code>http2stream.additionalHeaders(headers)</code><span><a class="mark" href="#all_http2_http2streamadditionalheadersheaders" id="all_http2_http2streamadditionalheadersheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_additionalheaders_headers"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a></li>
</ul>
<p>Sends an additional informational <code>HEADERS</code> frame to the connected HTTP/2 peer.</p>
<h5><code>http2stream.headersSent</code><span><a class="mark" href="#all_http2_http2streamheaderssent" id="all_http2_http2streamheaderssent">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_headerssent"></a></h5>
<div class="api_metadata">
<span>Added in: v8.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>True if headers were sent, false otherwise (read-only).</p>
<h5><code>http2stream.pushAllowed</code><span><a class="mark" href="#all_http2_http2streampushallowed" id="all_http2_http2streampushallowed">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_pushallowed"></a></h5>
<div class="api_metadata">
<span>Added in: v8.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>Read-only property mapped to the <code>SETTINGS_ENABLE_PUSH</code> flag of the remote
client's most recent <code>SETTINGS</code> frame. Will be <code>true</code> if the remote peer
accepts push streams, <code>false</code> otherwise. Settings are the same for every
<code>Http2Stream</code> in the same <code>Http2Session</code>.</p>
<h5><code>http2stream.pushStream(headers[, options], callback)</code><span><a class="mark" href="#all_http2_http2streampushstreamheaders-options-callback" id="all_http2_http2streampushstreamheaders-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_pushstream_headers_options_callback"></a></h5>
<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</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>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></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>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> and <code>parent</code> identifies a parent Stream,
the created stream is made the sole direct dependency of the parent, with
all other existing dependents made a dependent of the newly created stream.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the numeric identifier of a stream the newly
created stream is dependent on.</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> Callback that is called once the push stream has been
initiated.
<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>pushStream</code> <a href="#all_http2_class-serverhttp2stream" class="type"><ServerHttp2Stream></a> The returned <code>pushStream</code> object.</li>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a> Headers object the <code>pushStream</code> was
initiated with.</li>
</ul>
</li>
</ul>
<p>Initiates a push stream. The callback is invoked with the new <code>Http2Stream</code>
instance created for the push stream passed as the second argument, or an
<code>Error</code> passed as the first argument.</p>
<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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> });
stream.<span class="hljs-title function_">pushStream</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> }, <span class="hljs-function">(<span class="hljs-params">err, pushStream, headers</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
pushStream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> });
pushStream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some pushed data'</span>);
});
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some data'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> });
stream.<span class="hljs-title function_">pushStream</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> }, <span class="hljs-function">(<span class="hljs-params">err, pushStream, headers</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
pushStream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> });
pushStream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some pushed data'</span>);
});
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some data'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Setting the weight of a push stream is not allowed in the <code>HEADERS</code> frame. Pass
a <code>weight</code> value to <code>http2stream.priority</code> with the <code>silent</code> option set to
<code>true</code> to enable server-side bandwidth balancing between concurrent streams.</p>
<p>Calling <code>http2stream.pushStream()</code> from within a pushed stream is not permitted
and will throw an error.</p>
<h5><code>http2stream.respond([headers[, options]])</code><span><a class="mark" href="#all_http2_http2streamrespondheaders-options" id="all_http2_http2streamrespondheaders-options">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_respond_headers_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>v14.5.0, v12.19.0</td>
<td><p>Allow explicitly setting date headers.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></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>endStream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Set to <code>true</code> to indicate that the response will not
include payload data.</li>
<li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the
<code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> });
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some data'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> });
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some data'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Initiates a response. When the <code>options.waitForTrailers</code> option is set, the
<code>'wantTrailers'</code> event will be emitted immediately after queuing the last chunk
of payload data to be sent. The <code>http2stream.sendTrailers()</code> method can then be
used to sent trailing header fields to the peer.</p>
<p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically
close when the final <code>DATA</code> frame is transmitted. User code must call either
<code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the
<code>Http2Stream</code>.</p>
<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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> }, { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">ABC</span>: <span class="hljs-string">'some value to send'</span> });
});
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some data'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> }, { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">ABC</span>: <span class="hljs-string">'some value to send'</span> });
});
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some data'</span>);
});</code><button class="copy-button">copy</button></pre>
<h5><code>http2stream.respondWithFD(fd[, headers[, options]])</code><span><a class="mark" href="#all_http2_http2streamrespondwithfdfd-headers-options" id="all_http2_http2streamrespondwithfdfd-headers-options">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_respondwithfd_fd_headers_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>v14.5.0, v12.19.0</td>
<td><p>Allow explicitly setting date headers.</p></td></tr>
<tr><td>v12.12.0</td>
<td><p>The <code>fd</code> option may now be a <code>FileHandle</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Any readable file descriptor, not necessarily for a regular file, is supported now.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="#all_fs_class-filehandle" class="type"><FileHandle></a> A readable file descriptor.</li>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></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>statCheck</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the
<code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The offset position at which to begin reading.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The amount of data from the fd to send.</li>
</ul>
</li>
</ul>
<p>Initiates a response whose data is read from the given file descriptor. No
validation is performed on the given file descriptor. If an error occurs while
attempting to read data using the file descriptor, the <code>Http2Stream</code> will be
closed using an <code>RST_STREAM</code> frame using the standard <code>INTERNAL_ERROR</code> code.</p>
<p>When used, the <code>Http2Stream</code> object's <code>Duplex</code> interface will be closed
automatically.</p>
<pre class="with-57-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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">import</span> { openSync, fstatSync, closeSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-keyword">const</span> fd = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'/some/file'</span>, <span class="hljs-string">'r'</span>);
<span class="hljs-keyword">const</span> stat = <span class="hljs-title function_">fstatSync</span>(fd);
<span class="hljs-keyword">const</span> headers = {
<span class="hljs-string">'content-length'</span>: stat.<span class="hljs-property">size</span>,
<span class="hljs-string">'last-modified'</span>: stat.<span class="hljs-property">mtime</span>.<span class="hljs-title function_">toUTCString</span>(),
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
};
stream.<span class="hljs-title function_">respondWithFD</span>(fd, headers);
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">closeSync</span>(fd));
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</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> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-keyword">const</span> fd = fs.<span class="hljs-title function_">openSync</span>(<span class="hljs-string">'/some/file'</span>, <span class="hljs-string">'r'</span>);
<span class="hljs-keyword">const</span> stat = fs.<span class="hljs-title function_">fstatSync</span>(fd);
<span class="hljs-keyword">const</span> headers = {
<span class="hljs-string">'content-length'</span>: stat.<span class="hljs-property">size</span>,
<span class="hljs-string">'last-modified'</span>: stat.<span class="hljs-property">mtime</span>.<span class="hljs-title function_">toUTCString</span>(),
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
};
stream.<span class="hljs-title function_">respondWithFD</span>(fd, headers);
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> fs.<span class="hljs-title function_">closeSync</span>(fd));
});</code><button class="copy-button">copy</button></pre>
<p>The optional <code>options.statCheck</code> function may be specified to give user code
an opportunity to set additional content headers based on the <code>fs.Stat</code> details
of the given fd. If the <code>statCheck</code> function is provided, the
<code>http2stream.respondWithFD()</code> method will perform an <code>fs.fstat()</code> call to
collect details on the provided file descriptor.</p>
<p>The <code>offset</code> and <code>length</code> options may be used to limit the response to a
specific range subset. This can be used, for instance, to support HTTP Range
requests.</p>
<p>The file descriptor or <code>FileHandle</code> is not closed when the stream is closed,
so it will need to be closed manually once it is no longer needed.
Using the same file descriptor concurrently for multiple streams
is not supported and may result in data loss. Re-using a file descriptor
after a stream has finished is supported.</p>
<p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event
will be emitted immediately after queuing the last chunk of payload data to be
sent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing
header fields to the peer.</p>
<p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically
close when the final <code>DATA</code> frame is transmitted. User code <em>must</em> call either
<code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the
<code>Http2Stream</code>.</p>
<pre class="with-57-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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">import</span> { openSync, fstatSync, closeSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-keyword">const</span> fd = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'/some/file'</span>, <span class="hljs-string">'r'</span>);
<span class="hljs-keyword">const</span> stat = <span class="hljs-title function_">fstatSync</span>(fd);
<span class="hljs-keyword">const</span> headers = {
<span class="hljs-string">'content-length'</span>: stat.<span class="hljs-property">size</span>,
<span class="hljs-string">'last-modified'</span>: stat.<span class="hljs-property">mtime</span>.<span class="hljs-title function_">toUTCString</span>(),
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
};
stream.<span class="hljs-title function_">respondWithFD</span>(fd, headers, { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">ABC</span>: <span class="hljs-string">'some value to send'</span> });
});
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">closeSync</span>(fd));
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</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> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-keyword">const</span> fd = fs.<span class="hljs-title function_">openSync</span>(<span class="hljs-string">'/some/file'</span>, <span class="hljs-string">'r'</span>);
<span class="hljs-keyword">const</span> stat = fs.<span class="hljs-title function_">fstatSync</span>(fd);
<span class="hljs-keyword">const</span> headers = {
<span class="hljs-string">'content-length'</span>: stat.<span class="hljs-property">size</span>,
<span class="hljs-string">'last-modified'</span>: stat.<span class="hljs-property">mtime</span>.<span class="hljs-title function_">toUTCString</span>(),
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
};
stream.<span class="hljs-title function_">respondWithFD</span>(fd, headers, { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">ABC</span>: <span class="hljs-string">'some value to send'</span> });
});
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> fs.<span class="hljs-title function_">closeSync</span>(fd));
});</code><button class="copy-button">copy</button></pre>
<h5><code>http2stream.respondWithFile(path[, headers[, options]])</code><span><a class="mark" href="#all_http2_http2streamrespondwithfilepath-headers-options" id="all_http2_http2streamrespondwithfilepath-headers-options">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_respondwithfile_path_headers_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>v14.5.0, v12.19.0</td>
<td><p>Allow explicitly setting date headers.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Any readable file, not necessarily a regular file, is supported now.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a></li>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></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>statCheck</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li><code>onError</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback function invoked in the case of an
error before send.</li>
<li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the
<code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The offset position at which to begin reading.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The amount of data from the fd to send.</li>
</ul>
</li>
</ul>
<p>Sends a regular file as the response. The <code>path</code> must specify a regular file
or an <code>'error'</code> event will be emitted on the <code>Http2Stream</code> object.</p>
<p>When used, the <code>Http2Stream</code> object's <code>Duplex</code> interface will be closed
automatically.</p>
<p>The optional <code>options.statCheck</code> function may be specified to give user code
an opportunity to set additional content headers based on the <code>fs.Stat</code> details
of the given file:</p>
<p>If an error occurs while attempting to read the file data, the <code>Http2Stream</code>
will be closed using an <code>RST_STREAM</code> frame using the standard <code>INTERNAL_ERROR</code>
code. If the <code>onError</code> callback is defined, then it will be called. Otherwise
the stream will be destroyed.</p>
<p>Example using a file path:</p>
<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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-keyword">function</span> <span class="hljs-title function_">statCheck</span>(<span class="hljs-params">stat, headers</span>) {
headers[<span class="hljs-string">'last-modified'</span>] = stat.<span class="hljs-property">mtime</span>.<span class="hljs-title function_">toUTCString</span>();
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">onError</span>(<span class="hljs-params">err</span>) {
<span class="hljs-comment">// stream.respond() can throw if the stream has been destroyed by</span>
<span class="hljs-comment">// the other side.</span>
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'ENOENT'</span>) {
stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">404</span> });
} <span class="hljs-keyword">else</span> {
stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">500</span> });
}
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-comment">// Perform actual error handling.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}
stream.<span class="hljs-title function_">end</span>();
}
stream.<span class="hljs-title function_">respondWithFile</span>(<span class="hljs-string">'/some/file'</span>,
{ <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> },
{ statCheck, onError });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-keyword">function</span> <span class="hljs-title function_">statCheck</span>(<span class="hljs-params">stat, headers</span>) {
headers[<span class="hljs-string">'last-modified'</span>] = stat.<span class="hljs-property">mtime</span>.<span class="hljs-title function_">toUTCString</span>();
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">onError</span>(<span class="hljs-params">err</span>) {
<span class="hljs-comment">// stream.respond() can throw if the stream has been destroyed by</span>
<span class="hljs-comment">// the other side.</span>
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'ENOENT'</span>) {
stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">404</span> });
} <span class="hljs-keyword">else</span> {
stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">500</span> });
}
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-comment">// Perform actual error handling.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}
stream.<span class="hljs-title function_">end</span>();
}
stream.<span class="hljs-title function_">respondWithFile</span>(<span class="hljs-string">'/some/file'</span>,
{ <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> },
{ statCheck, onError });
});</code><button class="copy-button">copy</button></pre>
<p>The <code>options.statCheck</code> function may also be used to cancel the send operation
by returning <code>false</code>. For instance, a conditional request may check the stat
results to determine if the file has been modified to return an appropriate
<code>304</code> response:</p>
<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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-keyword">function</span> <span class="hljs-title function_">statCheck</span>(<span class="hljs-params">stat, headers</span>) {
<span class="hljs-comment">// Check the stat here...</span>
stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">304</span> });
<span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; <span class="hljs-comment">// Cancel the send operation</span>
}
stream.<span class="hljs-title function_">respondWithFile</span>(<span class="hljs-string">'/some/file'</span>,
{ <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> },
{ statCheck });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
<span class="hljs-keyword">function</span> <span class="hljs-title function_">statCheck</span>(<span class="hljs-params">stat, headers</span>) {
<span class="hljs-comment">// Check the stat here...</span>
stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">304</span> });
<span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; <span class="hljs-comment">// Cancel the send operation</span>
}
stream.<span class="hljs-title function_">respondWithFile</span>(<span class="hljs-string">'/some/file'</span>,
{ <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> },
{ statCheck });
});</code><button class="copy-button">copy</button></pre>
<p>The <code>content-length</code> header field will be automatically set.</p>
<p>The <code>offset</code> and <code>length</code> options may be used to limit the response to a
specific range subset. This can be used, for instance, to support HTTP Range
requests.</p>
<p>The <code>options.onError</code> function may also be used to handle all the errors
that could happen before the delivery of the file is initiated. The
default behavior is to destroy the stream.</p>
<p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event
will be emitted immediately after queuing the last chunk of payload data to be
sent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing
header fields to the peer.</p>
<p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically
close when the final <code>DATA</code> frame is transmitted. User code must call either
<code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the
<code>Http2Stream</code>.</p>
<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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respondWithFile</span>(<span class="hljs-string">'/some/file'</span>,
{ <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> },
{ <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">ABC</span>: <span class="hljs-string">'some value to send'</span> });
});
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
stream.<span class="hljs-title function_">respondWithFile</span>(<span class="hljs-string">'/some/file'</span>,
{ <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> },
{ <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">ABC</span>: <span class="hljs-string">'some value to send'</span> });
});
});</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>Http2Server</code><span><a class="mark" href="#all_http2_class-http2server" id="all_http2_class-http2server">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_http2server"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<p>Instances of <code>Http2Server</code> are created using the <code>http2.createServer()</code>
function. The <code>Http2Server</code> class is not exported directly by the
<code>node:http2</code> module.</p>
<h5>Event: <code>'checkContinue'</code><span><a class="mark" href="#all_http2_event-checkcontinue" id="all_http2_event-checkcontinue">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_checkcontinue"></a></h5>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http2_class-http2http2serverrequest" class="type"><http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="#all_http2_class-http2http2serverresponse" class="type"><http2.Http2ServerResponse></a></li>
</ul>
<p>If a <a href="#all_http2_event-request"><code>'request'</code></a> listener is registered or <a href="#all_http2_http2createserveroptions-onrequesthandler"><code>http2.createServer()</code></a> is
supplied a callback function, the <code>'checkContinue'</code> event is emitted each time
a request with an HTTP <code>Expect: 100-continue</code> is received. If this event is
not listened for, the server will automatically respond with a status
<code>100 Continue</code> as appropriate.</p>
<p>Handling this event involves calling <a href="#all_http2_responsewritecontinue"><code>response.writeContinue()</code></a> if the
client should continue to send the request body, or generating an appropriate
HTTP response (e.g. 400 Bad Request) if the client should not continue to send
the request body.</p>
<p>When this event is emitted and handled, the <a href="#all_http2_event-request"><code>'request'</code></a> event will
not be emitted.</p>
<h5>Event: <code>'connection'</code><span><a class="mark" href="#all_http2_event-connection" id="all_http2_event-connection">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_connection"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>This event is emitted when a new TCP stream is established. <code>socket</code> is
typically an object of type <a href="#all_net_class-netsocket"><code>net.Socket</code></a>. Usually users will not want to
access this event.</p>
<p>This event can also be explicitly emitted by users to inject connections
into the HTTP server. In that case, any <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> stream can be passed.</p>
<h5>Event: <code>'request'</code><span><a class="mark" href="#all_http2_event-request" id="all_http2_event-request">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_request"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http2_class-http2http2serverrequest" class="type"><http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="#all_http2_class-http2http2serverresponse" class="type"><http2.Http2ServerResponse></a></li>
</ul>
<p>Emitted each time there is a request. There may be multiple requests
per session. See the <a href="#all_http2_compatibility-api">Compatibility API</a>.</p>
<h5>Event: <code>'session'</code><span><a class="mark" href="#all_http2_event-session" id="all_http2_event-session">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_session"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>session</code> <a href="#all_http2_class-serverhttp2session" class="type"><ServerHttp2Session></a></li>
</ul>
<p>The <code>'session'</code> event is emitted when a new <code>Http2Session</code> is created by the
<code>Http2Server</code>.</p>
<h5>Event: <code>'sessionError'</code><span><a class="mark" href="#all_http2_event-sessionerror" id="all_http2_event-sessionerror">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_sessionerror"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</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><code>session</code> <a href="#all_http2_class-serverhttp2session" class="type"><ServerHttp2Session></a></li>
</ul>
<p>The <code>'sessionError'</code> event is emitted when an <code>'error'</code> event is emitted by
an <code>Http2Session</code> object associated with the <code>Http2Server</code>.</p>
<h5>Event: <code>'stream'</code><span><a class="mark" href="#all_http2_event-stream_1" id="all_http2_event-stream_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_stream_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_http2_class-http2stream" class="type"><Http2Stream></a> A reference to the stream</li>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a> An object describing the headers</li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The associated numeric flags</li>
<li><code>rawHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array containing the raw header names followed by
their respective values.</li>
</ul>
<p>The <code>'stream'</code> event is emitted when a <code>'stream'</code> event has been emitted by
an <code>Http2Session</code> associated with the server.</p>
<p>See also <a href="#all_http2_event-stream"><code>Http2Session</code>'s <code>'stream'</code> event</a>.</p>
<pre class="with-53-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> { createServer, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> {
<span class="hljs-title class_">HTTP2</span>_HEADER_METHOD,
<span class="hljs-title class_">HTTP2</span>_HEADER_PATH,
<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS,
<span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE,
} = constants;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers, flags</span>) =></span> {
<span class="hljs-keyword">const</span> method = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_METHOD];
<span class="hljs-keyword">const</span> path = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_PATH];
<span class="hljs-comment">// ...</span>
stream.<span class="hljs-title function_">respond</span>({
[<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS]: <span class="hljs-number">200</span>,
[<span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE]: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
});
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello '</span>);
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> {
<span class="hljs-title class_">HTTP2</span>_HEADER_METHOD,
<span class="hljs-title class_">HTTP2</span>_HEADER_PATH,
<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS,
<span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE,
} = http2.<span class="hljs-property">constants</span>;
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers, flags</span>) =></span> {
<span class="hljs-keyword">const</span> method = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_METHOD];
<span class="hljs-keyword">const</span> path = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_PATH];
<span class="hljs-comment">// ...</span>
stream.<span class="hljs-title function_">respond</span>({
[<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS]: <span class="hljs-number">200</span>,
[<span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE]: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
});
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello '</span>);
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world'</span>);
});</code><button class="copy-button">copy</button></pre>
<h5>Event: <code>'timeout'</code><span><a class="mark" href="#all_http2_event-timeout_2" id="all_http2_event-timeout_2">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_timeout_2"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for
a given number of milliseconds set using <code>http2server.setTimeout()</code>.
<strong>Default:</strong> 0 (no timeout)</p>
<h5><code>server.close([callback])</code><span><a class="mark" href="#all_http2_serverclosecallback" id="all_http2_serverclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_close_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.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></li>
</ul>
<p>Stops the server from establishing new sessions. This does not prevent new
request streams from being created due to the persistent nature of HTTP/2
sessions. To gracefully shut down the server, call <a href="#all_http2_http2sessionclosecallback"><code>http2session.close()</code></a> on
all active sessions.</p>
<p>If <code>callback</code> is provided, it is not invoked until all active sessions have been
closed, although the server has already stopped allowing new sessions. See
<a href="#all_net_serverclosecallback"><code>net.Server.close()</code></a> for more details.</p>
<h5><code>server[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_http2_serversymbolasyncdispose" id="all_http2_serversymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_symbol_asyncdispose"></a></h5>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_http2_serverclosecallback"><code>server.close()</code></a> and returns a promise that fulfills when the
server has closed.</p>
<h5><code>server.setTimeout([msecs][, callback])</code><span><a class="mark" href="#all_http2_serversettimeoutmsecs-callback" id="all_http2_serversettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_settimeout_msecs_callback"></a></h5>
<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</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>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> 0 (no timeout)</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_http2_class-http2server" class="type"><Http2Server></a></li>
</ul>
<p>Used to set the timeout value for http2 server requests,
and sets a callback function that is called when there is no activity
on the <code>Http2Server</code> after <code>msecs</code> milliseconds.</p>
<p>The given callback is registered as a listener on the <code>'timeout'</code> event.</p>
<p>In case if <code>callback</code> is not a function, a new <code>ERR_INVALID_ARG_TYPE</code>
error will be thrown.</p>
<h5><code>server.timeout</code><span><a class="mark" href="#all_http2_servertimeout" id="all_http2_servertimeout">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_timeout"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Timeout in milliseconds. <strong>Default:</strong> 0 (no timeout)</li>
</ul>
<p>The number of milliseconds of inactivity before a socket is presumed
to have timed out.</p>
<p>A value of <code>0</code> will disable the timeout behavior on incoming connections.</p>
<p>The socket timeout logic is set up on connection, so changing this
value only affects new connections to the server, not any existing connections.</p>
<h5><code>server.updateSettings([settings])</code><span><a class="mark" href="#all_http2_serverupdatesettingssettings" id="all_http2_serverupdatesettingssettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_updatesettings_settings"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a></li>
</ul>
<p>Used to update the server with the provided settings.</p>
<p>Throws <code>ERR_HTTP2_INVALID_SETTING_VALUE</code> for invalid <code>settings</code> values.</p>
<p>Throws <code>ERR_INVALID_ARG_TYPE</code> for invalid <code>settings</code> argument.</p>
<h4>Class: <code>Http2SecureServer</code><span><a class="mark" href="#all_http2_class-http2secureserver" id="all_http2_class-http2secureserver">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_http2secureserver"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_tls_class-tlsserver" class="type"><tls.Server></a></li>
</ul>
<p>Instances of <code>Http2SecureServer</code> are created using the
<code>http2.createSecureServer()</code> function. The <code>Http2SecureServer</code> class is not
exported directly by the <code>node:http2</code> module.</p>
<h5>Event: <code>'checkContinue'</code><span><a class="mark" href="#all_http2_event-checkcontinue_1" id="all_http2_event-checkcontinue_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_checkcontinue_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http2_class-http2http2serverrequest" class="type"><http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="#all_http2_class-http2http2serverresponse" class="type"><http2.Http2ServerResponse></a></li>
</ul>
<p>If a <a href="#all_http2_event-request"><code>'request'</code></a> listener is registered or <a href="#all_http2_http2createsecureserveroptions-onrequesthandler"><code>http2.createSecureServer()</code></a>
is supplied a callback function, the <code>'checkContinue'</code> event is emitted each
time a request with an HTTP <code>Expect: 100-continue</code> is received. If this event
is not listened for, the server will automatically respond with a status
<code>100 Continue</code> as appropriate.</p>
<p>Handling this event involves calling <a href="#all_http2_responsewritecontinue"><code>response.writeContinue()</code></a> if the
client should continue to send the request body, or generating an appropriate
HTTP response (e.g. 400 Bad Request) if the client should not continue to send
the request body.</p>
<p>When this event is emitted and handled, the <a href="#all_http2_event-request"><code>'request'</code></a> event will
not be emitted.</p>
<h5>Event: <code>'connection'</code><span><a class="mark" href="#all_http2_event-connection_1" id="all_http2_event-connection_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_connection_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>This event is emitted when a new TCP stream is established, before the TLS
handshake begins. <code>socket</code> is typically an object of type <a href="#all_net_class-netsocket"><code>net.Socket</code></a>.
Usually users will not want to access this event.</p>
<p>This event can also be explicitly emitted by users to inject connections
into the HTTP server. In that case, any <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> stream can be passed.</p>
<h5>Event: <code>'request'</code><span><a class="mark" href="#all_http2_event-request_1" id="all_http2_event-request_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_request_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http2_class-http2http2serverrequest" class="type"><http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="#all_http2_class-http2http2serverresponse" class="type"><http2.Http2ServerResponse></a></li>
</ul>
<p>Emitted each time there is a request. There may be multiple requests
per session. See the <a href="#all_http2_compatibility-api">Compatibility API</a>.</p>
<h5>Event: <code>'session'</code><span><a class="mark" href="#all_http2_event-session_1" id="all_http2_event-session_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_session_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>session</code> <a href="#all_http2_class-serverhttp2session" class="type"><ServerHttp2Session></a></li>
</ul>
<p>The <code>'session'</code> event is emitted when a new <code>Http2Session</code> is created by the
<code>Http2SecureServer</code>.</p>
<h5>Event: <code>'sessionError'</code><span><a class="mark" href="#all_http2_event-sessionerror_1" id="all_http2_event-sessionerror_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_sessionerror_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</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><code>session</code> <a href="#all_http2_class-serverhttp2session" class="type"><ServerHttp2Session></a></li>
</ul>
<p>The <code>'sessionError'</code> event is emitted when an <code>'error'</code> event is emitted by
an <code>Http2Session</code> object associated with the <code>Http2SecureServer</code>.</p>
<h5>Event: <code>'stream'</code><span><a class="mark" href="#all_http2_event-stream_2" id="all_http2_event-stream_2">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_stream_2"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_http2_class-http2stream" class="type"><Http2Stream></a> A reference to the stream</li>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a> An object describing the headers</li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The associated numeric flags</li>
<li><code>rawHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array containing the raw header names followed by
their respective values.</li>
</ul>
<p>The <code>'stream'</code> event is emitted when a <code>'stream'</code> event has been emitted by
an <code>Http2Session</code> associated with the server.</p>
<p>See also <a href="#all_http2_event-stream"><code>Http2Session</code>'s <code>'stream'</code> event</a>.</p>
<pre class="with-59-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> { createSecureServer, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> {
<span class="hljs-title class_">HTTP2</span>_HEADER_METHOD,
<span class="hljs-title class_">HTTP2</span>_HEADER_PATH,
<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS,
<span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE,
} = constants;
<span class="hljs-keyword">const</span> options = <span class="hljs-title function_">getOptionsSomehow</span>();
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers, flags</span>) =></span> {
<span class="hljs-keyword">const</span> method = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_METHOD];
<span class="hljs-keyword">const</span> path = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_PATH];
<span class="hljs-comment">// ...</span>
stream.<span class="hljs-title function_">respond</span>({
[<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS]: <span class="hljs-number">200</span>,
[<span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE]: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
});
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello '</span>);
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> {
<span class="hljs-title class_">HTTP2</span>_HEADER_METHOD,
<span class="hljs-title class_">HTTP2</span>_HEADER_PATH,
<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS,
<span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE,
} = http2.<span class="hljs-property">constants</span>;
<span class="hljs-keyword">const</span> options = <span class="hljs-title function_">getOptionsSomehow</span>();
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers, flags</span>) =></span> {
<span class="hljs-keyword">const</span> method = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_METHOD];
<span class="hljs-keyword">const</span> path = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_PATH];
<span class="hljs-comment">// ...</span>
stream.<span class="hljs-title function_">respond</span>({
[<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS]: <span class="hljs-number">200</span>,
[<span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE]: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
});
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello '</span>);
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world'</span>);
});</code><button class="copy-button">copy</button></pre>
<h5>Event: <code>'timeout'</code><span><a class="mark" href="#all_http2_event-timeout_3" id="all_http2_event-timeout_3">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_timeout_3"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for
a given number of milliseconds set using <code>http2secureServer.setTimeout()</code>.
<strong>Default:</strong> 2 minutes.</p>
<h5>Event: <code>'unknownProtocol'</code><span><a class="mark" href="#all_http2_event-unknownprotocol" id="all_http2_event-unknownprotocol">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_unknownprotocol"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This event will only be emitted if the client did not transmit an ALPN extension during the TLS handshake.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>The <code>'unknownProtocol'</code> event is emitted when a connecting client fails to
negotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler
receives the socket for handling. If no listener is registered for this event,
the connection is terminated. A timeout may be specified using the
<code>'unknownProtocolTimeout'</code> option passed to <a href="#all_http2_http2createsecureserveroptions-onrequesthandler"><code>http2.createSecureServer()</code></a>.</p>
<p>In earlier versions of Node.js, this event would be emitted if <code>allowHTTP1</code> is
<code>false</code> and, during the TLS handshake, the client either does not send an ALPN
extension or sends an ALPN extension that does not include HTTP/2 (<code>h2</code>). Newer
versions of Node.js only emit this event if <code>allowHTTP1</code> is <code>false</code> and the
client does not send an ALPN extension. If the client sends an ALPN extension
that does not include HTTP/2 (or HTTP/1.1 if <code>allowHTTP1</code> is <code>true</code>), the TLS
handshake will fail and no secure connection will be established.</p>
<p>See the <a href="#all_http2_compatibility-api">Compatibility API</a>.</p>
<h5><code>server.close([callback])</code><span><a class="mark" href="#all_http2_serverclosecallback_1" id="all_http2_serverclosecallback_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_close_callback_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.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></li>
</ul>
<p>Stops the server from establishing new sessions. This does not prevent new
request streams from being created due to the persistent nature of HTTP/2
sessions. To gracefully shut down the server, call <a href="#all_http2_http2sessionclosecallback"><code>http2session.close()</code></a> on
all active sessions.</p>
<p>If <code>callback</code> is provided, it is not invoked until all active sessions have been
closed, although the server has already stopped allowing new sessions. See
<a href="#all_tls_serverclosecallback"><code>tls.Server.close()</code></a> for more details.</p>
<h5><code>server.setTimeout([msecs][, callback])</code><span><a class="mark" href="#all_http2_serversettimeoutmsecs-callback_1" id="all_http2_serversettimeoutmsecs-callback_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_settimeout_msecs_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>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>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_http2_class-http2secureserver" class="type"><Http2SecureServer></a></li>
</ul>
<p>Used to set the timeout value for http2 secure server requests,
and sets a callback function that is called when there is no activity
on the <code>Http2SecureServer</code> after <code>msecs</code> milliseconds.</p>
<p>The given callback is registered as a listener on the <code>'timeout'</code> event.</p>
<p>In case if <code>callback</code> is not a function, a new <code>ERR_INVALID_ARG_TYPE</code>
error will be thrown.</p>
<h5><code>server.timeout</code><span><a class="mark" href="#all_http2_servertimeout_1" id="all_http2_servertimeout_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_timeout_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>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Timeout in milliseconds. <strong>Default:</strong> 0 (no timeout)</li>
</ul>
<p>The number of milliseconds of inactivity before a socket is presumed
to have timed out.</p>
<p>A value of <code>0</code> will disable the timeout behavior on incoming connections.</p>
<p>The socket timeout logic is set up on connection, so changing this
value only affects new connections to the server, not any existing connections.</p>
<h5><code>server.updateSettings([settings])</code><span><a class="mark" href="#all_http2_serverupdatesettingssettings_1" id="all_http2_serverupdatesettingssettings_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_updatesettings_settings_1"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a></li>
</ul>
<p>Used to update the server with the provided settings.</p>
<p>Throws <code>ERR_HTTP2_INVALID_SETTING_VALUE</code> for invalid <code>settings</code> values.</p>
<p>Throws <code>ERR_INVALID_ARG_TYPE</code> for invalid <code>settings</code> argument.</p>
<h4><code>http2.createServer([options][, onRequestHandler])</code><span><a class="mark" href="#all_http2_http2createserveroptions-onrequesthandler" id="all_http2_http2createserveroptions-onrequesthandler">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_createserver_options_onrequesthandler"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The <code>PADDING_STRATEGY_CALLBACK</code> has been made equivalent to providing <code>PADDING_STRATEGY_ALIGNED</code> and <code>selectPadding</code> has been removed.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p>Added <code>maxSessionRejectedStreams</code> option with a default of 100.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p>Added <code>maxSessionInvalidFrames</code> option with a default of 1000.</p></td></tr>
<tr><td>v12.4.0</td>
<td><p>The <code>options</code> parameter now supports <code>net.createServer()</code> options.</p></td></tr>
<tr><td>v15.10.0, v14.16.0, v12.21.0, v10.24.0</td>
<td><p>Added <code>unknownProtocolTimeout</code> option with a default of 10000.</p></td></tr>
<tr><td>v14.4.0, v12.18.0, v10.21.0</td>
<td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr>
<tr><td>v9.6.0</td>
<td><p>Added the <code>Http1IncomingMessage</code> and <code>Http1ServerResponse</code> option.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></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>maxDeflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum dynamic table size
for deflating header fields. <strong>Default:</strong> <code>4Kib</code>.</li>
<li><code>maxSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of settings entries per
<code>SETTINGS</code> frame. The minimum value allowed is <code>1</code>. <strong>Default:</strong> <code>32</code>.</li>
<li><code>maxSessionMemory</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum memory that the <code>Http2Session</code>
is permitted to use. The value is expressed in terms of number of megabytes,
e.g. <code>1</code> equal 1 megabyte. The minimum value allowed is <code>1</code>.
This is a credit based limit, existing <code>Http2Stream</code>s may cause this
limit to be exceeded, but new <code>Http2Stream</code> instances will be rejected
while this limit is exceeded. The current number of <code>Http2Stream</code> sessions,
the current memory use of the header compression tables, current data
queued to be sent, and unacknowledged <code>PING</code> and <code>SETTINGS</code> frames are all
counted towards the current limit. <strong>Default:</strong> <code>10</code>.</li>
<li><code>maxHeaderListPairs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of header entries.
This is similar to <a href="#all_http_servermaxheaderscount"><code>server.maxHeadersCount</code></a> or
<a href="#all_http_requestmaxheaderscount"><code>request.maxHeadersCount</code></a> in the <code>node:http</code> module. The minimum value
is <code>4</code>. <strong>Default:</strong> <code>128</code>.</li>
<li><code>maxOutstandingPings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of outstanding,
unacknowledged pings. <strong>Default:</strong> <code>10</code>.</li>
<li><code>maxSendHeaderBlockLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum allowed size for a
serialized, compressed block of headers. Attempts to send headers that
exceed this limit will result in a <code>'frameError'</code> event being emitted
and the stream being closed and destroyed.
While this sets the maximum allowed size to the entire block of headers,
<code>nghttp2</code> (the internal http2 library) has a limit of <code>65536</code>
for each decompressed key/value pair.</li>
<li><code>paddingStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The strategy used for determining the amount of
padding to use for <code>HEADERS</code> and <code>DATA</code> frames. <strong>Default:</strong>
<code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:
<ul>
<li><code>http2.constants.PADDING_STRATEGY_NONE</code>: No padding is applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_MAX</code>: The maximum amount of padding,
determined by the internal implementation, is applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code>: Attempts to apply enough
padding to ensure that the total frame length, including the 9-byte
header, is a multiple of 8. For each frame, there is a maximum allowed
number of padding bytes that is determined by current flow control state
and settings. If this maximum is less than the calculated amount needed to
ensure alignment, the maximum is used and the total frame length is not
necessarily aligned at 8 bytes.</li>
</ul>
</li>
<li><code>peerMaxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of concurrent
streams for the remote peer as if a <code>SETTINGS</code> frame had been received. Will
be overridden if the remote peer sets its own value for
<code>maxConcurrentStreams</code>. <strong>Default:</strong> <code>100</code>.</li>
<li><code>maxSessionInvalidFrames</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Sets the maximum number of invalid
frames that will be tolerated before the session is closed.
<strong>Default:</strong> <code>1000</code>.</li>
<li><code>maxSessionRejectedStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Sets the maximum number of rejected
upon creation streams that will be tolerated before the session is closed.
Each rejection is associated with an <code>NGHTTP2_ENHANCE_YOUR_CALM</code>
error that should tell the peer to not open any more streams, continuing
to open streams is therefore regarded as a sign of a misbehaving peer.
<strong>Default:</strong> <code>100</code>.</li>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a> The initial settings to send to the
remote peer upon connection.</li>
<li><code>remoteCustomSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> The array of integer values determines the
settings types, which are included in the <code>CustomSettings</code>-property of
the received remoteSettings. Please see the <code>CustomSettings</code>-property of
the <code>Http2Settings</code> object for more information,
on the allowed setting types.</li>
<li><code>Http1IncomingMessage</code> <a href="#all_http_class-httpincomingmessage" class="type"><http.IncomingMessage></a> Specifies the
<code>IncomingMessage</code> class to used for HTTP/1 fallback. Useful for extending
the original <code>http.IncomingMessage</code>. <strong>Default:</strong> <code>http.IncomingMessage</code>.</li>
<li><code>Http1ServerResponse</code> <a href="#all_http_class-httpserverresponse" class="type"><http.ServerResponse></a> Specifies the <code>ServerResponse</code>
class to used for HTTP/1 fallback. Useful for extending the original
<code>http.ServerResponse</code>. <strong>Default:</strong> <code>http.ServerResponse</code>.</li>
<li><code>Http2ServerRequest</code> <a href="#all_http2_class-http2http2serverrequest" class="type"><http2.Http2ServerRequest></a> Specifies the
<code>Http2ServerRequest</code> class to use.
Useful for extending the original <code>Http2ServerRequest</code>.
<strong>Default:</strong> <code>Http2ServerRequest</code>.</li>
<li><code>Http2ServerResponse</code> <a href="#all_http2_class-http2http2serverresponse" class="type"><http2.Http2ServerResponse></a> Specifies the
<code>Http2ServerResponse</code> class to use.
Useful for extending the original <code>Http2ServerResponse</code>.
<strong>Default:</strong> <code>Http2ServerResponse</code>.</li>
<li><code>unknownProtocolTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies a timeout in milliseconds that
a server should wait when an <a href="#all_http2_event-unknownprotocol"><code>'unknownProtocol'</code></a> is emitted. If the
socket has not been destroyed by that time the server will destroy it.
<strong>Default:</strong> <code>10000</code>.</li>
<li>...: Any <a href="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer()</code></a> option can be provided.</li>
</ul>
</li>
<li><code>onRequestHandler</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> See <a href="#all_http2_compatibility-api">Compatibility API</a></li>
<li>Returns: <a href="#all_http2_class-http2server" class="type"><Http2Server></a></li>
</ul>
<p>Returns a <code>net.Server</code> instance that creates and manages <code>Http2Session</code>
instances.</p>
<p>Since there are no browsers known that support
<a href="https://http2.github.io/faq/#does-http2-require-encryption">unencrypted HTTP/2</a>, the use of
<a href="#all_http2_http2createsecureserveroptions-onrequesthandler"><code>http2.createSecureServer()</code></a> is necessary when communicating
with browser clients.</p>
<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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-comment">// Create an unencrypted HTTP/2 server.</span>
<span class="hljs-comment">// Since there are no browsers known that support</span>
<span class="hljs-comment">// unencrypted HTTP/2, the use of `createSecureServer()`</span>
<span class="hljs-comment">// is necessary when communicating with browser clients.</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>({
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
<span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
});
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'<h1>Hello World</h1>'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-comment">// Create an unencrypted HTTP/2 server.</span>
<span class="hljs-comment">// Since there are no browsers known that support</span>
<span class="hljs-comment">// unencrypted HTTP/2, the use of `http2.createSecureServer()`</span>
<span class="hljs-comment">// is necessary when communicating with browser clients.</span>
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>({
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
<span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
});
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'<h1>Hello World</h1>'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>http2.createSecureServer(options[, onRequestHandler])</code><span><a class="mark" href="#all_http2_http2createsecureserveroptions-onrequesthandler" id="all_http2_http2createsecureserveroptions-onrequesthandler">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_createsecureserver_options_onrequesthandler"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The <code>PADDING_STRATEGY_CALLBACK</code> has been made equivalent to providing <code>PADDING_STRATEGY_ALIGNED</code> and <code>selectPadding</code> has been removed.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p>Added <code>maxSessionRejectedStreams</code> option with a default of 100.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p>Added <code>maxSessionInvalidFrames</code> option with a default of 1000.</p></td></tr>
<tr><td>v15.10.0, v14.16.0, v12.21.0, v10.24.0</td>
<td><p>Added <code>unknownProtocolTimeout</code> option with a default of 10000.</p></td></tr>
<tr><td>v14.4.0, v12.18.0, v10.21.0</td>
<td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p>Added the <code>origins</code> option to automatically send an <code>ORIGIN</code> frame on <code>Http2Session</code> startup.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></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>allowHTTP1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Incoming client connections that do not support
HTTP/2 will be downgraded to HTTP/1.x when set to <code>true</code>.
See the <a href="#all_http2_event-unknownprotocol"><code>'unknownProtocol'</code></a> event. See <a href="#all_http2_alpn-negotiation">ALPN negotiation</a>.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>maxDeflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum dynamic table size
for deflating header fields. <strong>Default:</strong> <code>4Kib</code>.</li>
<li><code>maxSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of settings entries per
<code>SETTINGS</code> frame. The minimum value allowed is <code>1</code>. <strong>Default:</strong> <code>32</code>.</li>
<li><code>maxSessionMemory</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum memory that the <code>Http2Session</code>
is permitted to use. The value is expressed in terms of number of megabytes,
e.g. <code>1</code> equal 1 megabyte. The minimum value allowed is <code>1</code>. This is a
credit based limit, existing <code>Http2Stream</code>s may cause this
limit to be exceeded, but new <code>Http2Stream</code> instances will be rejected
while this limit is exceeded. The current number of <code>Http2Stream</code> sessions,
the current memory use of the header compression tables, current data
queued to be sent, and unacknowledged <code>PING</code> and <code>SETTINGS</code> frames are all
counted towards the current limit. <strong>Default:</strong> <code>10</code>.</li>
<li><code>maxHeaderListPairs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of header entries.
This is similar to <a href="#all_http_servermaxheaderscount"><code>server.maxHeadersCount</code></a> or
<a href="#all_http_requestmaxheaderscount"><code>request.maxHeadersCount</code></a> in the <code>node:http</code> module. The minimum value
is <code>4</code>. <strong>Default:</strong> <code>128</code>.</li>
<li><code>maxOutstandingPings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of outstanding,
unacknowledged pings. <strong>Default:</strong> <code>10</code>.</li>
<li><code>maxSendHeaderBlockLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum allowed size for a
serialized, compressed block of headers. Attempts to send headers that
exceed this limit will result in a <code>'frameError'</code> event being emitted
and the stream being closed and destroyed.</li>
<li><code>paddingStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Strategy used for determining the amount of
padding to use for <code>HEADERS</code> and <code>DATA</code> frames. <strong>Default:</strong>
<code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:
<ul>
<li><code>http2.constants.PADDING_STRATEGY_NONE</code>: No padding is applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_MAX</code>: The maximum amount of padding,
determined by the internal implementation, is applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code>: Attempts to apply enough
padding to ensure that the total frame length, including the
9-byte header, is a multiple of 8. For each frame, there is a maximum
allowed number of padding bytes that is determined by current flow control
state and settings. If this maximum is less than the calculated amount
needed to ensure alignment, the maximum is used and the total frame length
is not necessarily aligned at 8 bytes.</li>
</ul>
</li>
<li><code>peerMaxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of concurrent
streams for the remote peer as if a <code>SETTINGS</code> frame had been received. Will
be overridden if the remote peer sets its own value for
<code>maxConcurrentStreams</code>. <strong>Default:</strong> <code>100</code>.</li>
<li><code>maxSessionInvalidFrames</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Sets the maximum number of invalid
frames that will be tolerated before the session is closed.
<strong>Default:</strong> <code>1000</code>.</li>
<li><code>maxSessionRejectedStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Sets the maximum number of rejected
upon creation streams that will be tolerated before the session is closed.
Each rejection is associated with an <code>NGHTTP2_ENHANCE_YOUR_CALM</code>
error that should tell the peer to not open any more streams, continuing
to open streams is therefore regarded as a sign of a misbehaving peer.
<strong>Default:</strong> <code>100</code>.</li>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a> The initial settings to send to the
remote peer upon connection.</li>
<li><code>remoteCustomSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> The array of integer values determines the
settings types, which are included in the <code>customSettings</code>-property of the
received remoteSettings. Please see the <code>customSettings</code>-property of the
<code>Http2Settings</code> object for more information, on the allowed setting types.</li>
<li>...: Any <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a> options can be provided. For
servers, the identity options (<code>pfx</code> or <code>key</code>/<code>cert</code>) are usually required.</li>
<li><code>origins</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array of origin strings to send within an <code>ORIGIN</code>
frame immediately following creation of a new server <code>Http2Session</code>.</li>
<li><code>unknownProtocolTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies a timeout in milliseconds that
a server should wait when an <a href="#all_http2_event-unknownprotocol"><code>'unknownProtocol'</code></a> event is emitted. If
the socket has not been destroyed by that time the server will destroy it.
<strong>Default:</strong> <code>10000</code>.</li>
</ul>
</li>
<li><code>onRequestHandler</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> See <a href="#all_http2_compatibility-api">Compatibility API</a></li>
<li>Returns: <a href="#all_http2_class-http2secureserver" class="type"><Http2SecureServer></a></li>
</ul>
<p>Returns a <code>tls.Server</code> instance that creates and manages <code>Http2Session</code>
instances.</p>
<pre class="with-48-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> { createSecureServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">key</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-key.pem'</span>),
<span class="hljs-attr">cert</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-cert.pem'</span>),
};
<span class="hljs-comment">// Create a secure HTTP/2 server</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>({
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
<span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
});
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'<h1>Hello World</h1>'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8443</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</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> options = {
<span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-key.pem'</span>),
<span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-cert.pem'</span>),
};
<span class="hljs-comment">// Create a secure HTTP/2 server</span>
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
stream.<span class="hljs-title function_">respond</span>({
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
<span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
});
stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'<h1>Hello World</h1>'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8443</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>http2.connect(authority[, options][, listener])</code><span><a class="mark" href="#all_http2_http2connectauthority-options-listener" id="all_http2_http2connectauthority-options-listener">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_connect_authority_options_listener"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The <code>PADDING_STRATEGY_CALLBACK</code> has been made equivalent to providing <code>PADDING_STRATEGY_ALIGNED</code> and <code>selectPadding</code> has been removed.</p></td></tr>
<tr><td>v15.10.0, v14.16.0, v12.21.0, v10.24.0</td>
<td><p>Added <code>unknownProtocolTimeout</code> option with a default of 10000.</p></td></tr>
<tr><td>v14.4.0, v12.18.0, v10.21.0</td>
<td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>authority</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> The remote HTTP/2 server to connect to. This must
be in the form of a minimal, valid URL with the <code>http://</code> or <code>https://</code>
prefix, host name, and IP port (if a non-default port is used). Userinfo
(user ID and password), path, querystring, and fragment details in the
URL will be ignored.</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>maxDeflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum dynamic table size
for deflating header fields. <strong>Default:</strong> <code>4Kib</code>.</li>
<li><code>maxSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of settings entries per
<code>SETTINGS</code> frame. The minimum value allowed is <code>1</code>. <strong>Default:</strong> <code>32</code>.</li>
<li><code>maxSessionMemory</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum memory that the <code>Http2Session</code>
is permitted to use. The value is expressed in terms of number of megabytes,
e.g. <code>1</code> equal 1 megabyte. The minimum value allowed is <code>1</code>.
This is a credit based limit, existing <code>Http2Stream</code>s may cause this
limit to be exceeded, but new <code>Http2Stream</code> instances will be rejected
while this limit is exceeded. The current number of <code>Http2Stream</code> sessions,
the current memory use of the header compression tables, current data
queued to be sent, and unacknowledged <code>PING</code> and <code>SETTINGS</code> frames are all
counted towards the current limit. <strong>Default:</strong> <code>10</code>.</li>
<li><code>maxHeaderListPairs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of header entries.
This is similar to <a href="#all_http_servermaxheaderscount"><code>server.maxHeadersCount</code></a> or
<a href="#all_http_requestmaxheaderscount"><code>request.maxHeadersCount</code></a> in the <code>node:http</code> module. The minimum value
is <code>1</code>. <strong>Default:</strong> <code>128</code>.</li>
<li><code>maxOutstandingPings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of outstanding,
unacknowledged pings. <strong>Default:</strong> <code>10</code>.</li>
<li><code>maxReservedRemoteStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of reserved push
streams the client will accept at any given time. Once the current number of
currently reserved push streams exceeds reaches this limit, new push streams
sent by the server will be automatically rejected. The minimum allowed value
is 0. The maximum allowed value is 2<sup>32</sup>-1. A negative value sets
this option to the maximum allowed value. <strong>Default:</strong> <code>200</code>.</li>
<li><code>maxSendHeaderBlockLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum allowed size for a
serialized, compressed block of headers. Attempts to send headers that
exceed this limit will result in a <code>'frameError'</code> event being emitted
and the stream being closed and destroyed.</li>
<li><code>paddingStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Strategy used for determining the amount of
padding to use for <code>HEADERS</code> and <code>DATA</code> frames. <strong>Default:</strong>
<code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:
<ul>
<li><code>http2.constants.PADDING_STRATEGY_NONE</code>: No padding is applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_MAX</code>: The maximum amount of padding,
determined by the internal implementation, is applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code>: Attempts to apply enough
padding to ensure that the total frame length, including the
9-byte header, is a multiple of 8. For each frame, there is a maximum
allowed number of padding bytes that is determined by current flow control
state and settings. If this maximum is less than the calculated amount
needed to ensure alignment, the maximum is used and the total frame length
is not necessarily aligned at 8 bytes.</li>
</ul>
</li>
<li><code>peerMaxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of concurrent
streams for the remote peer as if a <code>SETTINGS</code> frame had been received. Will
be overridden if the remote peer sets its own value for
<code>maxConcurrentStreams</code>. <strong>Default:</strong> <code>100</code>.</li>
<li><code>protocol</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The protocol to connect with, if not set in the
<code>authority</code>. Value may be either <code>'http:'</code> or <code>'https:'</code>. <strong>Default:</strong>
<code>'https:'</code></li>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a> The initial settings to send to the
remote peer upon connection.</li>
<li><code>remoteCustomSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> The array of integer values determines the
settings types, which are included in the <code>CustomSettings</code>-property of the
received remoteSettings. Please see the <code>CustomSettings</code>-property of the
<code>Http2Settings</code> object for more information, on the allowed setting types.</li>
<li><code>createConnection</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> An optional callback that receives the <code>URL</code>
instance passed to <code>connect</code> and the <code>options</code> object, and returns any
<a href="#all_stream_class-streamduplex"><code>Duplex</code></a> stream that is to be used as the connection for this session.</li>
<li>...: Any <a href="#all_net_netconnect"><code>net.connect()</code></a> or <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> options can be provided.</li>
<li><code>unknownProtocolTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies a timeout in milliseconds that
a server should wait when an <a href="#all_http2_event-unknownprotocol"><code>'unknownProtocol'</code></a> event is emitted. If
the socket has not been destroyed by that time the server will destroy it.
<strong>Default:</strong> <code>10000</code>.</li>
</ul>
</li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Will be registered as a one-time listener of the
<a href="#all_http2_event-connect"><code>'connect'</code></a> event.</li>
<li>Returns: <a href="#all_http2_class-clienthttp2session" class="type"><ClientHttp2Session></a></li>
</ul>
<p>Returns a <code>ClientHttp2Session</code> instance.</p>
<pre class="with-55-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> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost:1234'</span>);
<span class="hljs-comment">/* Use the client */</span>
client.<span class="hljs-title function_">close</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost:1234'</span>);
<span class="hljs-comment">/* Use the client */</span>
client.<span class="hljs-title function_">close</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>http2.constants</code><span><a class="mark" href="#all_http2_http2constants" id="all_http2_http2constants">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_constants"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<h5>Error codes for <code>RST_STREAM</code> and <code>GOAWAY</code><span><a class="mark" href="#all_http2_error-codes-for-rst_stream-and-goaway" id="all_http2_error-codes-for-rst_stream-and-goaway">#</a></span><a aria-hidden="true" class="legacy" id="http2_error_codes_for_rst_stream_and_goaway"></a></h5>
<table><thead><tr><th>Value</th><th>Name</th><th>Constant</th></tr></thead><tbody><tr><td><code>0x00</code></td><td>No Error</td><td><code>http2.constants.NGHTTP2_NO_ERROR</code></td></tr><tr><td><code>0x01</code></td><td>Protocol Error</td><td><code>http2.constants.NGHTTP2_PROTOCOL_ERROR</code></td></tr><tr><td><code>0x02</code></td><td>Internal Error</td><td><code>http2.constants.NGHTTP2_INTERNAL_ERROR</code></td></tr><tr><td><code>0x03</code></td><td>Flow Control Error</td><td><code>http2.constants.NGHTTP2_FLOW_CONTROL_ERROR</code></td></tr><tr><td><code>0x04</code></td><td>Settings Timeout</td><td><code>http2.constants.NGHTTP2_SETTINGS_TIMEOUT</code></td></tr><tr><td><code>0x05</code></td><td>Stream Closed</td><td><code>http2.constants.NGHTTP2_STREAM_CLOSED</code></td></tr><tr><td><code>0x06</code></td><td>Frame Size Error</td><td><code>http2.constants.NGHTTP2_FRAME_SIZE_ERROR</code></td></tr><tr><td><code>0x07</code></td><td>Refused Stream</td><td><code>http2.constants.NGHTTP2_REFUSED_STREAM</code></td></tr><tr><td><code>0x08</code></td><td>Cancel</td><td><code>http2.constants.NGHTTP2_CANCEL</code></td></tr><tr><td><code>0x09</code></td><td>Compression Error</td><td><code>http2.constants.NGHTTP2_COMPRESSION_ERROR</code></td></tr><tr><td><code>0x0a</code></td><td>Connect Error</td><td><code>http2.constants.NGHTTP2_CONNECT_ERROR</code></td></tr><tr><td><code>0x0b</code></td><td>Enhance Your Calm</td><td><code>http2.constants.NGHTTP2_ENHANCE_YOUR_CALM</code></td></tr><tr><td><code>0x0c</code></td><td>Inadequate Security</td><td><code>http2.constants.NGHTTP2_INADEQUATE_SECURITY</code></td></tr><tr><td><code>0x0d</code></td><td>HTTP/1.1 Required</td><td><code>http2.constants.NGHTTP2_HTTP_1_1_REQUIRED</code></td></tr></tbody></table>
<p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for
a given number of milliseconds set using <code>http2server.setTimeout()</code>.</p>
<h4><code>http2.getDefaultSettings()</code><span><a class="mark" href="#all_http2_http2getdefaultsettings" id="all_http2_http2getdefaultsettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_getdefaultsettings"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Returns: <a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a></li>
</ul>
<p>Returns an object containing the default settings for an <code>Http2Session</code>
instance. This method returns a new object instance every time it is called
so instances returned may be safely modified for use.</p>
<h4><code>http2.getPackedSettings([settings])</code><span><a class="mark" href="#all_http2_http2getpackedsettingssettings" id="all_http2_http2getpackedsettingssettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_getpackedsettings_settings"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a></li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Returns a <code>Buffer</code> instance containing serialized representation of the given
HTTP/2 settings as specified in the <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a> specification. This is intended
for use with the <code>HTTP2-Settings</code> header field.</p>
<pre class="with-47-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> { getPackedSettings } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> packed = <span class="hljs-title function_">getPackedSettings</span>({ <span class="hljs-attr">enablePush</span>: <span class="hljs-literal">false</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(packed.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'base64'</span>));
<span class="hljs-comment">// Prints: AAIAAAAA</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> packed = http2.<span class="hljs-title function_">getPackedSettings</span>({ <span class="hljs-attr">enablePush</span>: <span class="hljs-literal">false</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(packed.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'base64'</span>));
<span class="hljs-comment">// Prints: AAIAAAAA</span></code><button class="copy-button">copy</button></pre>
<h4><code>http2.getUnpackedSettings(buf)</code><span><a class="mark" href="#all_http2_http2getunpackedsettingsbuf" id="all_http2_http2getunpackedsettingsbuf">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_getunpackedsettings_buf"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>buf</code> <a href="#all_buffer_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> The packed settings.</li>
<li>Returns: <a href="#all_http2_settings-object" class="type"><HTTP/2 Settings Object></a></li>
</ul>
<p>Returns a <a href="#all_http2_settings-object">HTTP/2 Settings Object</a> containing the deserialized settings from
the given <code>Buffer</code> as generated by <code>http2.getPackedSettings()</code>.</p>
<h4><code>http2.performServerHandshake(socket[, options])</code><span><a class="mark" href="#all_http2_http2performserverhandshakesocket-options" id="all_http2_http2performserverhandshakesocket-options">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_performserverhandshake_socket_options"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></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>...: Any <a href="#all_http2_http2createserveroptions-onrequesthandler"><code>http2.createServer()</code></a> option can be provided.</li>
</ul>
</li>
<li>Returns: <a href="#all_http2_class-serverhttp2session" class="type"><ServerHttp2Session></a></li>
</ul>
<p>Create an HTTP/2 server session from an existing socket.</p>
<h4><code>http2.sensitiveHeaders</code><span><a class="mark" href="#all_http2_http2sensitiveheaders" id="all_http2_http2sensitiveheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_sensitiveheaders"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></li>
</ul>
<p>This symbol can be set as a property on the HTTP/2 headers object with an array
value in order to provide a list of headers considered sensitive.
See <a href="#all_http2_sensitive-headers">Sensitive headers</a> for more details.</p>
<h4>Headers object<span><a class="mark" href="#all_http2_headers-object" id="all_http2_headers-object">#</a></span><a aria-hidden="true" class="legacy" id="http2_headers_object"></a></h4>
<p>Headers are represented as own-properties on JavaScript objects. The property
keys will be serialized to lower-case. Property values should be strings (if
they are not they will be coerced to strings) or an <code>Array</code> of strings (in order
to send more than one value per header field).</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> headers = {
<span class="hljs-string">':status'</span>: <span class="hljs-string">'200'</span>,
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text-plain'</span>,
<span class="hljs-string">'ABC'</span>: [<span class="hljs-string">'has'</span>, <span class="hljs-string">'more'</span>, <span class="hljs-string">'than'</span>, <span class="hljs-string">'one'</span>, <span class="hljs-string">'value'</span>],
};
stream.<span class="hljs-title function_">respond</span>(headers);</code> <button class="copy-button">copy</button></pre>
<p>Header objects passed to callback functions will have a <code>null</code> prototype. This
means that normal JavaScript object methods such as
<code>Object.prototype.toString()</code> and <code>Object.prototype.hasOwnProperty()</code> will
not work.</p>
<p>For incoming headers:</p>
<ul>
<li>The <code>:status</code> header is converted to <code>number</code>.</li>
<li>Duplicates of <code>:status</code>, <code>:method</code>, <code>:authority</code>, <code>:scheme</code>, <code>:path</code>,
<code>:protocol</code>, <code>age</code>, <code>authorization</code>, <code>access-control-allow-credentials</code>,
<code>access-control-max-age</code>, <code>access-control-request-method</code>, <code>content-encoding</code>,
<code>content-language</code>, <code>content-length</code>, <code>content-location</code>, <code>content-md5</code>,
<code>content-range</code>, <code>content-type</code>, <code>date</code>, <code>dnt</code>, <code>etag</code>, <code>expires</code>, <code>from</code>,
<code>host</code>, <code>if-match</code>, <code>if-modified-since</code>, <code>if-none-match</code>, <code>if-range</code>,
<code>if-unmodified-since</code>, <code>last-modified</code>, <code>location</code>, <code>max-forwards</code>,
<code>proxy-authorization</code>, <code>range</code>, <code>referer</code>,<code>retry-after</code>, <code>tk</code>,
<code>upgrade-insecure-requests</code>, <code>user-agent</code> or <code>x-content-type-options</code> are
discarded.</li>
<li><code>set-cookie</code> is always an array. Duplicates are added to the array.</li>
<li>For duplicate <code>cookie</code> headers, the values are joined together with '; '.</li>
<li>For all other headers, the values are joined together with ', '.</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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[<span class="hljs-string">':path'</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers.<span class="hljs-property">ABC</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[<span class="hljs-string">':path'</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers.<span class="hljs-property">ABC</span>);
});</code><button class="copy-button">copy</button></pre>
<h5>Sensitive headers<span><a class="mark" href="#all_http2_sensitive-headers" id="all_http2_sensitive-headers">#</a></span><a aria-hidden="true" class="legacy" id="http2_sensitive_headers"></a></h5>
<p>HTTP2 headers can be marked as sensitive, which means that the HTTP/2
header compression algorithm will never index them. This can make sense for
header values with low entropy and that may be considered valuable to an
attacker, for example <code>Cookie</code> or <code>Authorization</code>. To achieve this, add
the header name to the <code>[http2.sensitiveHeaders]</code> property as an array:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> headers = {
<span class="hljs-string">':status'</span>: <span class="hljs-string">'200'</span>,
<span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text-plain'</span>,
<span class="hljs-string">'cookie'</span>: <span class="hljs-string">'some-cookie'</span>,
<span class="hljs-string">'other-sensitive-header'</span>: <span class="hljs-string">'very secret data'</span>,
[http2.<span class="hljs-property">sensitiveHeaders</span>]: [<span class="hljs-string">'cookie'</span>, <span class="hljs-string">'other-sensitive-header'</span>],
};
stream.<span class="hljs-title function_">respond</span>(headers);</code> <button class="copy-button">copy</button></pre>
<p>For some headers, such as <code>Authorization</code> and short <code>Cookie</code> headers,
this flag is set automatically.</p>
<p>This property is also set for received headers. It will contain the names of
all headers marked as sensitive, including ones marked that way automatically.</p>
<h4>Settings object<span><a class="mark" href="#all_http2_settings-object" id="all_http2_settings-object">#</a></span><a aria-hidden="true" class="legacy" id="http2_settings_object"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.12.0</td>
<td><p>The <code>maxConcurrentStreams</code> setting is stricter.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>The <code>maxHeaderListSize</code> setting is now strictly enforced.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>http2.getDefaultSettings()</code>, <code>http2.getPackedSettings()</code>,
<code>http2.createServer()</code>, <code>http2.createSecureServer()</code>,
<code>http2session.settings()</code>, <code>http2session.localSettings</code>, and
<code>http2session.remoteSettings</code> APIs either return or receive as input an
object that defines configuration settings for an <code>Http2Session</code> object.
These objects are ordinary JavaScript objects containing the following
properties.</p>
<ul>
<li><code>headerTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the maximum number of bytes used for
header compression. The minimum allowed value is 0. The maximum allowed value
is 2<sup>32</sup>-1. <strong>Default:</strong> <code>4096</code>.</li>
<li><code>enablePush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Specifies <code>true</code> if HTTP/2 Push Streams are to be
permitted on the <code>Http2Session</code> instances. <strong>Default:</strong> <code>true</code>.</li>
<li><code>initialWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the <em>sender's</em> initial window size in
bytes for stream-level flow control. The minimum allowed value is 0. The
maximum allowed value is 2<sup>32</sup>-1. <strong>Default:</strong> <code>65535</code>.</li>
<li><code>maxFrameSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the size in bytes of the largest frame
payload. The minimum allowed value is 16,384. The maximum allowed value is
2<sup>24</sup>-1. <strong>Default:</strong> <code>16384</code>.</li>
<li><code>maxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the maximum number of concurrent
streams permitted on an <code>Http2Session</code>. There is no default value which
implies, at least theoretically, 2<sup>32</sup>-1 streams may be open
concurrently at any given time in an <code>Http2Session</code>. The minimum value
is 0. The maximum allowed value is 2<sup>32</sup>-1. <strong>Default:</strong>
<code>4294967295</code>.</li>
<li><code>maxHeaderListSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the maximum size (uncompressed octets)
of header list that will be accepted. The minimum allowed value is 0. The
maximum allowed value is 2<sup>32</sup>-1. <strong>Default:</strong> <code>65535</code>.</li>
<li><code>maxHeaderSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>maxHeaderListSize</code>.</li>
<li><code>enableConnectProtocol</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Specifies <code>true</code> if the "Extended Connect
Protocol" defined by <a href="https://tools.ietf.org/html/rfc8441">RFC 8441</a> is to be enabled. This setting is only
meaningful if sent by the server. Once the <code>enableConnectProtocol</code> setting
has been enabled for a given <code>Http2Session</code>, it cannot be disabled.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>customSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Specifies additional settings, yet not implemented
in node and the underlying libraries. The key of the object defines the
numeric value of the settings type (as defined in the "HTTP/2 SETTINGS"
registry established by [RFC 7540]) and the values the actual numeric value
of the settings.
The settings type has to be an integer in the range from 1 to 2^16-1.
It should not be a settings type already handled by node, i.e. currently
it should be greater than 6, although it is not an error.
The values need to be unsigned integers in the range from 0 to 2^32-1.
Currently, a maximum of up 10 custom settings is supported.
It is only supported for sending SETTINGS, or for receiving settings values
specified in the <code>remoteCustomSettings</code> options of the server or client
object. Do not mix the <code>customSettings</code>-mechanism for a settings id with
interfaces for the natively handled settings, in case a setting becomes
natively supported in a future node version.</li>
</ul>
<p>All additional properties on the settings object are ignored.</p>
<h4>Error handling<span><a class="mark" href="#all_http2_error-handling" id="all_http2_error-handling">#</a></span><a aria-hidden="true" class="legacy" id="http2_error_handling"></a></h4>
<p>There are several types of error conditions that may arise when using the
<code>node:http2</code> module:</p>
<p>Validation errors occur when an incorrect argument, option, or setting value is
passed in. These will always be reported by a synchronous <code>throw</code>.</p>
<p>State errors occur when an action is attempted at an incorrect time (for
instance, attempting to send data on a stream after it has closed). These will
be reported using either a synchronous <code>throw</code> or via an <code>'error'</code> event on
the <code>Http2Stream</code>, <code>Http2Session</code> or HTTP/2 Server objects, depending on where
and when the error occurs.</p>
<p>Internal errors occur when an HTTP/2 session fails unexpectedly. These will be
reported via an <code>'error'</code> event on the <code>Http2Session</code> or HTTP/2 Server objects.</p>
<p>Protocol errors occur when various HTTP/2 protocol constraints are violated.
These will be reported using either a synchronous <code>throw</code> or via an <code>'error'</code>
event on the <code>Http2Stream</code>, <code>Http2Session</code> or HTTP/2 Server objects, depending
on where and when the error occurs.</p>
<h4>Invalid character handling in header names and values<span><a class="mark" href="#all_http2_invalid-character-handling-in-header-names-and-values" id="all_http2_invalid-character-handling-in-header-names-and-values">#</a></span><a aria-hidden="true" class="legacy" id="http2_invalid_character_handling_in_header_names_and_values"></a></h4>
<p>The HTTP/2 implementation applies stricter handling of invalid characters in
HTTP header names and values than the HTTP/1 implementation.</p>
<p>Header field names are <em>case-insensitive</em> and are transmitted over the wire
strictly as lower-case strings. The API provided by Node.js allows header
names to be set as mixed-case strings (e.g. <code>Content-Type</code>) but will convert
those to lower-case (e.g. <code>content-type</code>) upon transmission.</p>
<p>Header field-names <em>must only</em> contain one or more of the following ASCII
characters: <code>a</code>-<code>z</code>, <code>A</code>-<code>Z</code>, <code>0</code>-<code>9</code>, <code>!</code>, <code>#</code>, <code>$</code>, <code>%</code>, <code>&</code>, <code>'</code>, <code>*</code>, <code>+</code>,
<code>-</code>, <code>.</code>, <code>^</code>, <code>_</code>, <code>`</code> (backtick), <code>|</code>, and <code>~</code>.</p>
<p>Using invalid characters within an HTTP header field name will cause the
stream to be closed with a protocol error being reported.</p>
<p>Header field values are handled with more leniency but <em>should</em> not contain
new-line or carriage return characters and <em>should</em> be limited to US-ASCII
characters, per the requirements of the HTTP specification.</p>
<h4>Push streams on the client<span><a class="mark" href="#all_http2_push-streams-on-the-client" id="all_http2_push-streams-on-the-client">#</a></span><a aria-hidden="true" class="legacy" id="http2_push_streams_on_the_client"></a></h4>
<p>To receive pushed streams on the client, set a listener for the <code>'stream'</code>
event on the <code>ClientHttp2Session</code>:</p>
<pre class="with-37-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> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://localhost'</span>);
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">pushedStream, requestHeaders</span>) =></span> {
pushedStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'push'</span>, <span class="hljs-function">(<span class="hljs-params">responseHeaders</span>) =></span> {
<span class="hljs-comment">// Process response headers</span>
});
pushedStream.<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-comment">/* handle pushed data */</span> });
});
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://localhost'</span>);
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">pushedStream, requestHeaders</span>) =></span> {
pushedStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'push'</span>, <span class="hljs-function">(<span class="hljs-params">responseHeaders</span>) =></span> {
<span class="hljs-comment">// Process response headers</span>
});
pushedStream.<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-comment">/* handle pushed data */</span> });
});
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });</code><button class="copy-button">copy</button></pre>
<h4>Supporting the <code>CONNECT</code> method<span><a class="mark" href="#all_http2_supporting-the-connect-method" id="all_http2_supporting-the-connect-method">#</a></span><a aria-hidden="true" class="legacy" id="http2_supporting_the_connect_method"></a></h4>
<p>The <code>CONNECT</code> method is used to allow an HTTP/2 server to be used as a proxy
for TCP/IP connections.</p>
<p>A simple TCP Server:</p>
<pre class="with-40-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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
<span class="hljs-keyword">let</span> name = <span class="hljs-string">''</span>;
socket.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> name += chunk);
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">`hello <span class="hljs-subst">${name}</span>`</span>));
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
<span class="hljs-keyword">let</span> name = <span class="hljs-string">''</span>;
socket.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> name += chunk);
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">`hello <span class="hljs-subst">${name}</span>`</span>));
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>
<p>An HTTP/2 CONNECT proxy:</p>
<pre class="with-68-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> { createServer, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">NGHTTP2</span>_REFUSED_STREAM, <span class="hljs-title class_">NGHTTP2</span>_CONNECT_ERROR } = constants;
<span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">const</span> proxy = <span class="hljs-title function_">createServer</span>();
proxy.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
<span class="hljs-keyword">if</span> (headers[<span class="hljs-string">':method'</span>] !== <span class="hljs-string">'CONNECT'</span>) {
<span class="hljs-comment">// Only accept CONNECT requests</span>
stream.<span class="hljs-title function_">close</span>(<span class="hljs-title class_">NGHTTP2</span>_REFUSED_STREAM);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-keyword">const</span> auth = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`tcp://<span class="hljs-subst">${headers[<span class="hljs-string">':authority'</span>]}</span>`</span>);
<span class="hljs-comment">// It's a very good idea to verify that hostname and port are</span>
<span class="hljs-comment">// things this proxy should be connecting to.</span>
<span class="hljs-keyword">const</span> socket = <span class="hljs-title function_">connect</span>(auth.<span class="hljs-property">port</span>, auth.<span class="hljs-property">hostname</span>, <span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">respond</span>();
socket.<span class="hljs-title function_">pipe</span>(stream);
stream.<span class="hljs-title function_">pipe</span>(socket);
});
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> {
stream.<span class="hljs-title function_">close</span>(<span class="hljs-title class_">NGHTTP2</span>_CONNECT_ERROR);
});
});
proxy.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8001</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">NGHTTP2</span>_REFUSED_STREAM } = http2.<span class="hljs-property">constants</span>;
<span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> proxy = http2.<span class="hljs-title function_">createServer</span>();
proxy.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
<span class="hljs-keyword">if</span> (headers[<span class="hljs-string">':method'</span>] !== <span class="hljs-string">'CONNECT'</span>) {
<span class="hljs-comment">// Only accept CONNECT requests</span>
stream.<span class="hljs-title function_">close</span>(<span class="hljs-title class_">NGHTTP2</span>_REFUSED_STREAM);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-keyword">const</span> auth = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`tcp://<span class="hljs-subst">${headers[<span class="hljs-string">':authority'</span>]}</span>`</span>);
<span class="hljs-comment">// It's a very good idea to verify that hostname and port are</span>
<span class="hljs-comment">// things this proxy should be connecting to.</span>
<span class="hljs-keyword">const</span> socket = net.<span class="hljs-title function_">connect</span>(auth.<span class="hljs-property">port</span>, auth.<span class="hljs-property">hostname</span>, <span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">respond</span>();
socket.<span class="hljs-title function_">pipe</span>(stream);
stream.<span class="hljs-title function_">pipe</span>(socket);
});
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> {
stream.<span class="hljs-title function_">close</span>(http2.<span class="hljs-property">constants</span>.<span class="hljs-property">NGHTTP2_CONNECT_ERROR</span>);
});
});
proxy.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8001</span>);</code><button class="copy-button">copy</button></pre>
<p>An HTTP/2 CONNECT client:</p>
<pre class="with-48-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> { connect, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://localhost:8001'</span>);
<span class="hljs-comment">// Must not specify the ':path' and ':scheme' headers</span>
<span class="hljs-comment">// for CONNECT requests or an error will be thrown.</span>
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({
<span class="hljs-string">':method'</span>: <span class="hljs-string">'CONNECT'</span>,
<span class="hljs-string">':authority'</span>: <span class="hljs-string">'localhost:8000'</span>,
});
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[constants.<span class="hljs-property">HTTP2_HEADER_STATUS</span>]);
});
<span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
req.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</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> data += chunk);
req.<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">`The server says: <span class="hljs-subst">${data}</span>`</span>);
client.<span class="hljs-title function_">close</span>();
});
req.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Jane'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://localhost:8001'</span>);
<span class="hljs-comment">// Must not specify the ':path' and ':scheme' headers</span>
<span class="hljs-comment">// for CONNECT requests or an error will be thrown.</span>
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({
<span class="hljs-string">':method'</span>: <span class="hljs-string">'CONNECT'</span>,
<span class="hljs-string">':authority'</span>: <span class="hljs-string">'localhost:8000'</span>,
});
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[http2.<span class="hljs-property">constants</span>.<span class="hljs-property">HTTP2_HEADER_STATUS</span>]);
});
<span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
req.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</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> data += chunk);
req.<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">`The server says: <span class="hljs-subst">${data}</span>`</span>);
client.<span class="hljs-title function_">close</span>();
});
req.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Jane'</span>);</code><button class="copy-button">copy</button></pre>
<h4>The extended <code>CONNECT</code> protocol<span><a class="mark" href="#all_http2_the-extended-connect-protocol" id="all_http2_the-extended-connect-protocol">#</a></span><a aria-hidden="true" class="legacy" id="http2_the_extended_connect_protocol"></a></h4>
<p><a href="https://tools.ietf.org/html/rfc8441">RFC 8441</a> defines an "Extended CONNECT Protocol" extension to HTTP/2 that
may be used to bootstrap the use of an <code>Http2Stream</code> using the <code>CONNECT</code>
method as a tunnel for other communication protocols (such as WebSockets).</p>
<p>The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using
the <code>enableConnectProtocol</code> setting:</p>
<pre class="with-49-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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> settings = { <span class="hljs-attr">enableConnectProtocol</span>: <span class="hljs-literal">true</span> };
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>({ settings });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> settings = { <span class="hljs-attr">enableConnectProtocol</span>: <span class="hljs-literal">true</span> };
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>({ settings });</code><button class="copy-button">copy</button></pre>
<p>Once the client receives the <code>SETTINGS</code> frame from the server indicating that
the extended CONNECT may be used, it may send <code>CONNECT</code> requests that use the
<code>':protocol'</code> HTTP/2 pseudo-header:</p>
<pre class="with-54-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> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://localhost:8080'</span>);
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'remoteSettings'</span>, <span class="hljs-function">(<span class="hljs-params">settings</span>) =></span> {
<span class="hljs-keyword">if</span> (settings.<span class="hljs-property">enableConnectProtocol</span>) {
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':method'</span>: <span class="hljs-string">'CONNECT'</span>, <span class="hljs-string">':protocol'</span>: <span class="hljs-string">'foo'</span> });
<span class="hljs-comment">// ...</span>
}
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://localhost:8080'</span>);
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'remoteSettings'</span>, <span class="hljs-function">(<span class="hljs-params">settings</span>) =></span> {
<span class="hljs-keyword">if</span> (settings.<span class="hljs-property">enableConnectProtocol</span>) {
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':method'</span>: <span class="hljs-string">'CONNECT'</span>, <span class="hljs-string">':protocol'</span>: <span class="hljs-string">'foo'</span> });
<span class="hljs-comment">// ...</span>
}
});</code><button class="copy-button">copy</button></pre>
</section><section><h3>Compatibility API<span><a class="mark" href="#all_http2_compatibility-api" id="all_http2_compatibility-api">#</a></span><a aria-hidden="true" class="legacy" id="http2_compatibility_api"></a></h3>
<p>The Compatibility API has the goal of providing a similar developer experience
of HTTP/1 when using HTTP/2, making it possible to develop applications
that support both <a href="http.html">HTTP/1</a> and HTTP/2. This API targets only the
<strong>public API</strong> of the <a href="http.html">HTTP/1</a>. However many modules use internal
methods or state, and those <em>are not supported</em> as it is a completely
different implementation.</p>
<p>The following example creates an HTTP/2 server using the compatibility
API:</p>
<pre class="with-49-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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>);
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>);
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>In order to create a mixed <a href="https.html">HTTPS</a> and HTTP/2 server, refer to the
<a href="#all_http2_alpn-negotiation">ALPN negotiation</a> section.
Upgrading from non-tls HTTP/1 servers is not supported.</p>
<p>The HTTP/2 compatibility API is composed of <a href="#all_http2_class-http2http2serverrequest"><code>Http2ServerRequest</code></a> and
<a href="#all_http2_class-http2http2serverresponse"><code>Http2ServerResponse</code></a>. They aim at API compatibility with HTTP/1, but
they do not hide the differences between the protocols. As an example,
the status message for HTTP codes is ignored.</p>
<h4>ALPN negotiation<span><a class="mark" href="#all_http2_alpn-negotiation" id="all_http2_alpn-negotiation">#</a></span><a aria-hidden="true" class="legacy" id="http2_alpn_negotiation"></a></h4>
<p>ALPN negotiation allows supporting both <a href="https.html">HTTPS</a> and HTTP/2 over
the same socket. The <code>req</code> and <code>res</code> objects can be either HTTP/1 or
HTTP/2, and an application <strong>must</strong> restrict itself to the public API of
<a href="http.html">HTTP/1</a>, and detect if it is possible to use the more advanced
features of HTTP/2.</p>
<p>The following example creates a server that supports both protocols:</p>
<pre class="with-53-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> { createSecureServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> cert = <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'./cert.pem'</span>);
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'./key.pem'</span>);
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>(
{ cert, key, <span class="hljs-attr">allowHTTP1</span>: <span class="hljs-literal">true</span> },
onRequest,
).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">onRequest</span>(<span class="hljs-params">req, res</span>) {
<span class="hljs-comment">// Detects if it is a HTTPS request or HTTP/2</span>
<span class="hljs-keyword">const</span> { <span class="hljs-attr">socket</span>: { alpnProtocol } } = req.<span class="hljs-property">httpVersion</span> === <span class="hljs-string">'2.0'</span> ?
req.<span class="hljs-property">stream</span>.<span class="hljs-property">session</span> : req;
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'application/json'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
alpnProtocol,
<span class="hljs-attr">httpVersion</span>: req.<span class="hljs-property">httpVersion</span>,
}));
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createSecureServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> { readFileSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> cert = <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'./cert.pem'</span>);
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'./key.pem'</span>);
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>(
{ cert, key, <span class="hljs-attr">allowHTTP1</span>: <span class="hljs-literal">true</span> },
onRequest,
).<span class="hljs-title function_">listen</span>(<span class="hljs-number">4443</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">onRequest</span>(<span class="hljs-params">req, res</span>) {
<span class="hljs-comment">// Detects if it is a HTTPS request or HTTP/2</span>
<span class="hljs-keyword">const</span> { <span class="hljs-attr">socket</span>: { alpnProtocol } } = req.<span class="hljs-property">httpVersion</span> === <span class="hljs-string">'2.0'</span> ?
req.<span class="hljs-property">stream</span>.<span class="hljs-property">session</span> : req;
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'application/json'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
alpnProtocol,
<span class="hljs-attr">httpVersion</span>: req.<span class="hljs-property">httpVersion</span>,
}));
}</code><button class="copy-button">copy</button></pre>
<p>The <code>'request'</code> event works identically on both <a href="https.html">HTTPS</a> and
HTTP/2.</p>
<h4>Class: <code>http2.Http2ServerRequest</code><span><a class="mark" href="#all_http2_class-http2http2serverrequest" id="all_http2_class-http2http2serverrequest">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_http2_http2serverrequest"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a></li>
</ul>
<p>A <code>Http2ServerRequest</code> object is created by <a href="#all_http2_class-http2server"><code>http2.Server</code></a> or
<a href="#all_http2_class-http2secureserver"><code>http2.SecureServer</code></a> and passed as the first argument to the
<a href="#all_http2_event-request"><code>'request'</code></a> event. It may be used to access a request status, headers, and
data.</p>
<h5>Event: <code>'aborted'</code><span><a class="mark" href="#all_http2_event-aborted_1" id="all_http2_event-aborted_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_aborted_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'aborted'</code> event is emitted whenever a <code>Http2ServerRequest</code> instance is
abnormally aborted in mid-communication.</p>
<p>The <code>'aborted'</code> event will only be emitted if the <code>Http2ServerRequest</code> writable
side has not been ended.</p>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_http2_event-close_2" id="all_http2_event-close_2">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_close_2"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>Indicates that the underlying <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> was closed.
Just like <code>'end'</code>, this event occurs only once per response.</p>
<h5><code>request.aborted</code><span><a class="mark" href="#all_http2_requestaborted" id="all_http2_requestaborted">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_aborted"></a></h5>
<div class="api_metadata">
<span>Added in: v10.1.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>The <code>request.aborted</code> property will be <code>true</code> if the request has
been aborted.</p>
<h5><code>request.authority</code><span><a class="mark" href="#all_http2_requestauthority" id="all_http2_requestauthority">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_authority"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The request authority pseudo header field. Because HTTP/2 allows requests
to set either <code>:authority</code> or <code>host</code>, this value is derived from
<code>req.headers[':authority']</code> if present. Otherwise, it is derived from
<code>req.headers['host']</code>.</p>
<h5><code>request.complete</code><span><a class="mark" href="#all_http2_requestcomplete" id="all_http2_requestcomplete">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_complete"></a></h5>
<div class="api_metadata">
<span>Added in: v12.10.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>The <code>request.complete</code> property will be <code>true</code> if the request has
been completed, aborted, or destroyed.</p>
<h5><code>request.connection</code><span><a class="mark" href="#all_http2_requestconnection" id="all_http2_requestconnection">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_connection"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span><span>Deprecated since: v13.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http2_requestsocket"><code>request.socket</code></a>.</div><p></p>
<ul>
<li><a href="#all_net_class-netsocket" class="type"><net.Socket></a> | <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a></li>
</ul>
<p>See <a href="#all_http2_requestsocket"><code>request.socket</code></a>.</p>
<h5><code>request.destroy([error])</code><span><a class="mark" href="#all_http2_requestdestroyerror" id="all_http2_requestdestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_destroy_error"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</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>
</ul>
<p>Calls <code>destroy()</code> on the <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> that received
the <a href="#all_http2_class-http2http2serverrequest"><code>Http2ServerRequest</code></a>. If <code>error</code> is provided, an <code>'error'</code> event
is emitted and <code>error</code> is passed as an argument to any listeners on the event.</p>
<p>It does nothing if the stream was already destroyed.</p>
<h5><code>request.headers</code><span><a class="mark" href="#all_http2_requestheaders" id="all_http2_requestheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_headers"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The request/response headers object.</p>
<p>Key-value pairs of header names and values. Header names are lower-cased.</p>
<pre><code class="language-js"><span class="hljs-comment">// Prints something like:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// { 'user-agent': 'curl/7.22.0',</span>
<span class="hljs-comment">// host: '127.0.0.1:8000',</span>
<span class="hljs-comment">// accept: '*/*' }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(request.<span class="hljs-property">headers</span>);</code> <button class="copy-button">copy</button></pre>
<p>See <a href="#all_http2_headers-object">HTTP/2 Headers Object</a>.</p>
<p>In HTTP/2, the request path, host name, protocol, and method are represented as
special headers prefixed with the <code>:</code> character (e.g. <code>':path'</code>). These special
headers will be included in the <code>request.headers</code> object. Care must be taken not
to inadvertently modify these special headers or errors may occur. For instance,
removing all headers from the request will cause errors to occur:</p>
<pre><code class="language-js"><span class="hljs-title function_">removeAllHeaders</span>(request.<span class="hljs-property">headers</span>);
<span class="hljs-title function_">assert</span>(request.<span class="hljs-property">url</span>); <span class="hljs-comment">// Fails because the :path header has been removed</span></code> <button class="copy-button">copy</button></pre>
<h5><code>request.httpVersion</code><span><a class="mark" href="#all_http2_requesthttpversion" id="all_http2_requesthttpversion">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_httpversion"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>In case of server request, the HTTP version sent by the client. In the case of
client response, the HTTP version of the connected-to server. Returns
<code>'2.0'</code>.</p>
<p>Also <code>message.httpVersionMajor</code> is the first integer and
<code>message.httpVersionMinor</code> is the second.</p>
<h5><code>request.method</code><span><a class="mark" href="#all_http2_requestmethod" id="all_http2_requestmethod">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_method"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The request method as a string. Read-only. Examples: <code>'GET'</code>, <code>'DELETE'</code>.</p>
<h5><code>request.rawHeaders</code><span><a class="mark" href="#all_http2_requestrawheaders" id="all_http2_requestrawheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_rawheaders"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>The raw request/response headers list exactly as they were received.</p>
<p>The keys and values are in the same list. It is <em>not</em> a
list of tuples. So, the even-numbered offsets are key values, and the
odd-numbered offsets are the associated values.</p>
<p>Header names are not lowercased, and duplicates are not merged.</p>
<pre><code class="language-js"><span class="hljs-comment">// Prints something like:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// [ 'user-agent',</span>
<span class="hljs-comment">// 'this is invalid because there can be only one',</span>
<span class="hljs-comment">// 'User-Agent',</span>
<span class="hljs-comment">// 'curl/7.22.0',</span>
<span class="hljs-comment">// 'Host',</span>
<span class="hljs-comment">// '127.0.0.1:8000',</span>
<span class="hljs-comment">// 'ACCEPT',</span>
<span class="hljs-comment">// '*/*' ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(request.<span class="hljs-property">rawHeaders</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>request.rawTrailers</code><span><a class="mark" href="#all_http2_requestrawtrailers" id="all_http2_requestrawtrailers">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_rawtrailers"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>The raw request/response trailer keys and values exactly as they were
received. Only populated at the <code>'end'</code> event.</p>
<h5><code>request.scheme</code><span><a class="mark" href="#all_http2_requestscheme" id="all_http2_requestscheme">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_scheme"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The request scheme pseudo header field indicating the scheme
portion of the target URL.</p>
<h5><code>request.setTimeout(msecs, callback)</code><span><a class="mark" href="#all_http2_requestsettimeoutmsecs-callback" id="all_http2_requestsettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_settimeout_msecs_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_http2_class-http2http2serverrequest" class="type"><http2.Http2ServerRequest></a></li>
</ul>
<p>Sets the <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a>'s timeout value to <code>msecs</code>. If a callback is
provided, then it is added as a listener on the <code>'timeout'</code> event on
the response object.</p>
<p>If no <code>'timeout'</code> listener is added to the request, the response, or
the server, then <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a>s are destroyed when they time out. If a
handler is assigned to the request, the response, or the server's <code>'timeout'</code>
events, timed out sockets must be handled explicitly.</p>
<h5><code>request.socket</code><span><a class="mark" href="#all_http2_requestsocket" id="all_http2_requestsocket">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_socket"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_net_class-netsocket" class="type"><net.Socket></a> | <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a></li>
</ul>
<p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but
applies getters, setters, and methods based on HTTP/2 logic.</p>
<p><code>destroyed</code>, <code>readable</code>, and <code>writable</code> properties will be retrieved from and
set on <code>request.stream</code>.</p>
<p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>on</code> and <code>once</code> methods will be called on
<code>request.stream</code>.</p>
<p><code>setTimeout</code> method will be called on <code>request.stream.session</code>.</p>
<p><code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw an error with code
<code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See <a href="#all_http2_http2session-and-sockets"><code>Http2Session</code> and Sockets</a> for
more information.</p>
<p>All other interactions will be routed directly to the socket. With TLS support,
use <a href="#all_tls_tlssocketgetpeercertificatedetailed"><code>request.socket.getPeerCertificate()</code></a> to obtain the client's
authentication details.</p>
<h5><code>request.stream</code><span><a class="mark" href="#all_http2_requeststream" id="all_http2_requeststream">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_http2_class-http2stream" class="type"><Http2Stream></a></li>
</ul>
<p>The <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> object backing the request.</p>
<h5><code>request.trailers</code><span><a class="mark" href="#all_http2_requesttrailers" id="all_http2_requesttrailers">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_trailers"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The request/response trailers object. Only populated at the <code>'end'</code> event.</p>
<h5><code>request.url</code><span><a class="mark" href="#all_http2_requesturl" id="all_http2_requesturl">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_url"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Request URL string. This contains only the URL that is present in the actual
HTTP request. If the request is:</p>
<pre><code class="language-http"><span class="hljs-keyword">GET</span> <span class="hljs-string">/status?name=ryan</span> <span class="hljs-meta">HTTP/1.1</span>
<span class="hljs-attribute">Accept</span><span class="hljs-punctuation">: </span>text/plain</code> <button class="copy-button">copy</button></pre>
<p>Then <code>request.url</code> will be:</p>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js"><span class="hljs-string">'/status?name=ryan'</span></code> <button class="copy-button">copy</button></pre>
<p>To parse the url into its parts, <code>new URL()</code> can be used:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">new URL(<span class="hljs-string">'/status?name=ryan'</span>, <span class="hljs-string">'http://example.com'</span>)</span>
URL {
href: 'http://example.com/status?name=ryan',
origin: 'http://example.com',
protocol: 'http:',
username: '',
password: '',
host: 'example.com',
hostname: 'example.com',
port: '',
pathname: '/status',
search: '?name=ryan',
searchParams: URLSearchParams { 'name' => 'ryan' },
hash: ''
}</code> <button class="copy-button">copy</button></pre>
<h4>Class: <code>http2.Http2ServerResponse</code><span><a class="mark" href="#all_http2_class-http2http2serverresponse" id="all_http2_class-http2http2serverresponse">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_http2_http2serverresponse"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_stream" class="type"><Stream></a></li>
</ul>
<p>This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the <a href="#all_http2_event-request"><code>'request'</code></a> event.</p>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_http2_event-close_3" id="all_http2_event-close_3">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_close_3"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>Indicates that the underlying <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> was terminated before
<a href="#all_http2_responseenddata-encoding-callback"><code>response.end()</code></a> was called or able to flush.</p>
<h5>Event: <code>'finish'</code><span><a class="mark" href="#all_http2_event-finish" id="all_http2_event-finish">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_finish"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>Emitted when the response has been sent. More specifically, this event is
emitted when the last segment of the response headers and body have been
handed off to the HTTP/2 multiplexing for transmission over the network. It
does not imply that the client has received anything yet.</p>
<p>After this event, no more events will be emitted on the response object.</p>
<h5><code>response.addTrailers(headers)</code><span><a class="mark" href="#all_http2_responseaddtrailersheaders" id="all_http2_responseaddtrailersheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_addtrailers_headers"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>This method adds HTTP trailing headers (a header but at the end of the
message) to the response.</p>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
<h5><code>response.appendHeader(name, value)</code><span><a class="mark" href="#all_http2_responseappendheadername-value" id="all_http2_responseappendheadername-value">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_appendheader_name_value"></a></h5>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>value</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#String_type" class="type"><string[]></a></li>
</ul>
<p>Append a single header value to the header object.</p>
<p>If the value is an array, this is equivalent to calling this method multiple
times.</p>
<p>If there were no previous values for the header, this is equivalent to calling
<a href="#all_http2_responsesetheadername-value"><code>response.setHeader()</code></a>.</p>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
<pre><code class="language-js"><span class="hljs-comment">// Returns headers including "set-cookie: a" and "set-cookie: b"</span>
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'set-cookie'</span>, <span class="hljs-string">'a'</span>);
res.<span class="hljs-title function_">appendHeader</span>(<span class="hljs-string">'set-cookie'</span>, <span class="hljs-string">'b'</span>);
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h5><code>response.connection</code><span><a class="mark" href="#all_http2_responseconnection" id="all_http2_responseconnection">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_connection"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span><span>Deprecated since: v13.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http2_responsesocket"><code>response.socket</code></a>.</div><p></p>
<ul>
<li><a href="#all_net_class-netsocket" class="type"><net.Socket></a> | <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a></li>
</ul>
<p>See <a href="#all_http2_responsesocket"><code>response.socket</code></a>.</p>
<h5><code>response.createPushResponse(headers, callback)</code><span><a class="mark" href="#all_http2_responsecreatepushresponseheaders-callback" id="all_http2_responsecreatepushresponseheaders-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_createpushresponse_headers_callback"></a></h5>
<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</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>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type"><HTTP/2 Headers Object></a> An object describing the headers</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 once <code>http2stream.pushStream()</code> is finished,
or either when the attempt to create the pushed <code>Http2Stream</code> has failed or
has been rejected, or the state of <code>Http2ServerRequest</code> is closed prior to
calling the <code>http2stream.pushStream()</code> method
<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>res</code> <a href="#all_http2_class-http2http2serverresponse" class="type"><http2.Http2ServerResponse></a> The newly-created <code>Http2ServerResponse</code>
object</li>
</ul>
</li>
</ul>
<p>Call <a href="#all_http2_http2streampushstreamheaders-options-callback"><code>http2stream.pushStream()</code></a> with the given headers, and wrap the
given <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> on a newly created <code>Http2ServerResponse</code> as the callback
parameter if successful. When <code>Http2ServerRequest</code> is closed, the callback is
called with an error <code>ERR_HTTP2_INVALID_STREAM</code>.</p>
<h5><code>response.end([data[, encoding]][, callback])</code><span><a class="mark" href="#all_http2_responseenddata-encoding-callback" id="all_http2_responseenddata-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_end_data_encoding_callback"></a></h5>
<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>This method now returns a reference to <code>ServerResponse</code>.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></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>This method signals to the server that all of the response headers and body
have been sent; that server should consider this message complete.
The method, <code>response.end()</code>, MUST be called on each response.</p>
<p>If <code>data</code> is specified, it is equivalent to calling
<a href="#all_http_responsewritechunk-encoding-callback"><code>response.write(data, encoding)</code></a> followed by <code>response.end(callback)</code>.</p>
<p>If <code>callback</code> is specified, it will be called when the response stream
is finished.</p>
<h5><code>response.finished</code><span><a class="mark" href="#all_http2_responsefinished" id="all_http2_responsefinished">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_finished"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span><span>Deprecated since: v13.4.0, v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http2_responsewritableended"><code>response.writableEnded</code></a>.</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>Boolean value that indicates whether the response has completed. Starts
as <code>false</code>. After <a href="#all_http2_responseenddata-encoding-callback"><code>response.end()</code></a> executes, the value will be <code>true</code>.</p>
<h5><code>response.getHeader(name)</code><span><a class="mark" href="#all_http2_responsegetheadername" id="all_http2_responsegetheadername">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_getheader_name"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Reads out a header that has already been queued but not sent to the client.
The name is case-insensitive.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> contentType = response.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'content-type'</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>response.getHeaderNames()</code><span><a class="mark" href="#all_http2_responsegetheadernames" id="all_http2_responsegetheadernames">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_getheadernames"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>Returns an array containing the unique names of the current outgoing headers.
All header names are lowercase.</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);
<span class="hljs-keyword">const</span> headerNames = response.<span class="hljs-title function_">getHeaderNames</span>();
<span class="hljs-comment">// headerNames === ['foo', 'set-cookie']</span></code> <button class="copy-button">copy</button></pre>
<h5><code>response.getHeaders()</code><span><a class="mark" href="#all_http2_responsegetheaders" id="all_http2_responsegetheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_getheaders"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns a shallow copy of the current outgoing headers. Since a shallow copy
is used, array values may be mutated without additional calls to various
header-related http module methods. The keys of the returned object are the
header names and the values are the respective header values. All header names
are lowercase.</p>
<p>The object returned by the <code>response.getHeaders()</code> method <em>does not</em>
prototypically inherit from the JavaScript <code>Object</code>. This means that typical
<code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others
are not defined and <em>will not work</em>.</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);
<span class="hljs-keyword">const</span> headers = response.<span class="hljs-title function_">getHeaders</span>();
<span class="hljs-comment">// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }</span></code> <button class="copy-button">copy</button></pre>
<h5><code>response.hasHeader(name)</code><span><a class="mark" href="#all_http2_responsehasheadername" id="all_http2_responsehasheadername">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_hasheader_name"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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 <code>true</code> if the header identified by <code>name</code> is currently set in the
outgoing headers. The header name matching is case-insensitive.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> hasContentType = response.<span class="hljs-title function_">hasHeader</span>(<span class="hljs-string">'content-type'</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>response.headersSent</code><span><a class="mark" href="#all_http2_responseheaderssent" id="all_http2_responseheaderssent">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_headerssent"></a></h5>
<div class="api_metadata">
<span>Added in: v8.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>True if headers were sent, false otherwise (read-only).</p>
<h5><code>response.removeHeader(name)</code><span><a class="mark" href="#all_http2_responseremoveheadername" id="all_http2_responseremoveheadername">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_removeheader_name"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Removes a header that has been queued for implicit sending.</p>
<pre><code class="language-js">response.<span class="hljs-title function_">removeHeader</span>(<span class="hljs-string">'Content-Encoding'</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>response.req</code><span><a class="mark" href="#all_http2_responsereq" id="all_http2_responsereq">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_req"></a></h5>
<div class="api_metadata">
<span>Added in: v15.7.0</span>
</div>
<ul>
<li><a href="#all_http2_class-http2http2serverrequest" class="type"><http2.Http2ServerRequest></a></li>
</ul>
<p>A reference to the original HTTP2 <code>request</code> object.</p>
<h5><code>response.sendDate</code><span><a class="mark" href="#all_http2_responsesenddate" id="all_http2_responsesenddate">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_senddate"></a></h5>
<div class="api_metadata">
<span>Added in: v8.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>When true, the Date header will be automatically generated and sent in
the response if it is not already present in the headers. Defaults to true.</p>
<p>This should only be disabled for testing; HTTP requires the Date header
in responses.</p>
<h5><code>response.setHeader(name, value)</code><span><a class="mark" href="#all_http2_responsesetheadername-value" id="all_http2_responsesetheadername-value">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_setheader_name_value"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>value</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#String_type" class="type"><string[]></a></li>
</ul>
<p>Sets a single header value for implicit headers. If this header already exists
in the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name.</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html; charset=utf-8'</span>);</code> <button class="copy-button">copy</button></pre>
<p>or</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]);</code> <button class="copy-button">copy</button></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
<p>When headers have been set with <a href="#all_http2_responsesetheadername-value"><code>response.setHeader()</code></a>, they will be merged
with any headers passed to <a href="#all_http2_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a>, with the headers passed
to <a href="#all_http2_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="language-js"><span class="hljs-comment">// Returns content-type = text/plain</span>
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html; charset=utf-8'</span>);
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>);
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h5><code>response.setTimeout(msecs[, callback])</code><span><a class="mark" href="#all_http2_responsesettimeoutmsecs-callback" id="all_http2_responsesettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_settimeout_msecs_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_http2_class-http2http2serverresponse" class="type"><http2.Http2ServerResponse></a></li>
</ul>
<p>Sets the <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a>'s timeout value to <code>msecs</code>. If a callback is
provided, then it is added as a listener on the <code>'timeout'</code> event on
the response object.</p>
<p>If no <code>'timeout'</code> listener is added to the request, the response, or
the server, then <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a>s are destroyed when they time out. If a
handler is assigned to the request, the response, or the server's <code>'timeout'</code>
events, timed out sockets must be handled explicitly.</p>
<h5><code>response.socket</code><span><a class="mark" href="#all_http2_responsesocket" id="all_http2_responsesocket">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_socket"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_net_class-netsocket" class="type"><net.Socket></a> | <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a></li>
</ul>
<p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but
applies getters, setters, and methods based on HTTP/2 logic.</p>
<p><code>destroyed</code>, <code>readable</code>, and <code>writable</code> properties will be retrieved from and
set on <code>response.stream</code>.</p>
<p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>on</code> and <code>once</code> methods will be called on
<code>response.stream</code>.</p>
<p><code>setTimeout</code> method will be called on <code>response.stream.session</code>.</p>
<p><code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw an error with code
<code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See <a href="#all_http2_http2session-and-sockets"><code>Http2Session</code> and Sockets</a> for
more information.</p>
<p>All other interactions will be routed directly to the socket.</p>
<pre class="with-49-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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <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> ip = req.<span class="hljs-property">socket</span>.<span class="hljs-property">remoteAddress</span>;
<span class="hljs-keyword">const</span> port = req.<span class="hljs-property">socket</span>.<span class="hljs-property">remotePort</span>;
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<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> ip = req.<span class="hljs-property">socket</span>.<span class="hljs-property">remoteAddress</span>;
<span class="hljs-keyword">const</span> port = req.<span class="hljs-property">socket</span>.<span class="hljs-property">remotePort</span>;
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><button class="copy-button">copy</button></pre>
<h5><code>response.statusCode</code><span><a class="mark" href="#all_http2_responsestatuscode" id="all_http2_responsestatuscode">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_statuscode"></a></h5>
<div class="api_metadata">
<span>Added in: v8.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>When using implicit headers (not calling <a href="#all_http2_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> explicitly),
this property controls the status code that will be sent to the client when
the headers get flushed.</p>
<pre><code class="language-js">response.<span class="hljs-property">statusCode</span> = <span class="hljs-number">404</span>;</code> <button class="copy-button">copy</button></pre>
<p>After response header was sent to the client, this property indicates the
status code which was sent out.</p>
<h5><code>response.statusMessage</code><span><a class="mark" href="#all_http2_responsestatusmessage" id="all_http2_responsestatusmessage">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_statusmessage"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns
an empty string.</p>
<h5><code>response.stream</code><span><a class="mark" href="#all_http2_responsestream" id="all_http2_responsestream">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_http2_class-http2stream" class="type"><Http2Stream></a></li>
</ul>
<p>The <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> object backing the response.</p>
<h5><code>response.writableEnded</code><span><a class="mark" href="#all_http2_responsewritableended" id="all_http2_responsewritableended">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_writableended"></a></h5>
<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="#all_http2_responseenddata-encoding-callback"><code>response.end()</code></a> has been called. This property
does not indicate whether the data has been flushed, for this use
<a href="#all_stream_writablewritablefinished"><code>writable.writableFinished</code></a> instead.</p>
<h5><code>response.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#all_http2_responsewritechunk-encoding-callback" id="all_http2_responsewritechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_write_chunk_encoding_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</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="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></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>If this method is called and <a href="#all_http2_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> has not been called,
it will switch to implicit header mode and flush the implicit headers.</p>
<p>This sends a chunk of the response body. This method may
be called multiple times to provide successive parts of the body.</p>
<p>In the <code>node:http</code> module, the response body is omitted when the
request is a HEAD request. Similarly, the <code>204</code> and <code>304</code> responses
<em>must not</em> include a message body.</p>
<p><code>chunk</code> can be a string or a buffer. If <code>chunk</code> is a string,
the second parameter specifies how to encode it into a byte stream.
By default the <code>encoding</code> is <code>'utf8'</code>. <code>callback</code> will be called when this chunk
of data is flushed.</p>
<p>This is the raw HTTP body and has nothing to do with higher-level multi-part
body encodings that may be used.</p>
<p>The first time <a href="#all_http2_responsewritechunk-encoding-callback"><code>response.write()</code></a> is called, it will send the buffered
header information and the first chunk of the body to the client. The second
time <a href="#all_http2_responsewritechunk-encoding-callback"><code>response.write()</code></a> is called, Node.js assumes data will be streamed,
and sends the new data separately. That is, the response is buffered up to the
first chunk of the body.</p>
<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
buffer. Returns <code>false</code> if all or part of the data was queued in user memory.
<code>'drain'</code> will be emitted when the buffer is free again.</p>
<h5><code>response.writeContinue()</code><span><a class="mark" href="#all_http2_responsewritecontinue" id="all_http2_responsewritecontinue">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_writecontinue"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>Sends a status <code>100 Continue</code> to the client, indicating that the request body
should be sent. See the <a href="#all_http2_event-checkcontinue"><code>'checkContinue'</code></a> event on <code>Http2Server</code> and
<code>Http2SecureServer</code>.</p>
<h5><code>response.writeEarlyHints(hints)</code><span><a class="mark" href="#all_http2_responsewriteearlyhintshints" id="all_http2_responsewriteearlyhintshints">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_writeearlyhints_hints"></a></h5>
<div class="api_metadata">
<span>Added in: v18.11.0</span>
</div>
<ul>
<li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Sends a status <code>103 Early Hints</code> to the client with a Link header,
indicating that the user agent can preload/preconnect the linked resources.
The <code>hints</code> is an object containing the values of headers to be sent with
early hints message.</p>
<p><strong>Example</strong></p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> earlyHintsLink = <span class="hljs-string">'</styles.css>; rel=preload; as=style'</span>;
response.<span class="hljs-title function_">writeEarlyHints</span>({
<span class="hljs-string">'link'</span>: earlyHintsLink,
});
<span class="hljs-keyword">const</span> earlyHintsLinks = [
<span class="hljs-string">'</styles.css>; rel=preload; as=style'</span>,
<span class="hljs-string">'</scripts.js>; rel=preload; as=script'</span>,
];
response.<span class="hljs-title function_">writeEarlyHints</span>({
<span class="hljs-string">'link'</span>: earlyHintsLinks,
});</code> <button class="copy-button">copy</button></pre>
<h5><code>response.writeHead(statusCode[, statusMessage][, headers])</code><span><a class="mark" href="#all_http2_responsewriteheadstatuscode-statusmessage-headers" id="all_http2_responsewriteheadstatuscode-statusmessage-headers">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_writehead_statuscode_statusmessage_headers"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.10.0, v10.17.0</td>
<td><p>Return <code>this</code> from <code>writeHead()</code> to allow chaining with <code>end()</code>.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>statusMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
<li>Returns: <a href="#all_http2_class-http2http2serverresponse" class="type"><http2.Http2ServerResponse></a></li>
</ul>
<p>Sends a response header to the request. The status code is a 3-digit HTTP
status code, like <code>404</code>. The last argument, <code>headers</code>, are the response headers.</p>
<p>Returns a reference to the <code>Http2ServerResponse</code>, so that calls can be chained.</p>
<p>For compatibility with <a href="http.html">HTTP/1</a>, a human-readable <code>statusMessage</code> may be
passed as the second argument. However, because the <code>statusMessage</code> has no
meaning within HTTP/2, the argument will have no effect and a process warning
will be emitted.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> body = <span class="hljs-string">'hello world'</span>;
response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, {
<span class="hljs-string">'Content-Length'</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(body),
<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
});</code> <button class="copy-button">copy</button></pre>
<p><code>Content-Length</code> is given in bytes not characters. The
<code>Buffer.byteLength()</code> API may be used to determine the number of bytes in a
given encoding. On outbound messages, Node.js does not check if Content-Length
and the length of the body being transmitted are equal or not. However, when
receiving messages, Node.js will automatically reject messages when the
<code>Content-Length</code> does not match the actual payload size.</p>
<p>This method may be called at most one time on a message before
<a href="#all_http2_responseenddata-encoding-callback"><code>response.end()</code></a> is called.</p>
<p>If <a href="#all_http2_responsewritechunk-encoding-callback"><code>response.write()</code></a> or <a href="#all_http2_responseenddata-encoding-callback"><code>response.end()</code></a> are called before calling
this, the implicit/mutable headers will be calculated and call this function.</p>
<p>When headers have been set with <a href="#all_http2_responsesetheadername-value"><code>response.setHeader()</code></a>, they will be merged
with any headers passed to <a href="#all_http2_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a>, with the headers passed
to <a href="#all_http2_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="language-js"><span class="hljs-comment">// Returns content-type = text/plain</span>
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html; charset=utf-8'</span>);
res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>);
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> });
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
</section><section><h3>Collecting HTTP/2 performance metrics<span><a class="mark" href="#all_http2_collecting-http2-performance-metrics" id="all_http2_collecting-http2-performance-metrics">#</a></span><a aria-hidden="true" class="legacy" id="http2_collecting_http_2_performance_metrics"></a></h3>
<p>The <a href="perf_hooks.html">Performance Observer</a> API can be used to collect basic performance
metrics for each <code>Http2Session</code> and <code>Http2Stream</code> instance.</p>
<pre class="with-59-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_">PerformanceObserver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:perf_hooks'</span>;
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> {
<span class="hljs-keyword">const</span> entry = items.<span class="hljs-title function_">getEntries</span>()[<span class="hljs-number">0</span>];
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(entry.<span class="hljs-property">entryType</span>); <span class="hljs-comment">// prints 'http2'</span>
<span class="hljs-keyword">if</span> (entry.<span class="hljs-property">name</span> === <span class="hljs-string">'Http2Session'</span>) {
<span class="hljs-comment">// Entry contains statistics about the Http2Session</span>
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (entry.<span class="hljs-property">name</span> === <span class="hljs-string">'Http2Stream'</span>) {
<span class="hljs-comment">// Entry contains statistics about the Http2Stream</span>
}
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'http2'</span>] });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">PerformanceObserver</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> {
<span class="hljs-keyword">const</span> entry = items.<span class="hljs-title function_">getEntries</span>()[<span class="hljs-number">0</span>];
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(entry.<span class="hljs-property">entryType</span>); <span class="hljs-comment">// prints 'http2'</span>
<span class="hljs-keyword">if</span> (entry.<span class="hljs-property">name</span> === <span class="hljs-string">'Http2Session'</span>) {
<span class="hljs-comment">// Entry contains statistics about the Http2Session</span>
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (entry.<span class="hljs-property">name</span> === <span class="hljs-string">'Http2Stream'</span>) {
<span class="hljs-comment">// Entry contains statistics about the Http2Stream</span>
}
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'http2'</span>] });</code><button class="copy-button">copy</button></pre>
<p>The <code>entryType</code> property of the <code>PerformanceEntry</code> will be equal to <code>'http2'</code>.</p>
<p>The <code>name</code> property of the <code>PerformanceEntry</code> will be equal to either
<code>'Http2Stream'</code> or <code>'Http2Session'</code>.</p>
<p>If <code>name</code> is equal to <code>Http2Stream</code>, the <code>PerformanceEntry</code> will contain the
following additional properties:</p>
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of <code>DATA</code> frame bytes received for this
<code>Http2Stream</code>.</li>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of <code>DATA</code> frame bytes sent for this
<code>Http2Stream</code>.</li>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The identifier of the associated <code>Http2Stream</code></li>
<li><code>timeToFirstByte</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds elapsed between the
<code>PerformanceEntry</code> <code>startTime</code> and the reception of the first <code>DATA</code> frame.</li>
<li><code>timeToFirstByteSent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds elapsed between
the <code>PerformanceEntry</code> <code>startTime</code> and sending of the first <code>DATA</code> frame.</li>
<li><code>timeToFirstHeader</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds elapsed between the
<code>PerformanceEntry</code> <code>startTime</code> and the reception of the first header.</li>
</ul>
<p>If <code>name</code> is equal to <code>Http2Session</code>, the <code>PerformanceEntry</code> will contain the
following additional properties:</p>
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes received for this <code>Http2Session</code>.</li>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes sent for this <code>Http2Session</code>.</li>
<li><code>framesReceived</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of HTTP/2 frames received by the
<code>Http2Session</code>.</li>
<li><code>framesSent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of HTTP/2 frames sent by the <code>Http2Session</code>.</li>
<li><code>maxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum number of streams concurrently
open during the lifetime of the <code>Http2Session</code>.</li>
<li><code>pingRTT</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds elapsed since the transmission
of a <code>PING</code> frame and the reception of its acknowledgment. Only present if
a <code>PING</code> frame has been sent on the <code>Http2Session</code>.</li>
<li><code>streamAverageDuration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The average duration (in milliseconds) for
all <code>Http2Stream</code> instances.</li>
<li><code>streamCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of <code>Http2Stream</code> instances processed by
the <code>Http2Session</code>.</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>'server'</code> or <code>'client'</code> to identify the type of
<code>Http2Session</code>.</li>
</ul>
</section><section><h3>Note on <code>:authority</code> and <code>host</code><span><a class="mark" href="#all_http2_note-on-authority-and-host" id="all_http2_note-on-authority-and-host">#</a></span><a aria-hidden="true" class="legacy" id="http2_note_on_authority_and_host"></a></h3>
<p>HTTP/2 requires requests to have either the <code>:authority</code> pseudo-header
or the <code>host</code> header. Prefer <code>:authority</code> when constructing an HTTP/2
request directly, and <code>host</code> when converting from HTTP/1 (in proxies,
for instance).</p>
<p>The compatibility API falls back to <code>host</code> if <code>:authority</code> is not
present. See <a href="#all_http2_requestauthority"><code>request.authority</code></a> for more information. However,
if you don't use the compatibility API (or use <code>req.headers</code> directly),
you need to implement any fall-back behavior yourself.</p></section>
</section>
<section><h2>HTTPS<span><a class="mark" href="#all_https_https" id="all_https_https">#</a></span><a aria-hidden="true" class="legacy" id="https_https"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/https.js">lib/https.js</a></p>
<p>HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
separate module.</p>
<section><h3>Determining if crypto support is unavailable<span><a class="mark" href="#all_https_determining-if-crypto-support-is-unavailable" id="all_https_determining-if-crypto-support-is-unavailable">#</a></span><a aria-hidden="true" class="legacy" id="https_determining_if_crypto_support_is_unavailable"></a></h3>
<p>It is possible for Node.js to be built without including support for the
<code>node:crypto</code> module. In such cases, attempting to <code>import</code> from <code>https</code> or
calling <code>require('node:https')</code> will result in an error being thrown.</p>
<p>When using CommonJS, the error thrown can be caught using try/catch:</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">let</span> https;
<span class="hljs-keyword">try</span> {
https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:https'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'https support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>When using the lexical ESM <code>import</code> keyword, the error can only be
caught if a handler for <code>process.on('uncaughtException')</code> is registered
<em>before</em> any attempt to load the module is made (using, for instance,
a preload module).</p>
<p>When using ESM, if there is a chance that the code may be run on a build
of Node.js where crypto support is not enabled, consider using the
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import"><code>import()</code></a> function instead of the lexical <code>import</code> keyword:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">let</span> https;
<span class="hljs-keyword">try</span> {
https = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:https'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'https support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>https.Agent</code><span><a class="mark" href="#all_https_class-httpsagent" id="all_https_class-httpsagent">#</a></span><a aria-hidden="true" class="legacy" id="https_class_https_agent"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.3.0</td>
<td><p>support <code>0</code> <code>maxCachedSessions</code> to disable TLS session caching.</p></td></tr>
<tr><td>v2.5.0</td>
<td><p>parameter <code>maxCachedSessions</code> added to <code>options</code> for TLS sessions reuse.</p></td></tr>
<tr><td>v0.4.5</td>
<td><p><span>Added in: v0.4.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An <a href="#all_https_class-httpsagent"><code>Agent</code></a> object for HTTPS similar to <a href="#all_http_class-httpagent"><code>http.Agent</code></a>. See
<a href="#all_https_httpsrequestoptions-callback"><code>https.request()</code></a> for more information.</p>
<h4><code>new Agent([options])</code><span><a class="mark" href="#all_https_new-agentoptions" id="all_https_new-agentoptions">#</a></span><a aria-hidden="true" class="legacy" id="https_new_agent_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>v12.5.0</td>
<td><p>do not automatically set servername if the target host was specified using an IP address.</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> Set of configurable options to set on the agent.
Can have the same fields as for <a href="#all_http_new-agentoptions"><code>http.Agent(options)</code></a>, and
<ul>
<li>
<p><code>maxCachedSessions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> maximum number of TLS cached sessions.
Use <code>0</code> to disable TLS session caching. <strong>Default:</strong> <code>100</code>.</p>
</li>
<li>
<p><code>servername</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> the value of
<a href="https://en.wikipedia.org/wiki/Server_Name_Indication">Server Name Indication extension</a> to be sent to the server. Use
empty string <code>''</code> to disable sending the extension.
<strong>Default:</strong> host name of the target server, unless the target server
is specified using an IP address, in which case the default is <code>''</code> (no
extension).</p>
<p>See <a href="#all_tls_session-resumption"><code>Session Resumption</code></a> for information about TLS session reuse.</p>
</li>
</ul>
</li>
</ul>
<h5>Event: <code>'keylog'</code><span><a class="mark" href="#all_https_event-keylog" id="all_https_event-keylog">#</a></span><a aria-hidden="true" class="legacy" id="https_event_keylog"></a></h5>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<ul>
<li><code>line</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> Line of ASCII text, in NSS <code>SSLKEYLOGFILE</code> format.</li>
<li><code>tlsSocket</code> <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a> The <code>tls.TLSSocket</code> instance on which it was
generated.</li>
</ul>
<p>The <code>keylog</code> event is emitted when key material is generated or received by a
connection managed by this agent (typically before handshake has completed, but
not necessarily). This keying material can be stored for debugging, as it
allows captured TLS traffic to be decrypted. It may be emitted multiple times
for each socket.</p>
<p>A typical use case is to append received lines to a common text file, which is
later used by software (such as Wireshark) to decrypt the traffic:</p>
<pre><code class="language-js"><span class="hljs-comment">// ...</span>
https.<span class="hljs-property">globalAgent</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'keylog'</span>, <span class="hljs-function">(<span class="hljs-params">line, tlsSocket</span>) =></span> {
fs.<span class="hljs-title function_">appendFileSync</span>(<span class="hljs-string">'/tmp/ssl-keys.log'</span>, line, { <span class="hljs-attr">mode</span>: <span class="hljs-number">0o600</span> });
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>https.Server</code><span><a class="mark" href="#all_https_class-httpsserver" id="all_https_class-httpsserver">#</a></span><a aria-hidden="true" class="legacy" id="https_class_https_server"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<ul>
<li>Extends: <a href="#all_tls_class-tlsserver" class="type"><tls.Server></a></li>
</ul>
<p>See <a href="#all_http_class-httpserver"><code>http.Server</code></a> for more information.</p>
<h4><code>server.close([callback])</code><span><a class="mark" href="#all_https_serverclosecallback" id="all_https_serverclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="https_server_close_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</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></li>
<li>Returns: <a href="#all_https_class-httpsserver" class="type"><https.Server></a></li>
</ul>
<p>See <a href="#all_http_serverclosecallback"><code>server.close()</code></a> in the <code>node:http</code> module.</p>
<h4><code>server[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_https_serversymbolasyncdispose" id="all_https_serversymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="https_server_symbol_asyncdispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_https_serverclosecallback"><code>server.close()</code></a> and returns a promise that
fulfills when the server has closed.</p>
<h4><code>server.closeAllConnections()</code><span><a class="mark" href="#all_https_servercloseallconnections" id="all_https_servercloseallconnections">#</a></span><a aria-hidden="true" class="legacy" id="https_server_closeallconnections"></a></h4>
<div class="api_metadata">
<span>Added in: v18.2.0</span>
</div>
<p>See <a href="#all_http_servercloseallconnections"><code>server.closeAllConnections()</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.closeIdleConnections()</code><span><a class="mark" href="#all_https_servercloseidleconnections" id="all_https_servercloseidleconnections">#</a></span><a aria-hidden="true" class="legacy" id="https_server_closeidleconnections"></a></h4>
<div class="api_metadata">
<span>Added in: v18.2.0</span>
</div>
<p>See <a href="#all_http_servercloseidleconnections"><code>server.closeIdleConnections()</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.headersTimeout</code><span><a class="mark" href="#all_https_serverheaderstimeout" id="all_https_serverheaderstimeout">#</a></span><a aria-hidden="true" class="legacy" id="https_server_headerstimeout"></a></h4>
<div class="api_metadata">
<span>Added in: v11.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> <strong>Default:</strong> <code>60000</code></li>
</ul>
<p>See <a href="#all_http_serverheaderstimeout"><code>server.headersTimeout</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.listen()</code><span><a class="mark" href="#all_https_serverlisten" id="all_https_serverlisten">#</a></span><a aria-hidden="true" class="legacy" id="https_server_listen"></a></h4>
<p>Starts the HTTPS server listening for encrypted connections.
This method is identical to <a href="#all_net_serverlisten"><code>server.listen()</code></a> from <a href="#all_net_class-netserver"><code>net.Server</code></a>.</p>
<h4><code>server.maxHeadersCount</code><span><a class="mark" href="#all_https_servermaxheaderscount" id="all_https_servermaxheaderscount">#</a></span><a aria-hidden="true" class="legacy" id="https_server_maxheaderscount"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>2000</code></li>
</ul>
<p>See <a href="#all_http_servermaxheaderscount"><code>server.maxHeadersCount</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.requestTimeout</code><span><a class="mark" href="#all_https_serverrequesttimeout" id="all_https_serverrequesttimeout">#</a></span><a aria-hidden="true" class="legacy" id="https_server_requesttimeout"></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</td>
<td><p>The default request timeout changed from no timeout to 300s (5 minutes).</p></td></tr>
<tr><td>v14.11.0</td>
<td><p><span>Added in: v14.11.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>300000</code></li>
</ul>
<p>See <a href="#all_http_serverrequesttimeout"><code>server.requestTimeout</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.setTimeout([msecs][, callback])</code><span><a class="mark" href="#all_https_serversettimeoutmsecs-callback" id="all_https_serversettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="https_server_settimeout_msecs_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div>
<ul>
<li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_https_class-httpsserver" class="type"><https.Server></a></li>
</ul>
<p>See <a href="#all_http_serversettimeoutmsecs-callback"><code>server.setTimeout()</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.timeout</code><span><a class="mark" href="#all_https_servertimeout" id="all_https_servertimeout">#</a></span><a aria-hidden="true" class="legacy" id="https_server_timeout"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</p></td></tr>
<tr><td>v0.11.2</td>
<td><p><span>Added in: v0.11.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> 0 (no timeout)</li>
</ul>
<p>See <a href="#all_http_servertimeout"><code>server.timeout</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.keepAliveTimeout</code><span><a class="mark" href="#all_https_serverkeepalivetimeout" id="all_https_serverkeepalivetimeout">#</a></span><a aria-hidden="true" class="legacy" id="https_server_keepalivetimeout"></a></h4>
<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#Number_type" class="type"><number></a> <strong>Default:</strong> <code>5000</code> (5 seconds)</li>
</ul>
<p>See <a href="#all_http_serverkeepalivetimeout"><code>server.keepAliveTimeout</code></a> in the <code>node:http</code> module.</p>
</section><section><h3><code>https.createServer([options][, requestListener])</code><span><a class="mark" href="#all_https_httpscreateserveroptions-requestlistener" id="all_https_httpscreateserveroptions-requestlistener">#</a></span><a aria-hidden="true" class="legacy" id="https_https_createserver_options_requestlistener"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</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> Accepts <code>options</code> from <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a>,
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> and <a href="#all_http_httpcreateserveroptions-requestlistener"><code>http.createServer()</code></a>.</li>
<li><code>requestListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A listener to be added to the <code>'request'</code> event.</li>
<li>Returns: <a href="#all_https_class-httpsserver" class="type"><https.Server></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-comment">// curl -k https://localhost:8000/</span>
<span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
<span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">key</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'private-key.pem'</span>),
<span class="hljs-attr">cert</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'certificate.pem'</span>),
};
<span class="hljs-title function_">createServer</span>(options, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-comment">// curl -k https://localhost:8000/</span>
<span class="hljs-keyword">const</span> https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:https'</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> options = {
<span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'private-key.pem'</span>),
<span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'certificate.pem'</span>),
};
https.<span class="hljs-title function_">createServer</span>(options, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>
<p>Or</p>
<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> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
<span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">pfx</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'test_cert.pfx'</span>),
<span class="hljs-attr">passphrase</span>: <span class="hljs-string">'sample'</span>,
};
<span class="hljs-title function_">createServer</span>(options, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:https'</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> options = {
<span class="hljs-attr">pfx</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'test_cert.pfx'</span>),
<span class="hljs-attr">passphrase</span>: <span class="hljs-string">'sample'</span>,
};
https.<span class="hljs-title function_">createServer</span>(options, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>
<p>To generate the certificate and key for this example, run:</p>
<pre><code class="language-bash">openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj <span class="hljs-string">'/CN=localhost'</span> \
-keyout private-key.pem -out certificate.pem</code> <button class="copy-button">copy</button></pre>
<p>Then, to generate the <code>pfx</code> certificate for this example, run:</p>
<pre><code class="language-bash">openssl pkcs12 -certpbe AES-256-CBC -<span class="hljs-built_in">export</span> -out test_cert.pfx \
-inkey private-key.pem -<span class="hljs-keyword">in</span> certificate.pem -passout pass:sample</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>https.get(options[, callback])</code><span><a class="mark" href="#all_https_httpsgetoptions-callback" id="all_https_httpsgetoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="https_https_get_options_callback"></a></h3>
</section><section><h3><code>https.get(url[, options][, callback])</code><span><a class="mark" href="#all_https_httpsgeturl-options-callback" id="all_https_httpsgeturl-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="https_https_get_url_options_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr>
<tr><td>v7.5.0</td>
<td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr>
<tr><td>v0.3.6</td>
<td><p><span>Added in: v0.3.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> Accepts the same <code>options</code> as
<a href="#all_https_httpsrequestoptions-callback"><code>https.request()</code></a>, with the method set to GET by default.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>Like <a href="#all_http_httpgetoptions-callback"><code>http.get()</code></a> but for HTTPS.</p>
<p><code>options</code> can be an object, a string, or a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a> object. If <code>options</code> is a
string, it is automatically parsed with <a href="#all_url_new-urlinput-base"><code>new URL()</code></a>. If it is a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a>
object, it will be automatically converted to an ordinary <code>options</code> object.</p>
<pre class="with-36-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> { get } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-title function_">get</span>(<span class="hljs-string">'https://encrypted.google.com/'</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'statusCode:'</span>, res.<span class="hljs-property">statusCode</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'headers:'</span>, res.<span class="hljs-property">headers</span>);
res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =></span> {
process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">write</span>(d);
});
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:https'</span>);
https.<span class="hljs-title function_">get</span>(<span class="hljs-string">'https://encrypted.google.com/'</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'statusCode:'</span>, res.<span class="hljs-property">statusCode</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'headers:'</span>, res.<span class="hljs-property">headers</span>);
res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =></span> {
process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">write</span>(d);
});
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e);
});</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>https.globalAgent</code><span><a class="mark" href="#all_https_httpsglobalagent" id="all_https_httpsglobalagent">#</a></span><a aria-hidden="true" class="legacy" id="https_https_globalagent"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>The agent now uses HTTP Keep-Alive and a 5 second timeout by default.</p></td></tr>
<tr><td>v0.5.9</td>
<td><p><span>Added in: v0.5.9</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Global instance of <a href="#all_https_class-httpsagent"><code>https.Agent</code></a> for all HTTPS client requests. Diverges
from a default <a href="#all_https_class-httpsagent"><code>https.Agent</code></a> configuration by having <code>keepAlive</code> enabled and
a <code>timeout</code> of 5 seconds.</p>
</section><section><h3><code>https.request(options[, callback])</code><span><a class="mark" href="#all_https_httpsrequestoptions-callback" id="all_https_httpsrequestoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="https_https_request_options_callback"></a></h3>
</section><section><h3><code>https.request(url[, options][, callback])</code><span><a class="mark" href="#all_https_httpsrequesturl-options-callback" id="all_https_httpsrequesturl-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="https_https_request_url_options_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>clientCertEngine</code> option depends on custom engine support in OpenSSL which is deprecated in OpenSSL 3.</p></td></tr>
<tr><td>v16.7.0, v14.18.0</td>
<td><p>When using a <code>URL</code> object parsed username and password will now be properly URI decoded.</p></td></tr>
<tr><td>v14.1.0, v13.14.0</td>
<td><p>The <code>highWaterMark</code> option is accepted now.</p></td></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr>
<tr><td>v9.3.0</td>
<td><p>The <code>options</code> parameter can now include <code>clientCertEngine</code>.</p></td></tr>
<tr><td>v7.5.0</td>
<td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr>
<tr><td>v0.3.6</td>
<td><p><span>Added in: v0.3.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> Accepts all <code>options</code> from
<a href="#all_http_httprequestoptions-callback"><code>http.request()</code></a>, with some differences in default values:
<ul>
<li><code>protocol</code> <strong>Default:</strong> <code>'https:'</code></li>
<li><code>port</code> <strong>Default:</strong> <code>443</code></li>
<li><code>agent</code> <strong>Default:</strong> <code>https.globalAgent</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></li>
<li>Returns: <a href="#all_http_class-httpclientrequest" class="type"><http.ClientRequest></a></li>
</ul>
<p>Makes a request to a secure web server.</p>
<p>The following additional <code>options</code> from <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> are also accepted:
<code>ca</code>, <code>cert</code>, <code>ciphers</code>, <code>clientCertEngine</code> (deprecated), <code>crl</code>, <code>dhparam</code>, <code>ecdhCurve</code>,
<code>honorCipherOrder</code>, <code>key</code>, <code>passphrase</code>, <code>pfx</code>, <code>rejectUnauthorized</code>,
<code>secureOptions</code>, <code>secureProtocol</code>, <code>servername</code>, <code>sessionIdContext</code>,
<code>highWaterMark</code>.</p>
<p><code>options</code> can be an object, a string, or a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a> object. If <code>options</code> is a
string, it is automatically parsed with <a href="#all_url_new-urlinput-base"><code>new URL()</code></a>. If it is a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a>
object, it will be automatically converted to an ordinary <code>options</code> object.</p>
<p><code>https.request()</code> returns an instance of the <a href="#all_http_class-httpclientrequest"><code>http.ClientRequest</code></a>
class. The <code>ClientRequest</code> instance is a writable stream. If one needs to
upload a file with a POST request, then write to the <code>ClientRequest</code> object.</p>
<pre class="with-37-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> { request } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">hostname</span>: <span class="hljs-string">'encrypted.google.com'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
<span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
};
<span class="hljs-keyword">const</span> req = <span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'statusCode:'</span>, res.<span class="hljs-property">statusCode</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'headers:'</span>, res.<span class="hljs-property">headers</span>);
res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =></span> {
process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">write</span>(d);
});
});
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e);
});
req.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:https'</span>);
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">hostname</span>: <span class="hljs-string">'encrypted.google.com'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
<span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
};
<span class="hljs-keyword">const</span> req = https.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'statusCode:'</span>, res.<span class="hljs-property">statusCode</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'headers:'</span>, res.<span class="hljs-property">headers</span>);
res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =></span> {
process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">write</span>(d);
});
});
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e);
});
req.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<p>Example using options from <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">hostname</span>: <span class="hljs-string">'encrypted.google.com'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
<span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
<span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'private-key.pem'</span>),
<span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'certificate.pem'</span>),
};
options.<span class="hljs-property">agent</span> = <span class="hljs-keyword">new</span> https.<span class="hljs-title class_">Agent</span>(options);
<span class="hljs-keyword">const</span> req = https.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-comment">// ...</span>
});</code> <button class="copy-button">copy</button></pre>
<p>Alternatively, opt out of connection pooling by not using an <a href="#all_https_class-httpsagent"><code>Agent</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">hostname</span>: <span class="hljs-string">'encrypted.google.com'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
<span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
<span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'private-key.pem'</span>),
<span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'certificate.pem'</span>),
<span class="hljs-attr">agent</span>: <span class="hljs-literal">false</span>,
};
<span class="hljs-keyword">const</span> req = https.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-comment">// ...</span>
});</code> <button class="copy-button">copy</button></pre>
<p>Example using a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a> as <code>options</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> options = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://abc:xyz@example.com'</span>);
<span class="hljs-keyword">const</span> req = https.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-comment">// ...</span>
});</code> <button class="copy-button">copy</button></pre>
<p>Example pinning on certificate fingerprint, or the public key (similar to
<code>pin-sha256</code>):</p>
<pre class="with-47-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> { checkServerIdentity } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:tls'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Agent</span>, request } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
<span class="hljs-keyword">import</span> { createHash } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:crypto'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">sha256</span>(<span class="hljs-params">s</span>) {
<span class="hljs-keyword">return</span> <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>).<span class="hljs-title function_">update</span>(s).<span class="hljs-title function_">digest</span>(<span class="hljs-string">'base64'</span>);
}
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">hostname</span>: <span class="hljs-string">'github.com'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
<span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
<span class="hljs-attr">checkServerIdentity</span>: <span class="hljs-keyword">function</span>(<span class="hljs-params">host, cert</span>) {
<span class="hljs-comment">// Make sure the certificate is issued to the host we are connected to</span>
<span class="hljs-keyword">const</span> err = <span class="hljs-title function_">checkServerIdentity</span>(host, cert);
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-keyword">return</span> err;
}
<span class="hljs-comment">// Pin the public key, similar to HPKP pin-sha256 pinning</span>
<span class="hljs-keyword">const</span> pubkey256 = <span class="hljs-string">'SIXvRyDmBJSgatgTQRGbInBaAK+hZOQ18UmrSwnDlK8='</span>;
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">sha256</span>(cert.<span class="hljs-property">pubkey</span>) !== pubkey256) {
<span class="hljs-keyword">const</span> msg = <span class="hljs-string">'Certificate verification error: '</span> +
<span class="hljs-string">`The public key of '<span class="hljs-subst">${cert.subject.CN}</span>' `</span> +
<span class="hljs-string">'does not match our pinned fingerprint'</span>;
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(msg);
}
<span class="hljs-comment">// Pin the exact certificate, rather than the pub key</span>
<span class="hljs-keyword">const</span> cert256 = <span class="hljs-string">'FD:6E:9B:0E:F3:98:BC:D9:04:C3:B2:EC:16:7A:7B:'</span> +
<span class="hljs-string">'0F:DA:72:01:C9:03:C5:3A:6A:6A:E5:D0:41:43:63:EF:65'</span>;
<span class="hljs-keyword">if</span> (cert.<span class="hljs-property">fingerprint256</span> !== cert256) {
<span class="hljs-keyword">const</span> msg = <span class="hljs-string">'Certificate verification error: '</span> +
<span class="hljs-string">`The certificate of '<span class="hljs-subst">${cert.subject.CN}</span>' `</span> +
<span class="hljs-string">'does not match our pinned fingerprint'</span>;
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(msg);
}
<span class="hljs-comment">// This loop is informational only.</span>
<span class="hljs-comment">// Print the certificate and public key fingerprints of all certs in the</span>
<span class="hljs-comment">// chain. Its common to pin the public key of the issuer on the public</span>
<span class="hljs-comment">// internet, while pinning the public key of the service in sensitive</span>
<span class="hljs-comment">// environments.</span>
<span class="hljs-keyword">let</span> lastprint256;
<span class="hljs-keyword">do</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Subject Common Name:'</span>, cert.<span class="hljs-property">subject</span>.<span class="hljs-property">CN</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">' Certificate SHA256 fingerprint:'</span>, cert.<span class="hljs-property">fingerprint256</span>);
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">' Public key ping-sha256:'</span>, <span class="hljs-title function_">sha256</span>(cert.<span class="hljs-property">pubkey</span>));
lastprint256 = cert.<span class="hljs-property">fingerprint256</span>;
cert = cert.<span class="hljs-property">issuerCertificate</span>;
} <span class="hljs-keyword">while</span> (cert.<span class="hljs-property">fingerprint256</span> !== lastprint256);
},
};
options.<span class="hljs-property">agent</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Agent</span>(options);
<span class="hljs-keyword">const</span> req = <span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'All OK. Server matched our pinned cert or public key'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'statusCode:'</span>, res.<span class="hljs-property">statusCode</span>);
res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =></span> {});
});
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e.<span class="hljs-property">message</span>);
});
req.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> tls = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:tls'</span>);
<span class="hljs-keyword">const</span> https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:https'</span>);
<span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">sha256</span>(<span class="hljs-params">s</span>) {
<span class="hljs-keyword">return</span> crypto.<span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>).<span class="hljs-title function_">update</span>(s).<span class="hljs-title function_">digest</span>(<span class="hljs-string">'base64'</span>);
}
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">hostname</span>: <span class="hljs-string">'github.com'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
<span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
<span class="hljs-attr">checkServerIdentity</span>: <span class="hljs-keyword">function</span>(<span class="hljs-params">host, cert</span>) {
<span class="hljs-comment">// Make sure the certificate is issued to the host we are connected to</span>
<span class="hljs-keyword">const</span> err = tls.<span class="hljs-title function_">checkServerIdentity</span>(host, cert);
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-keyword">return</span> err;
}
<span class="hljs-comment">// Pin the public key, similar to HPKP pin-sha256 pinning</span>
<span class="hljs-keyword">const</span> pubkey256 = <span class="hljs-string">'SIXvRyDmBJSgatgTQRGbInBaAK+hZOQ18UmrSwnDlK8='</span>;
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">sha256</span>(cert.<span class="hljs-property">pubkey</span>) !== pubkey256) {
<span class="hljs-keyword">const</span> msg = <span class="hljs-string">'Certificate verification error: '</span> +
<span class="hljs-string">`The public key of '<span class="hljs-subst">${cert.subject.CN}</span>' `</span> +
<span class="hljs-string">'does not match our pinned fingerprint'</span>;
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(msg);
}
<span class="hljs-comment">// Pin the exact certificate, rather than the pub key</span>
<span class="hljs-keyword">const</span> cert256 = <span class="hljs-string">'FD:6E:9B:0E:F3:98:BC:D9:04:C3:B2:EC:16:7A:7B:'</span> +
<span class="hljs-string">'0F:DA:72:01:C9:03:C5:3A:6A:6A:E5:D0:41:43:63:EF:65'</span>;
<span class="hljs-keyword">if</span> (cert.<span class="hljs-property">fingerprint256</span> !== cert256) {
<span class="hljs-keyword">const</span> msg = <span class="hljs-string">'Certificate verification error: '</span> +
<span class="hljs-string">`The certificate of '<span class="hljs-subst">${cert.subject.CN}</span>' `</span> +
<span class="hljs-string">'does not match our pinned fingerprint'</span>;
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(msg);
}
<span class="hljs-comment">// This loop is informational only.</span>
<span class="hljs-comment">// Print the certificate and public key fingerprints of all certs in the</span>
<span class="hljs-comment">// chain. Its common to pin the public key of the issuer on the public</span>
<span class="hljs-comment">// internet, while pinning the public key of the service in sensitive</span>
<span class="hljs-comment">// environments.</span>
<span class="hljs-keyword">do</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Subject Common Name:'</span>, cert.<span class="hljs-property">subject</span>.<span class="hljs-property">CN</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">' Certificate SHA256 fingerprint:'</span>, cert.<span class="hljs-property">fingerprint256</span>);
hash = crypto.<span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">' Public key ping-sha256:'</span>, <span class="hljs-title function_">sha256</span>(cert.<span class="hljs-property">pubkey</span>));
lastprint256 = cert.<span class="hljs-property">fingerprint256</span>;
cert = cert.<span class="hljs-property">issuerCertificate</span>;
} <span class="hljs-keyword">while</span> (cert.<span class="hljs-property">fingerprint256</span> !== lastprint256);
},
};
options.<span class="hljs-property">agent</span> = <span class="hljs-keyword">new</span> https.<span class="hljs-title class_">Agent</span>(options);
<span class="hljs-keyword">const</span> req = https.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'All OK. Server matched our pinned cert or public key'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'statusCode:'</span>, res.<span class="hljs-property">statusCode</span>);
res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =></span> {});
});
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e.<span class="hljs-property">message</span>);
});
req.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<p>Outputs for example:</p>
<pre><code class="language-text">Subject Common Name: github.com
Certificate SHA256 fingerprint: FD:6E:9B:0E:F3:98:BC:D9:04:C3:B2:EC:16:7A:7B:0F:DA:72:01:C9:03:C5:3A:6A:6A:E5:D0:41:43:63:EF:65
Public key ping-sha256: SIXvRyDmBJSgatgTQRGbInBaAK+hZOQ18UmrSwnDlK8=
Subject Common Name: Sectigo ECC Domain Validation Secure Server CA
Certificate SHA256 fingerprint: 61:E9:73:75:E9:F6:DA:98:2F:F5:C1:9E:2F:94:E6:6C:4E:35:B6:83:7C:E3:B9:14:D2:24:5C:7F:5F:65:82:5F
Public key ping-sha256: Eep0p/AsSa9lFUH6KT2UY+9s1Z8v7voAPkQ4fGknZ2g=
Subject Common Name: USERTrust ECC Certification Authority
Certificate SHA256 fingerprint: A6:CF:64:DB:B4:C8:D5:FD:19:CE:48:89:60:68:DB:03:B5:33:A8:D1:33:6C:62:56:A8:7D:00:CB:B3:DE:F3:EA
Public key ping-sha256: UJM2FOhG9aTNY0Pg4hgqjNzZ/lQBiMGRxPD5Y2/e0bw=
Subject Common Name: AAA Certificate Services
Certificate SHA256 fingerprint: D7:A7:A0:FB:5D:7E:27:31:D7:71:E9:48:4E:BC:DE:F7:1D:5F:0C:3E:0A:29:48:78:2B:C8:3E:E0:EA:69:9E:F4
Public key ping-sha256: vRU+17BDT2iGsXvOi76E7TQMcTLXAqj0+jGPdW7L1vM=
All OK. Server matched our pinned cert or public key
statusCode: 200</code> <button class="copy-button">copy</button></pre></section>
</section>
<section><h2>Inspector<span><a class="mark" href="#all_inspector_inspector" id="all_inspector_inspector">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/inspector.js">lib/inspector.js</a></p>
<p>The <code>node:inspector</code> module provides an API for interacting with the V8
inspector.</p>
<p>It can be accessed using:</p>
<pre class="with-53-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-keyword">as</span> inspector <span class="hljs-keyword">from</span> <span class="hljs-string">'node:inspector/promises'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> inspector = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:inspector/promises'</span>);</code><button class="copy-button">copy</button></pre>
<p>or</p>
<pre class="with-44-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-keyword">as</span> inspector <span class="hljs-keyword">from</span> <span class="hljs-string">'node:inspector'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> inspector = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:inspector'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>Promises API<span><a class="mark" href="#all_inspector_promises-api" id="all_inspector_promises-api">#</a></span><a aria-hidden="true" class="legacy" id="inspector_promises_api"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<h4>Class: <code>inspector.Session</code><span><a class="mark" href="#all_inspector_class-inspectorsession" id="all_inspector_class-inspectorsession">#</a></span><a aria-hidden="true" class="legacy" id="inspector_class_inspector_session"></a></h4>
<ul>
<li>Extends: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>The <code>inspector.Session</code> is used for dispatching messages to the V8 inspector
back-end and receiving message responses and notifications.</p>
<h5><code>new inspector.Session()</code><span><a class="mark" href="#all_inspector_new-inspectorsession" id="all_inspector_new-inspectorsession">#</a></span><a aria-hidden="true" class="legacy" id="inspector_new_inspector_session"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Create a new instance of the <code>inspector.Session</code> class. The inspector session
needs to be connected through <a href="#all_inspector_sessionconnect"><code>session.connect()</code></a> before the messages
can be dispatched to the inspector backend.</p>
<p>When using <code>Session</code>, the object outputted by the console API will not be
released, unless we performed manually <code>Runtime.DiscardConsoleEntries</code>
command.</p>
<h5>Event: <code>'inspectorNotification'</code><span><a class="mark" href="#all_inspector_event-inspectornotification" id="all_inspector_event-inspectornotification">#</a></span><a aria-hidden="true" class="legacy" id="inspector_event_inspectornotification"></a></h5>
<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/Reference/Global_Objects/Object" class="type"><Object></a> The notification message object</li>
</ul>
<p>Emitted when any notification from the V8 Inspector is received.</p>
<pre><code class="language-js">session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'inspectorNotification'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message.<span class="hljs-property">method</span>));
<span class="hljs-comment">// Debugger.paused</span>
<span class="hljs-comment">// Debugger.resumed</span></code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Caveat</strong> Breakpoints with same-thread session is not recommended, see
<a href="#all_inspector_support-of-breakpoints">support of breakpoints</a>.</p>
</blockquote>
<p>It is also possible to subscribe only to notifications with specific method:</p>
<h5>Event: <code><inspector-protocol-method></code>;<span><a class="mark" href="#all_inspector_event-inspector-protocol-method" id="all_inspector_event-inspector-protocol-method">#</a></span><a aria-hidden="true" class="legacy" id="inspector_event_inspector_protocol_method"></a></h5>
<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/Reference/Global_Objects/Object" class="type"><Object></a> The notification message object</li>
</ul>
<p>Emitted when an inspector notification is received that has its method field set
to the <code><inspector-protocol-method></code> value.</p>
<p>The following snippet installs a listener on the <a href="https://chromedevtools.github.io/devtools-protocol/v8/Debugger#event-paused"><code>'Debugger.paused'</code></a>
event, and prints the reason for program suspension whenever program
execution is suspended (through breakpoints, for example):</p>
<pre><code class="language-js">session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'Debugger.paused'</span>, <span class="hljs-function">(<span class="hljs-params">{ params }</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-property">hitBreakpoints</span>);
});
<span class="hljs-comment">// [ '/the/file/that/has/the/breakpoint.js:11:0' ]</span></code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Caveat</strong> Breakpoints with same-thread session is not recommended, see
<a href="#all_inspector_support-of-breakpoints">support of breakpoints</a>.</p>
</blockquote>
<h5><code>session.connect()</code><span><a class="mark" href="#all_inspector_sessionconnect" id="all_inspector_sessionconnect">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_connect"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Connects a session to the inspector back-end.</p>
<h5><code>session.connectToMainThread()</code><span><a class="mark" href="#all_inspector_sessionconnecttomainthread" id="all_inspector_sessionconnecttomainthread">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_connecttomainthread"></a></h5>
<div class="api_metadata">
<span>Added in: v12.11.0</span>
</div>
<p>Connects a session to the main thread inspector back-end. An exception will
be thrown if this API was not called on a Worker thread.</p>
<h5><code>session.disconnect()</code><span><a class="mark" href="#all_inspector_sessiondisconnect" id="all_inspector_sessiondisconnect">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_disconnect"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Immediately close the session. All pending message callbacks will be called
with an error. <a href="#all_inspector_sessionconnect"><code>session.connect()</code></a> will need to be called to be able to send
messages again. Reconnected session will lose all inspector state, such as
enabled agents or configured breakpoints.</p>
<h5><code>session.post(method[, params])</code><span><a class="mark" href="#all_inspector_sessionpostmethod-params" id="all_inspector_sessionpostmethod-params">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_post_method_params"></a></h5>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<ul>
<li><code>method</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Posts a message to the inspector back-end.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Session</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:inspector/promises'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> session = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Session</span>();
session.<span class="hljs-title function_">connect</span>();
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Runtime.evaluate'</span>, { <span class="hljs-attr">expression</span>: <span class="hljs-string">'2 + 2'</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error);
}
<span class="hljs-comment">// Output: { result: { type: 'number', value: 4, description: '4' } }</span></code> <button class="copy-button">copy</button></pre>
<p>The latest version of the V8 inspector protocol is published on the
<a href="https://chromedevtools.github.io/devtools-protocol/v8/">Chrome DevTools Protocol Viewer</a>.</p>
<p>Node.js inspector supports all the Chrome DevTools Protocol domains declared
by V8. Chrome DevTools Protocol domain provides an interface for interacting
with one of the runtime agents used to inspect the application state and listen
to the run-time events.</p>
<h5>Example usage<span><a class="mark" href="#all_inspector_example-usage" id="all_inspector_example-usage">#</a></span><a aria-hidden="true" class="legacy" id="inspector_example_usage"></a></h5>
<p>Apart from the debugger, various V8 Profilers are available through the DevTools
protocol.</p>
<h6>CPU profiler<span><a class="mark" href="#all_inspector_cpu-profiler" id="all_inspector_cpu-profiler">#</a></span><a aria-hidden="true" class="legacy" id="inspector_cpu_profiler"></a></h6>
<p>Here's an example showing how to use the <a href="https://chromedevtools.github.io/devtools-protocol/v8/Profiler">CPU Profiler</a>:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Session</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:inspector/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">const</span> session = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Session</span>();
session.<span class="hljs-title function_">connect</span>();
<span class="hljs-keyword">await</span> session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Profiler.enable'</span>);
<span class="hljs-keyword">await</span> session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Profiler.start'</span>);
<span class="hljs-comment">// Invoke business logic under measurement here...</span>
<span class="hljs-comment">// some time later...</span>
<span class="hljs-keyword">const</span> { profile } = <span class="hljs-keyword">await</span> session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Profiler.stop'</span>);
<span class="hljs-comment">// Write profile to disk, upload, etc.</span>
fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'./profile.cpuprofile'</span>, <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(profile));</code> <button class="copy-button">copy</button></pre>
<h6>Heap profiler<span><a class="mark" href="#all_inspector_heap-profiler" id="all_inspector_heap-profiler">#</a></span><a aria-hidden="true" class="legacy" id="inspector_heap_profiler"></a></h6>
<p>Here's an example showing how to use the <a href="https://chromedevtools.github.io/devtools-protocol/v8/HeapProfiler">Heap Profiler</a>:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Session</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:inspector/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">const</span> session = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Session</span>();
<span class="hljs-keyword">const</span> fd = fs.<span class="hljs-title function_">openSync</span>(<span class="hljs-string">'profile.heapsnapshot'</span>, <span class="hljs-string">'w'</span>);
session.<span class="hljs-title function_">connect</span>();
session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'HeapProfiler.addHeapSnapshotChunk'</span>, <span class="hljs-function">(<span class="hljs-params">m</span>) =></span> {
fs.<span class="hljs-title function_">writeSync</span>(fd, m.<span class="hljs-property">params</span>.<span class="hljs-property">chunk</span>);
});
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'HeapProfiler.takeHeapSnapshot'</span>, <span class="hljs-literal">null</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'HeapProfiler.takeHeapSnapshot done:'</span>, result);
session.<span class="hljs-title function_">disconnect</span>();
fs.<span class="hljs-title function_">closeSync</span>(fd);</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Callback API<span><a class="mark" href="#all_inspector_callback-api" id="all_inspector_callback-api">#</a></span><a aria-hidden="true" class="legacy" id="inspector_callback_api"></a></h3>
<h4>Class: <code>inspector.Session</code><span><a class="mark" href="#all_inspector_class-inspectorsession_1" id="all_inspector_class-inspectorsession_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_class_inspector_session_1"></a></h4>
<ul>
<li>Extends: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>The <code>inspector.Session</code> is used for dispatching messages to the V8 inspector
back-end and receiving message responses and notifications.</p>
<h5><code>new inspector.Session()</code><span><a class="mark" href="#all_inspector_new-inspectorsession_1" id="all_inspector_new-inspectorsession_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_new_inspector_session_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Create a new instance of the <code>inspector.Session</code> class. The inspector session
needs to be connected through <a href="#all_inspector_sessionconnect"><code>session.connect()</code></a> before the messages
can be dispatched to the inspector backend.</p>
<p>When using <code>Session</code>, the object outputted by the console API will not be
released, unless we performed manually <code>Runtime.DiscardConsoleEntries</code>
command.</p>
<h5>Event: <code>'inspectorNotification'</code><span><a class="mark" href="#all_inspector_event-inspectornotification_1" id="all_inspector_event-inspectornotification_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_event_inspectornotification_1"></a></h5>
<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/Reference/Global_Objects/Object" class="type"><Object></a> The notification message object</li>
</ul>
<p>Emitted when any notification from the V8 Inspector is received.</p>
<pre><code class="language-js">session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'inspectorNotification'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message.<span class="hljs-property">method</span>));
<span class="hljs-comment">// Debugger.paused</span>
<span class="hljs-comment">// Debugger.resumed</span></code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Caveat</strong> Breakpoints with same-thread session is not recommended, see
<a href="#all_inspector_support-of-breakpoints">support of breakpoints</a>.</p>
</blockquote>
<p>It is also possible to subscribe only to notifications with specific method:</p>
<h5>Event: <code><inspector-protocol-method></code>;<span><a class="mark" href="#all_inspector_event-inspector-protocol-method_1" id="all_inspector_event-inspector-protocol-method_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_event_inspector_protocol_method_1"></a></h5>
<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/Reference/Global_Objects/Object" class="type"><Object></a> The notification message object</li>
</ul>
<p>Emitted when an inspector notification is received that has its method field set
to the <code><inspector-protocol-method></code> value.</p>
<p>The following snippet installs a listener on the <a href="https://chromedevtools.github.io/devtools-protocol/v8/Debugger#event-paused"><code>'Debugger.paused'</code></a>
event, and prints the reason for program suspension whenever program
execution is suspended (through breakpoints, for example):</p>
<pre><code class="language-js">session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'Debugger.paused'</span>, <span class="hljs-function">(<span class="hljs-params">{ params }</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-property">hitBreakpoints</span>);
});
<span class="hljs-comment">// [ '/the/file/that/has/the/breakpoint.js:11:0' ]</span></code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Caveat</strong> Breakpoints with same-thread session is not recommended, see
<a href="#all_inspector_support-of-breakpoints">support of breakpoints</a>.</p>
</blockquote>
<h5><code>session.connect()</code><span><a class="mark" href="#all_inspector_sessionconnect_1" id="all_inspector_sessionconnect_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_connect_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Connects a session to the inspector back-end.</p>
<h5><code>session.connectToMainThread()</code><span><a class="mark" href="#all_inspector_sessionconnecttomainthread_1" id="all_inspector_sessionconnecttomainthread_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_connecttomainthread_1"></a></h5>
<div class="api_metadata">
<span>Added in: v12.11.0</span>
</div>
<p>Connects a session to the main thread inspector back-end. An exception will
be thrown if this API was not called on a Worker thread.</p>
<h5><code>session.disconnect()</code><span><a class="mark" href="#all_inspector_sessiondisconnect_1" id="all_inspector_sessiondisconnect_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_disconnect_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Immediately close the session. All pending message callbacks will be called
with an error. <a href="#all_inspector_sessionconnect"><code>session.connect()</code></a> will need to be called to be able to send
messages again. Reconnected session will lose all inspector state, such as
enabled agents or configured breakpoints.</p>
<h5><code>session.post(method[, params][, callback])</code><span><a class="mark" href="#all_inspector_sessionpostmethod-params-callback" id="all_inspector_sessionpostmethod-params-callback">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_post_method_params_callback"></a></h5>
<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</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>v8.0.0</td>
<td><p><span>Added in: v8.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>method</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>Posts a message to the inspector back-end. <code>callback</code> will be notified when
a response is received. <code>callback</code> is a function that accepts two optional
arguments: error and message-specific result.</p>
<pre><code class="language-js">session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Runtime.evaluate'</span>, { <span class="hljs-attr">expression</span>: <span class="hljs-string">'2 + 2'</span> },
<span class="hljs-function">(<span class="hljs-params">error, { result }</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result));
<span class="hljs-comment">// Output: { type: 'number', value: 4, description: '4' }</span></code> <button class="copy-button">copy</button></pre>
<p>The latest version of the V8 inspector protocol is published on the
<a href="https://chromedevtools.github.io/devtools-protocol/v8/">Chrome DevTools Protocol Viewer</a>.</p>
<p>Node.js inspector supports all the Chrome DevTools Protocol domains declared
by V8. Chrome DevTools Protocol domain provides an interface for interacting
with one of the runtime agents used to inspect the application state and listen
to the run-time events.</p>
<p>You can not set <code>reportProgress</code> to <code>true</code> when sending a
<code>HeapProfiler.takeHeapSnapshot</code> or <code>HeapProfiler.stopTrackingHeapObjects</code>
command to V8.</p>
<h5>Example usage<span><a class="mark" href="#all_inspector_example-usage_1" id="all_inspector_example-usage_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_example_usage_1"></a></h5>
<p>Apart from the debugger, various V8 Profilers are available through the DevTools
protocol.</p>
<h6>CPU profiler<span><a class="mark" href="#all_inspector_cpu-profiler_1" id="all_inspector_cpu-profiler_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_cpu_profiler_1"></a></h6>
<p>Here's an example showing how to use the <a href="https://chromedevtools.github.io/devtools-protocol/v8/Profiler">CPU Profiler</a>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> inspector = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:inspector'</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> session = <span class="hljs-keyword">new</span> inspector.<span class="hljs-title class_">Session</span>();
session.<span class="hljs-title function_">connect</span>();
session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Profiler.enable'</span>, <span class="hljs-function">() =></span> {
session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Profiler.start'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Invoke business logic under measurement here...</span>
<span class="hljs-comment">// some time later...</span>
session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Profiler.stop'</span>, <span class="hljs-function">(<span class="hljs-params">err, { profile }</span>) =></span> {
<span class="hljs-comment">// Write profile to disk, upload, etc.</span>
<span class="hljs-keyword">if</span> (!err) {
fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'./profile.cpuprofile'</span>, <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(profile));
}
});
});
});</code> <button class="copy-button">copy</button></pre>
<h6>Heap profiler<span><a class="mark" href="#all_inspector_heap-profiler_1" id="all_inspector_heap-profiler_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_heap_profiler_1"></a></h6>
<p>Here's an example showing how to use the <a href="https://chromedevtools.github.io/devtools-protocol/v8/HeapProfiler">Heap Profiler</a>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> inspector = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:inspector'</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> session = <span class="hljs-keyword">new</span> inspector.<span class="hljs-title class_">Session</span>();
<span class="hljs-keyword">const</span> fd = fs.<span class="hljs-title function_">openSync</span>(<span class="hljs-string">'profile.heapsnapshot'</span>, <span class="hljs-string">'w'</span>);
session.<span class="hljs-title function_">connect</span>();
session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'HeapProfiler.addHeapSnapshotChunk'</span>, <span class="hljs-function">(<span class="hljs-params">m</span>) =></span> {
fs.<span class="hljs-title function_">writeSync</span>(fd, m.<span class="hljs-property">params</span>.<span class="hljs-property">chunk</span>);
});
session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'HeapProfiler.takeHeapSnapshot'</span>, <span class="hljs-literal">null</span>, <span class="hljs-function">(<span class="hljs-params">err, r</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'HeapProfiler.takeHeapSnapshot done:'</span>, err, r);
session.<span class="hljs-title function_">disconnect</span>();
fs.<span class="hljs-title function_">closeSync</span>(fd);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Common Objects<span><a class="mark" href="#all_inspector_common-objects" id="all_inspector_common-objects">#</a></span><a aria-hidden="true" class="legacy" id="inspector_common_objects"></a></h3>
<h4><code>inspector.close()</code><span><a class="mark" href="#all_inspector_inspectorclose" id="all_inspector_inspectorclose">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_close"></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.10.0</td>
<td><p>The API is exposed in the worker threads.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p><span>Added in: v9.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Attempts to close all remaining connections, blocking the event loop until all
are closed. Once all connections are closed, deactivates the inspector.</p>
<h4><code>inspector.console</code><span><a class="mark" href="#all_inspector_inspectorconsole" id="all_inspector_inspectorconsole">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_console"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object to send messages to the remote inspector console.</li>
</ul>
<pre><code class="language-js"><span class="hljs-built_in">require</span>(<span class="hljs-string">'node:inspector'</span>).<span class="hljs-property">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a message'</span>);</code> <button class="copy-button">copy</button></pre>
<p>The inspector console does not have API parity with Node.js
console.</p>
<h4><code>inspector.open([port[, host[, wait]]])</code><span><a class="mark" href="#all_inspector_inspectoropenport-host-wait" id="all_inspector_inspectoropenport-host-wait">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_open_port_host_wait"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>inspector.open() now returns a <code>Disposable</code> object.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port to listen on for inspector connections. Optional.
<strong>Default:</strong> what was specified on the CLI.</li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host to listen on for inspector connections. Optional.
<strong>Default:</strong> what was specified on the CLI.</li>
<li><code>wait</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Block until a client has connected. Optional.
<strong>Default:</strong> <code>false</code>.</li>
<li>Returns: <a href="https://tc39.es/proposal-explicit-resource-management/#sec-disposable-interface" class="type"><Disposable></a> A Disposable that calls <a href="#all_inspector_inspectorclose"><code>inspector.close()</code></a>.</li>
</ul>
<p>Activate inspector on host and port. Equivalent to
<code>node --inspect=[[host:]port]</code>, but can be done programmatically after node has
started.</p>
<p>If wait is <code>true</code>, will block until a client has connected to the inspect port
and flow control has been passed to the debugger client.</p>
<p>See the <a href="#all_cli_warning-binding-inspector-to-a-public-ipport-combination-is-insecure">security warning</a> regarding the <code>host</code>
parameter usage.</p>
<h4><code>inspector.url()</code><span><a class="mark" href="#all_inspector_inspectorurl" id="all_inspector_inspectorurl">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_url"></a></h4>
<ul>
<li>Returns: <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#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>Return the URL of the active inspector, or <code>undefined</code> if there is none.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --inspect -p <span class="hljs-string">'inspector.url()'</span></span>
Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
For help, see: https://nodejs.org/en/docs/inspector
ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
<span class="hljs-meta prompt_">
$ </span><span class="language-bash">node --inspect=localhost:3000 -p <span class="hljs-string">'inspector.url()'</span></span>
Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
For help, see: https://nodejs.org/en/docs/inspector
ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
<span class="hljs-meta prompt_">
$ </span><span class="language-bash">node -p <span class="hljs-string">'inspector.url()'</span></span>
undefined</code> <button class="copy-button">copy</button></pre>
<h4><code>inspector.waitForDebugger()</code><span><a class="mark" href="#all_inspector_inspectorwaitfordebugger" id="all_inspector_inspectorwaitfordebugger">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_waitfordebugger"></a></h4>
<div class="api_metadata">
<span>Added in: v12.7.0</span>
</div>
<p>Blocks until a client (existing or connected later) has sent
<code>Runtime.runIfWaitingForDebugger</code> command.</p>
<p>An exception will be thrown if there is no active inspector.</p>
</section><section><h3>Integration with DevTools<span><a class="mark" href="#all_inspector_integration-with-devtools" id="all_inspector_integration-with-devtools">#</a></span><a aria-hidden="true" class="legacy" id="inspector_integration_with_devtools"></a></h3>
<p>The <code>node:inspector</code> module provides an API for integrating with devtools that support Chrome DevTools Protocol.
DevTools frontends connected to a running Node.js instance can capture protocol events emitted from the instance
and display them accordingly to facilitate debugging.
The following methods broadcast a protocol event to all connected frontends.
The <code>params</code> passed to the methods can be optional, depending on the protocol.</p>
<pre><code class="language-js"><span class="hljs-comment">// The `Network.requestWillBeSent` event will be fired.</span>
inspector.<span class="hljs-property">Network</span>.<span class="hljs-title function_">requestWillBeSent</span>({
<span class="hljs-attr">requestId</span>: <span class="hljs-string">'request-id-1'</span>,
<span class="hljs-attr">timestamp</span>: <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>() / <span class="hljs-number">1000</span>,
<span class="hljs-attr">wallTime</span>: <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(),
<span class="hljs-attr">request</span>: {
<span class="hljs-attr">url</span>: <span class="hljs-string">'https://nodejs.org/en'</span>,
<span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
},
});</code> <button class="copy-button">copy</button></pre>
<h4><code>inspector.Network.requestWillBeSent([params])</code><span><a class="mark" href="#all_inspector_inspectornetworkrequestwillbesentparams" id="all_inspector_inspectornetworkrequestwillbesentparams">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_network_requestwillbesent_params"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>This feature is only available with the <code>--experimental-network-inspection</code> flag enabled.</p>
<p>Broadcasts the <code>Network.requestWillBeSent</code> event to connected frontends. This event indicates that
the application is about to send an HTTP request.</p>
<h4><code>inspector.Network.responseReceived([params])</code><span><a class="mark" href="#all_inspector_inspectornetworkresponsereceivedparams" id="all_inspector_inspectornetworkresponsereceivedparams">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_network_responsereceived_params"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>This feature is only available with the <code>--experimental-network-inspection</code> flag enabled.</p>
<p>Broadcasts the <code>Network.responseReceived</code> event to connected frontends. This event indicates that
HTTP response is available.</p>
<h4><code>inspector.Network.loadingFinished([params])</code><span><a class="mark" href="#all_inspector_inspectornetworkloadingfinishedparams" id="all_inspector_inspectornetworkloadingfinishedparams">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_network_loadingfinished_params"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>This feature is only available with the <code>--experimental-network-inspection</code> flag enabled.</p>
<p>Broadcasts the <code>Network.loadingFinished</code> event to connected frontends. This event indicates that
HTTP request has finished loading.</p>
<h4><code>inspector.Network.loadingFailed([params])</code><span><a class="mark" href="#all_inspector_inspectornetworkloadingfailedparams" id="all_inspector_inspectornetworkloadingfailedparams">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_network_loadingfailed_params"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>This feature is only available with the <code>--experimental-network-inspection</code> flag enabled.</p>
<p>Broadcasts the <code>Network.loadingFailed</code> event to connected frontends. This event indicates that
HTTP request has failed to load.</p>
</section><section><h3>Support of breakpoints<span><a class="mark" href="#all_inspector_support-of-breakpoints" id="all_inspector_support-of-breakpoints">#</a></span><a aria-hidden="true" class="legacy" id="inspector_support_of_breakpoints"></a></h3>
<p>The Chrome DevTools Protocol <a href="https://chromedevtools.github.io/devtools-protocol/v8/Debugger"><code>Debugger</code> domain</a> allows an
<code>inspector.Session</code> to attach to a program and set breakpoints to step through
the codes.</p>
<p>However, setting breakpoints with a same-thread <code>inspector.Session</code>, which is
connected by <a href="#all_inspector_sessionconnect"><code>session.connect()</code></a>, should be avoided as the program being
attached and paused is exactly the debugger itself. Instead, try connect to the
main thread by <a href="#all_inspector_sessionconnecttomainthread"><code>session.connectToMainThread()</code></a> and set breakpoints in a
worker thread, or connect with a <a href="debugger.html">Debugger</a> program over WebSocket
connection.</p></section>
</section>
<section><h2>Internationalization support<span><a class="mark" href="#all_intl_internationalization-support" id="all_intl_internationalization-support">#</a></span><a aria-hidden="true" class="legacy" id="intl_internationalization_support"></a></h2>
<p>Node.js has many features that make it easier to write internationalized
programs. Some of them are:</p>
<ul>
<li>Locale-sensitive or Unicode-aware functions in the <a href="https://tc39.github.io/ecma262/">ECMAScript Language
Specification</a>:
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase"><code>String.prototype.toLowerCase()</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase"><code>String.prototype.toUpperCase()</code></a></li>
</ul>
</li>
<li>All functionality described in the <a href="https://tc39.github.io/ecma402/">ECMAScript Internationalization API
Specification</a> (aka ECMA-402):
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl"><code>Intl</code></a> object</li>
<li>Locale-sensitive methods like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare"><code>String.prototype.localeCompare()</code></a> and
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString"><code>Date.prototype.toLocaleString()</code></a></li>
</ul>
</li>
<li>The <a href="#all_url_the-whatwg-url-api">WHATWG URL parser</a>'s <a href="https://en.wikipedia.org/wiki/Internationalized_domain_name">internationalized domain names</a> (IDNs) support</li>
<li><a href="#all_buffer_buffertranscodesource-fromenc-toenc"><code>require('node:buffer').transcode()</code></a></li>
<li>More accurate <a href="#all_repl_repl">REPL</a> line editing</li>
<li><a href="#all_util_class-utiltextdecoder"><code>require('node:util').TextDecoder</code></a></li>
<li><a href="https://github.com/tc39/proposal-regexp-unicode-property-escapes"><code>RegExp</code> Unicode Property Escapes</a></li>
</ul>
<p>Node.js and the underlying V8 engine use
<a href="http://site.icu-project.org/">International Components for Unicode (ICU)</a> to implement these features
in native C/C++ code. The full ICU data set is provided by Node.js by default.
However, due to the size of the ICU data file, several
options are provided for customizing the ICU data set either when
building or running Node.js.</p>
<section><h3>Options for building Node.js<span><a class="mark" href="#all_intl_options-for-building-nodejs" id="all_intl_options-for-building-nodejs">#</a></span><a aria-hidden="true" class="legacy" id="intl_options_for_building_node_js"></a></h3>
<p>To control how ICU is used in Node.js, four <code>configure</code> options are available
during compilation. Additional details on how to compile Node.js are documented
in <a href="https://github.com/nodejs/node/blob/HEAD/BUILDING.md">BUILDING.md</a>.</p>
<ul>
<li><code>--with-intl=none</code>/<code>--without-intl</code></li>
<li><code>--with-intl=system-icu</code></li>
<li><code>--with-intl=small-icu</code></li>
<li><code>--with-intl=full-icu</code> (default)</li>
</ul>
<p>An overview of available Node.js and JavaScript features for each <code>configure</code>
option:</p>
<table><thead><tr><th>Feature</th><th><code>none</code></th><th><code>system-icu</code></th><th><code>small-icu</code></th><th><code>full-icu</code></th></tr></thead><tbody><tr><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a></td><td>none (function is no-op)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><code>String.prototype.to*Case()</code></td><td>full</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl"><code>Intl</code></a></td><td>none (object does not exist)</td><td>partial/full (depends on OS)</td><td>partial (English-only)</td><td>full</td></tr><tr><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare"><code>String.prototype.localeCompare()</code></a></td><td>partial (not locale-aware)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><code>String.prototype.toLocale*Case()</code></td><td>partial (not locale-aware)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString"><code>Number.prototype.toLocaleString()</code></a></td><td>partial (not locale-aware)</td><td>partial/full (depends on OS)</td><td>partial (English-only)</td><td>full</td></tr><tr><td><code>Date.prototype.toLocale*String()</code></td><td>partial (not locale-aware)</td><td>partial/full (depends on OS)</td><td>partial (English-only)</td><td>full</td></tr><tr><td><a href="#all_url_legacy-url-api">Legacy URL Parser</a></td><td>partial (no IDN support)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="#all_url_the-whatwg-url-api">WHATWG URL Parser</a></td><td>partial (no IDN support)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="#all_buffer_buffertranscodesource-fromenc-toenc"><code>require('node:buffer').transcode()</code></a></td><td>none (function does not exist)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="#all_repl_repl">REPL</a></td><td>partial (inaccurate line editing)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="#all_util_class-utiltextdecoder"><code>require('node:util').TextDecoder</code></a></td><td>partial (basic encodings support)</td><td>partial/full (depends on OS)</td><td>partial (Unicode-only)</td><td>full</td></tr><tr><td><a href="https://github.com/tc39/proposal-regexp-unicode-property-escapes"><code>RegExp</code> Unicode Property Escapes</a></td><td>none (invalid <code>RegExp</code> error)</td><td>full</td><td>full</td><td>full</td></tr></tbody></table>
<p>The "(not locale-aware)" designation denotes that the function carries out its
operation just like the non-<code>Locale</code> version of the function, if one
exists. For example, under <code>none</code> mode, <code>Date.prototype.toLocaleString()</code>'s
operation is identical to that of <code>Date.prototype.toString()</code>.</p>
<h4>Disable all internationalization features (<code>none</code>)<span><a class="mark" href="#all_intl_disable-all-internationalization-features-none" id="all_intl_disable-all-internationalization-features-none">#</a></span><a aria-hidden="true" class="legacy" id="intl_disable_all_internationalization_features_none"></a></h4>
<p>If this option is chosen, ICU is disabled and most internationalization
features mentioned above will be <strong>unavailable</strong> in the resulting <code>node</code> binary.</p>
<h4>Build with a pre-installed ICU (<code>system-icu</code>)<span><a class="mark" href="#all_intl_build-with-a-pre-installed-icu-system-icu" id="all_intl_build-with-a-pre-installed-icu-system-icu">#</a></span><a aria-hidden="true" class="legacy" id="intl_build_with_a_pre_installed_icu_system_icu"></a></h4>
<p>Node.js can link against an ICU build already installed on the system. In fact,
most Linux distributions already come with ICU installed, and this option would
make it possible to reuse the same set of data used by other components in the
OS.</p>
<p>Functionalities that only require the ICU library itself, such as
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a> and the <a href="#all_url_the-whatwg-url-api">WHATWG URL parser</a>, are fully
supported under <code>system-icu</code>. Features that require ICU locale data in
addition, such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat"><code>Intl.DateTimeFormat</code></a> <em>may</em> be fully or partially
supported, depending on the completeness of the ICU data installed on the
system.</p>
<h4>Embed a limited set of ICU data (<code>small-icu</code>)<span><a class="mark" href="#all_intl_embed-a-limited-set-of-icu-data-small-icu" id="all_intl_embed-a-limited-set-of-icu-data-small-icu">#</a></span><a aria-hidden="true" class="legacy" id="intl_embed_a_limited_set_of_icu_data_small_icu"></a></h4>
<p>This option makes the resulting binary link against the ICU library statically,
and includes a subset of ICU data (typically only the English locale) within
the <code>node</code> executable.</p>
<p>Functionalities that only require the ICU library itself, such as
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a> and the <a href="#all_url_the-whatwg-url-api">WHATWG URL parser</a>, are fully
supported under <code>small-icu</code>. Features that require ICU locale data in addition,
such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat"><code>Intl.DateTimeFormat</code></a>, generally only work with the English locale:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> january = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>(<span class="hljs-number">9e8</span>);
<span class="hljs-keyword">const</span> english = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Intl</span>.<span class="hljs-title class_">DateTimeFormat</span>(<span class="hljs-string">'en'</span>, { <span class="hljs-attr">month</span>: <span class="hljs-string">'long'</span> });
<span class="hljs-keyword">const</span> spanish = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Intl</span>.<span class="hljs-title class_">DateTimeFormat</span>(<span class="hljs-string">'es'</span>, { <span class="hljs-attr">month</span>: <span class="hljs-string">'long'</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(english.<span class="hljs-title function_">format</span>(january));
<span class="hljs-comment">// Prints "January"</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(spanish.<span class="hljs-title function_">format</span>(january));
<span class="hljs-comment">// Prints either "M01" or "January" on small-icu, depending on the user’s default locale</span>
<span class="hljs-comment">// Should print "enero"</span></code> <button class="copy-button">copy</button></pre>
<p>This mode provides a balance between features and binary size.</p>
<h5>Providing ICU data at runtime<span><a class="mark" href="#all_intl_providing-icu-data-at-runtime" id="all_intl_providing-icu-data-at-runtime">#</a></span><a aria-hidden="true" class="legacy" id="intl_providing_icu_data_at_runtime"></a></h5>
<p>If the <code>small-icu</code> option is used, one can still provide additional locale data
at runtime so that the JS methods would work for all ICU locales. Assuming the
data file is stored at <code>/runtime/directory/with/dat/file</code>, it can be made
available to ICU through either:</p>
<ul>
<li>
<p>The <code>--with-icu-default-data-dir</code> configure option:</p>
<pre><code class="language-bash">./configure --with-icu-default-data-dir=/runtime/directory/with/dat/file --with-intl=small-icu</code> <button class="copy-button">copy</button></pre>
<p>This only embeds the default data directory path into the binary.
The actual data file is going to be loaded at runtime from this directory
path.</p>
</li>
<li>
<p>The <a href="#all_cli_node_icu_datafile"><code>NODE_ICU_DATA</code></a> environment variable:</p>
<pre><code class="language-bash"><span class="hljs-built_in">env</span> NODE_ICU_DATA=/runtime/directory/with/dat/file node</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>The <a href="#all_cli_--icu-data-dirfile"><code>--icu-data-dir</code></a> CLI parameter:</p>
<pre><code class="language-bash">node --icu-data-dir=/runtime/directory/with/dat/file</code> <button class="copy-button">copy</button></pre>
</li>
</ul>
<p>When more than one of them is specified, the <code>--icu-data-dir</code> CLI parameter has
the highest precedence, then the <code>NODE_ICU_DATA</code> environment variable, then
the <code>--with-icu-default-data-dir</code> configure option.</p>
<p>ICU is able to automatically find and load a variety of data formats, but the
data must be appropriate for the ICU version, and the file correctly named.
The most common name for the data file is <code>icudtX[bl].dat</code>, where <code>X</code> denotes
the intended ICU version, and <code>b</code> or <code>l</code> indicates the system's endianness.
Node.js would fail to load if the expected data file cannot be read from the
specified directory. The name of the data file corresponding to the current
Node.js version can be computed with:</p>
<pre><code class="language-js"><span class="hljs-string">`icudt<span class="hljs-subst">${process.versions.icu.split(<span class="hljs-string">'.'</span>)[<span class="hljs-number">0</span>]}</span><span class="hljs-subst">${os.endianness()[<span class="hljs-number">0</span>].toLowerCase()}</span>.dat`</span>;</code> <button class="copy-button">copy</button></pre>
<p>Check <a href="http://userguide.icu-project.org/icudata">"ICU Data"</a> article in the ICU User Guide for other supported formats
and more details on ICU data in general.</p>
<p>The <a href="https://www.npmjs.com/package/full-icu">full-icu</a> npm module can greatly simplify ICU data installation by
detecting the ICU version of the running <code>node</code> executable and downloading the
appropriate data file. After installing the module through <code>npm i full-icu</code>,
the data file will be available at <code>./node_modules/full-icu</code>. This path can be
then passed either to <code>NODE_ICU_DATA</code> or <code>--icu-data-dir</code> as shown above to
enable full <code>Intl</code> support.</p>
<h4>Embed the entire ICU (<code>full-icu</code>)<span><a class="mark" href="#all_intl_embed-the-entire-icu-full-icu" id="all_intl_embed-the-entire-icu-full-icu">#</a></span><a aria-hidden="true" class="legacy" id="intl_embed_the_entire_icu_full_icu"></a></h4>
<p>This option makes the resulting binary link against ICU statically and include
a full set of ICU data. A binary created this way has no further external
dependencies and supports all locales, but might be rather large. This is
the default behavior if no <code>--with-intl</code> flag is passed. The official binaries
are also built in this mode.</p>
</section><section><h3>Detecting internationalization support<span><a class="mark" href="#all_intl_detecting-internationalization-support" id="all_intl_detecting-internationalization-support">#</a></span><a aria-hidden="true" class="legacy" id="intl_detecting_internationalization_support"></a></h3>
<p>To verify that ICU is enabled at all (<code>system-icu</code>, <code>small-icu</code>, or
<code>full-icu</code>), simply checking the existence of <code>Intl</code> should suffice:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> hasICU = <span class="hljs-keyword">typeof</span> <span class="hljs-title class_">Intl</span> === <span class="hljs-string">'object'</span>;</code> <button class="copy-button">copy</button></pre>
<p>Alternatively, checking for <code>process.versions.icu</code>, a property defined only
when ICU is enabled, works too:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> hasICU = <span class="hljs-keyword">typeof</span> process.<span class="hljs-property">versions</span>.<span class="hljs-property">icu</span> === <span class="hljs-string">'string'</span>;</code> <button class="copy-button">copy</button></pre>
<p>To check for support for a non-English locale (i.e. <code>full-icu</code> or
<code>system-icu</code>), <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat"><code>Intl.DateTimeFormat</code></a> can be a good distinguishing factor:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> hasFullICU = (<span class="hljs-function">() =></span> {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> january = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>(<span class="hljs-number">9e8</span>);
<span class="hljs-keyword">const</span> spanish = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Intl</span>.<span class="hljs-title class_">DateTimeFormat</span>(<span class="hljs-string">'es'</span>, { <span class="hljs-attr">month</span>: <span class="hljs-string">'long'</span> });
<span class="hljs-keyword">return</span> spanish.<span class="hljs-title function_">format</span>(january) === <span class="hljs-string">'enero'</span>;
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
}
})();</code> <button class="copy-button">copy</button></pre>
<p>For more verbose tests for <code>Intl</code> support, the following resources may be found
to be helpful:</p>
<ul>
<li><a href="https://github.com/srl295/btest402">btest402</a>: Generally used to check whether Node.js with <code>Intl</code> support is
built correctly.</li>
<li><a href="https://github.com/tc39/test262/tree/HEAD/test/intl402">Test262</a>: ECMAScript's official conformance test suite includes a section
dedicated to ECMA-402.</li>
</ul></section>
</section>
<section><h2>Modules: CommonJS modules<span><a class="mark" href="#all_modules_modules-commonjs-modules" id="all_modules_modules-commonjs-modules">#</a></span><a aria-hidden="true" class="legacy" id="modules_modules_commonjs_modules"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>CommonJS modules are the original way to package JavaScript code for Node.js.
Node.js also supports the <a href="esm.html">ECMAScript modules</a> standard used by browsers
and other JavaScript runtimes.</p>
<p>In Node.js, each file is treated as a separate module. For
example, consider a file named <code>foo.js</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> circle = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./circle.js'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The area of a circle of radius 4 is <span class="hljs-subst">${circle.area(<span class="hljs-number">4</span>)}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<p>On the first line, <code>foo.js</code> loads the module <code>circle.js</code> that is in the same
directory as <code>foo.js</code>.</p>
<p>Here are the contents of <code>circle.js</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-variable constant_">PI</span> } = <span class="hljs-title class_">Math</span>;
<span class="hljs-built_in">exports</span>.<span class="hljs-property">area</span> = <span class="hljs-function">(<span class="hljs-params">r</span>) =></span> <span class="hljs-variable constant_">PI</span> * r ** <span class="hljs-number">2</span>;
<span class="hljs-built_in">exports</span>.<span class="hljs-property">circumference</span> = <span class="hljs-function">(<span class="hljs-params">r</span>) =></span> <span class="hljs-number">2</span> * <span class="hljs-variable constant_">PI</span> * r;</code> <button class="copy-button">copy</button></pre>
<p>The module <code>circle.js</code> has exported the functions <code>area()</code> and
<code>circumference()</code>. Functions and objects are added to the root of a module
by specifying additional properties on the special <code>exports</code> object.</p>
<p>Variables local to the module will be private, because the module is wrapped
in a function by Node.js (see <a href="#all_modules_the-module-wrapper">module wrapper</a>).
In this example, the variable <code>PI</code> is private to <code>circle.js</code>.</p>
<p>The <code>module.exports</code> property can be assigned a new value (such as a function
or object).</p>
<p>In the following code, <code>bar.js</code> makes use of the <code>square</code> module, which exports
a Square class:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">Square</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./square.js'</span>);
<span class="hljs-keyword">const</span> mySquare = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Square</span>(<span class="hljs-number">2</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The area of mySquare is <span class="hljs-subst">${mySquare.area()}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<p>The <code>square</code> module is defined in <code>square.js</code>:</p>
<pre><code class="language-js"><span class="hljs-comment">// Assigning to exports will not modify module, must use module.exports</span>
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">class</span> <span class="hljs-title class_">Square</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">width</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">width</span> = width;
}
<span class="hljs-title function_">area</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">width</span> ** <span class="hljs-number">2</span>;
}
};</code> <button class="copy-button">copy</button></pre>
<p>The CommonJS module system is implemented in the <a href="module.html"><code>module</code> core module</a>.</p>
<section><h3>Enabling<span><a class="mark" href="#all_modules_enabling" id="all_modules_enabling">#</a></span><a aria-hidden="true" class="legacy" id="modules_enabling"></a></h3>
<p>Node.js has two module systems: CommonJS modules and <a href="esm.html">ECMAScript modules</a>.</p>
<p>By default, Node.js will treat the following as CommonJS modules:</p>
<ul>
<li>
<p>Files with a <code>.cjs</code> extension;</p>
</li>
<li>
<p>Files with a <code>.js</code> extension when the nearest parent <code>package.json</code> file
contains a top-level field <a href="#all_packages_type"><code>"type"</code></a> with a value of <code>"commonjs"</code>.</p>
</li>
<li>
<p>Files with a <code>.js</code> extension or without an extension, when the nearest parent
<code>package.json</code> file doesn't contain a top-level field <a href="#all_packages_type"><code>"type"</code></a> or there is
no <code>package.json</code> in any parent folder; unless the file contains syntax that
errors unless it is evaluated as an ES module. Package authors should include
the <a href="#all_packages_type"><code>"type"</code></a> field, even in packages where all sources are CommonJS. Being
explicit about the <code>type</code> of the package will make things easier for build
tools and loaders to determine how the files in the package should be
interpreted.</p>
</li>
<li>
<p>Files with an extension that is not <code>.mjs</code>, <code>.cjs</code>, <code>.json</code>, <code>.node</code>, or <code>.js</code>
(when the nearest parent <code>package.json</code> file contains a top-level field
<a href="#all_packages_type"><code>"type"</code></a> with a value of <code>"module"</code>, those files will be recognized as
CommonJS modules only if they are being included via <code>require()</code>, not when
used as the command-line entry point of the program).</p>
</li>
</ul>
<p>See <a href="#all_packages_determining-module-system">Determining module system</a> for more details.</p>
<p>Calling <code>require()</code> always use the CommonJS module loader. Calling <code>import()</code>
always use the ECMAScript module loader.</p>
</section><section><h3>Accessing the main module<span><a class="mark" href="#all_modules_accessing-the-main-module" id="all_modules_accessing-the-main-module">#</a></span><a aria-hidden="true" class="legacy" id="modules_accessing_the_main_module"></a></h3>
<p>When a file is run directly from Node.js, <code>require.main</code> is set to its
<code>module</code>. That means that it is possible to determine whether a file has been
run directly by testing <code>require.main === module</code>.</p>
<p>For a file <code>foo.js</code>, this will be <code>true</code> if run via <code>node foo.js</code>, but
<code>false</code> if run by <code>require('./foo')</code>.</p>
<p>When the entry point is not a CommonJS module, <code>require.main</code> is <code>undefined</code>,
and the main module is out of reach.</p>
</section><section><h3>Package manager tips<span><a class="mark" href="#all_modules_package-manager-tips" id="all_modules_package-manager-tips">#</a></span><a aria-hidden="true" class="legacy" id="modules_package_manager_tips"></a></h3>
<p>The semantics of the Node.js <code>require()</code> function were designed to be general
enough to support reasonable directory structures. Package manager programs
such as <code>dpkg</code>, <code>rpm</code>, and <code>npm</code> will hopefully find it possible to build
native packages from Node.js modules without modification.</p>
<p>In the following, we give a suggested directory structure that could work:</p>
<p>Let's say that we wanted to have the folder at
<code>/usr/lib/node/<some-package>/<some-version></code> hold the contents of a
specific version of a package.</p>
<p>Packages can depend on one another. In order to install package <code>foo</code>, it
may be necessary to install a specific version of package <code>bar</code>. The <code>bar</code>
package may itself have dependencies, and in some cases, these may even collide
or form cyclic dependencies.</p>
<p>Because Node.js looks up the <code>realpath</code> of any modules it loads (that is, it
resolves symlinks) and then <a href="#all_modules_loading-from-node_modules-folders">looks for their dependencies in <code>node_modules</code> folders</a>,
this situation can be resolved with the following architecture:</p>
<ul>
<li><code>/usr/lib/node/foo/1.2.3/</code>: Contents of the <code>foo</code> package, version 1.2.3.</li>
<li><code>/usr/lib/node/bar/4.3.2/</code>: Contents of the <code>bar</code> package that <code>foo</code> depends
on.</li>
<li><code>/usr/lib/node/foo/1.2.3/node_modules/bar</code>: Symbolic link to
<code>/usr/lib/node/bar/4.3.2/</code>.</li>
<li><code>/usr/lib/node/bar/4.3.2/node_modules/*</code>: Symbolic links to the packages that
<code>bar</code> depends on.</li>
</ul>
<p>Thus, even if a cycle is encountered, or if there are dependency
conflicts, every module will be able to get a version of its dependency
that it can use.</p>
<p>When the code in the <code>foo</code> package does <code>require('bar')</code>, it will get the
version that is symlinked into <code>/usr/lib/node/foo/1.2.3/node_modules/bar</code>.
Then, when the code in the <code>bar</code> package calls <code>require('quux')</code>, it'll get
the version that is symlinked into
<code>/usr/lib/node/bar/4.3.2/node_modules/quux</code>.</p>
<p>Furthermore, to make the module lookup process even more optimal, rather
than putting packages directly in <code>/usr/lib/node</code>, we could put them in
<code>/usr/lib/node_modules/<name>/<version></code>. Then Node.js will not bother
looking for missing dependencies in <code>/usr/node_modules</code> or <code>/node_modules</code>.</p>
<p>In order to make modules available to the Node.js REPL, it might be useful to
also add the <code>/usr/lib/node_modules</code> folder to the <code>$NODE_PATH</code> environment
variable. Since the module lookups using <code>node_modules</code> folders are all
relative, and based on the real path of the files making the calls to
<code>require()</code>, the packages themselves can be anywhere.</p>
</section><section><h3>Loading ECMAScript modules using <code>require()</code><span><a class="mark" href="#all_modules_loading-ecmascript-modules-using-require" id="all_modules_loading-ecmascript-modules-using-require">#</a></span><a aria-hidden="true" class="legacy" id="modules_loading_ecmascript_modules_using_require"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.19.0</td>
<td><p>This feature no longer emits an experimental warning by default, though the warning can still be emitted by --trace-require-module.</p></td></tr>
<tr><td>v20.19.0</td>
<td><p>This feature is no longer behind the <code>--experimental-require-module</code> CLI flag.</p></td></tr>
<tr><td>v20.19.0</td>
<td><p>Support <code>'module.exports'</code> interop export in <code>require(esm)</code>.</p></td></tr>
<tr><td>v22.0.0, v20.17.0</td>
<td><p><span>Added in: v22.0.0, v20.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<p>The <code>.mjs</code> extension is reserved for <a href="esm.html">ECMAScript Modules</a>.
See <a href="#all_packages_determining-module-system">Determining module system</a> section for more info
regarding which files are parsed as ECMAScript modules.</p>
<p><code>require()</code> only supports loading ECMAScript modules that meet the following requirements:</p>
<ul>
<li>The module is fully synchronous (contains no top-level <code>await</code>); and</li>
<li>One of these conditions are met:
<ol>
<li>The file has a <code>.mjs</code> extension.</li>
<li>The file has a <code>.js</code> extension, and the closest <code>package.json</code> contains <code>"type": "module"</code></li>
<li>The file has a <code>.js</code> extension, the closest <code>package.json</code> does not contain
<code>"type": "commonjs"</code>, and the module contains ES module syntax.</li>
</ol>
</li>
</ul>
<p>If the ES Module being loaded meet the requirements, <code>require()</code> can load it and
return the module namespace object. In this case it is similar to dynamic
<code>import()</code> but is run synchronously and returns the name space object
directly.</p>
<p>With the following ES Modules:</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// distance.mjs</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">distance</span>(<span class="hljs-params">a, b</span>) { <span class="hljs-keyword">return</span> (b.<span class="hljs-property">x</span> - a.<span class="hljs-property">x</span>) ** <span class="hljs-number">2</span> + (b.<span class="hljs-property">y</span> - a.<span class="hljs-property">y</span>) ** <span class="hljs-number">2</span>; }</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js mjs"><span class="hljs-comment">// point.mjs</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Point</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">x, y</span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-property">x</span> = x; <span class="hljs-variable language_">this</span>.<span class="hljs-property">y</span> = y; }
}</code> <button class="copy-button">copy</button></pre>
<p>A CommonJS module can load them with <code>require()</code>:</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> distance = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./distance.mjs'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(distance);
<span class="hljs-comment">// [Module: null prototype] {</span>
<span class="hljs-comment">// distance: [Function: distance]</span>
<span class="hljs-comment">// }</span>
<span class="hljs-keyword">const</span> point = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./point.mjs'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(point);
<span class="hljs-comment">// [Module: null prototype] {</span>
<span class="hljs-comment">// default: [class Point],</span>
<span class="hljs-comment">// __esModule: true,</span>
<span class="hljs-comment">// }</span></code> <button class="copy-button">copy</button></pre>
<p>For interoperability with existing tools that convert ES Modules into CommonJS,
which could then load real ES Modules through <code>require()</code>, the returned namespace
would contain a <code>__esModule: true</code> property if it has a <code>default</code> export so that
consuming code generated by tools can recognize the default exports in real
ES Modules. If the namespace already defines <code>__esModule</code>, this would not be added.
This property is experimental and can change in the future. It should only be used
by tools converting ES modules into CommonJS modules, following existing ecosystem
conventions. Code authored directly in CommonJS should avoid depending on it.</p>
<p>When a ES Module contains both named exports and a default export, the result returned by <code>require()</code>
is the module namespace object, which places the default export in the <code>.default</code> property, similar to
the results returned by <code>import()</code>.
To customize what should be returned by <code>require(esm)</code> directly, the ES Module can export the
desired value using the string name <code>"module.exports"</code>.</p>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js mjs"><span class="hljs-comment">// point.mjs</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Point</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">x, y</span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-property">x</span> = x; <span class="hljs-variable language_">this</span>.<span class="hljs-property">y</span> = y; }
}
<span class="hljs-comment">// `distance` is lost to CommonJS consumers of this module, unless it's</span>
<span class="hljs-comment">// added to `Point` as a static property.</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">distance</span>(<span class="hljs-params">a, b</span>) { <span class="hljs-keyword">return</span> (b.<span class="hljs-property">x</span> - a.<span class="hljs-property">x</span>) ** <span class="hljs-number">2</span> + (b.<span class="hljs-property">y</span> - a.<span class="hljs-property">y</span>) ** <span class="hljs-number">2</span>; }
<span class="hljs-keyword">export</span> { <span class="hljs-title class_">Point</span> <span class="hljs-keyword">as</span> <span class="hljs-string">'module.exports'</span> }</code> <button class="copy-button">copy</button></pre>
<!-- eslint-disable node-core/no-duplicate-requires -->
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">Point</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./point.mjs'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Point</span>); <span class="hljs-comment">// [class Point]</span>
<span class="hljs-comment">// Named exports are lost when 'module.exports' is used</span>
<span class="hljs-keyword">const</span> { distance } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./point.mjs'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(distance); <span class="hljs-comment">// undefined</span></code> <button class="copy-button">copy</button></pre>
<p>Notice in the example above, when the <code>module.exports</code> export name is used, named exports
will be lost to CommonJS consumers. To allow CommonJS consumers to continue accessing
named exports, the module can make sure that the default export is an object with the
named exports attached to it as properties. For example with the example above,
<code>distance</code> can be attached to the default export, the <code>Point</code> class, as a static method.</p>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">distance</span>(<span class="hljs-params">a, b</span>) { <span class="hljs-keyword">return</span> (b.<span class="hljs-property">x</span> - a.<span class="hljs-property">x</span>) ** <span class="hljs-number">2</span> + (b.<span class="hljs-property">y</span> - a.<span class="hljs-property">y</span>) ** <span class="hljs-number">2</span>; }
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Point</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">x, y</span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-property">x</span> = x; <span class="hljs-variable language_">this</span>.<span class="hljs-property">y</span> = y; }
<span class="hljs-keyword">static</span> distance = distance;
}
<span class="hljs-keyword">export</span> { <span class="hljs-title class_">Point</span> <span class="hljs-keyword">as</span> <span class="hljs-string">'module.exports'</span> }</code> <button class="copy-button">copy</button></pre>
<!-- eslint-disable node-core/no-duplicate-requires -->
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">Point</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./point.mjs'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Point</span>); <span class="hljs-comment">// [class Point]</span>
<span class="hljs-keyword">const</span> { distance } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./point.mjs'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(distance); <span class="hljs-comment">// [Function: distance]</span></code> <button class="copy-button">copy</button></pre>
<p>If the module being <code>require()</code>'d contains top-level <code>await</code>, or the module
graph it <code>import</code>s contains top-level <code>await</code>,
<a href="#all_errors_err_require_async_module"><code>ERR_REQUIRE_ASYNC_MODULE</code></a> will be thrown. In this case, users should
load the asynchronous module using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import"><code>import()</code></a>.</p>
<p>If <code>--experimental-print-required-tla</code> is enabled, instead of throwing
<code>ERR_REQUIRE_ASYNC_MODULE</code> before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.</p>
<p>Support for loading ES modules using <code>require()</code> is currently
experimental and can be disabled using <code>--no-experimental-require-module</code>.
To print where this feature is used, use <a href="#all_cli_--trace-require-modulemode"><code>--trace-require-module</code></a>.</p>
<p>This feature can be detected by checking if
<a href="#all_process_processfeaturesrequire_module"><code>process.features.require_module</code></a> is <code>true</code>.</p>
</section><section><h3>All together<span><a class="mark" href="#all_modules_all-together" id="all_modules_all-together">#</a></span><a aria-hidden="true" class="legacy" id="modules_all_together"></a></h3>
<p>To get the exact filename that will be loaded when <code>require()</code> is called, use
the <code>require.resolve()</code> function.</p>
<p>Putting together all of the above, here is the high-level algorithm
in pseudocode of what <code>require()</code> does:</p>
<pre><code class="language-text">require(X) from module at path Y
1. If X is a core module,
a. return the core module
b. STOP
2. If X begins with '/'
a. set Y to be the file system root
3. If X begins with './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
c. THROW "not found"
4. If X begins with '#'
a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))
5. LOAD_PACKAGE_SELF(X, dirname(Y))
6. LOAD_NODE_MODULES(X, dirname(Y))
7. THROW "not found"
MAYBE_DETECT_AND_LOAD(X)
1. If X parses as a CommonJS module, load X as a CommonJS module. STOP.
2. Else, if the source code of X can be parsed as ECMAScript module using
<a href="esm.md#resolver-algorithm-specification">DETECT_MODULE_SYNTAX defined in
the ESM resolver</a>,
a. Load X as an ECMAScript module. STOP.
3. THROW the SyntaxError from attempting to parse X as CommonJS in 1. STOP.
LOAD_AS_FILE(X)
1. If X is a file, load X as its file extension format. STOP
2. If X.js is a file,
a. Find the closest package scope SCOPE to X.
b. If no scope was found
1. MAYBE_DETECT_AND_LOAD(X.js)
c. If the SCOPE/package.json contains "type" field,
1. If the "type" field is "module", load X.js as an ECMAScript module. STOP.
2. If the "type" field is "commonjs", load X.js as an CommonJS module. STOP.
d. MAYBE_DETECT_AND_LOAD(X.js)
3. If X.json is a file, load X.json to a JavaScript Object. STOP
4. If X.node is a file, load X.node as binary addon. STOP
LOAD_INDEX(X)
1. If X/index.js is a file
a. Find the closest package scope SCOPE to X.
b. If no scope was found, load X/index.js as a CommonJS module. STOP.
c. If the SCOPE/package.json contains "type" field,
1. If the "type" field is "module", load X/index.js as an ECMAScript module. STOP.
2. Else, load X/index.js as an CommonJS module. STOP.
2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
3. If X/index.node is a file, load X/index.node as binary addon. STOP
LOAD_AS_DIRECTORY(X)
1. If X/package.json is a file,
a. Parse X/package.json, and look for "main" field.
b. If "main" is a falsy value, GOTO 2.
c. let M = X + (json main field)
d. LOAD_AS_FILE(M)
e. LOAD_INDEX(M)
f. LOAD_INDEX(X) DEPRECATED
g. THROW "not found"
2. LOAD_INDEX(X)
LOAD_NODE_MODULES(X, START)
1. let DIRS = NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
a. LOAD_PACKAGE_EXPORTS(X, DIR)
b. LOAD_AS_FILE(DIR/X)
c. LOAD_AS_DIRECTORY(DIR/X)
NODE_MODULES_PATHS(START)
1. let PARTS = path split(START)
2. let I = count of PARTS - 1
3. let DIRS = []
4. while I >= 0,
a. if PARTS[I] = "node_modules", GOTO d.
b. DIR = path join(PARTS[0 .. I] + "node_modules")
c. DIRS = DIR + DIRS
d. let I = I - 1
5. return DIRS + GLOBAL_FOLDERS
LOAD_PACKAGE_IMPORTS(X, DIR)
1. Find the closest package scope SCOPE to DIR.
2. If no scope was found, return.
3. If the SCOPE/package.json "imports" is null or undefined, return.
4. If `--experimental-require-module` is enabled
a. let CONDITIONS = ["node", "require", "module-sync"]
b. Else, let CONDITIONS = ["node", "require"]
5. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),
CONDITIONS) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.
6. RESOLVE_ESM_MATCH(MATCH).
LOAD_PACKAGE_EXPORTS(X, DIR)
1. Try to interpret X as a combination of NAME and SUBPATH where the name
may have a @scope/ prefix and the subpath begins with a slash (`/`).
2. If X does not match this pattern or DIR/NAME/package.json is not a file,
return.
3. Parse DIR/NAME/package.json, and look for "exports" field.
4. If "exports" is null or undefined, return.
5. If `--experimental-require-module` is enabled
a. let CONDITIONS = ["node", "require", "module-sync"]
b. Else, let CONDITIONS = ["node", "require"]
6. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH,
`package.json` "exports", CONDITIONS) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.
7. RESOLVE_ESM_MATCH(MATCH)
LOAD_PACKAGE_SELF(X, DIR)
1. Find the closest package scope SCOPE to DIR.
2. If no scope was found, return.
3. If the SCOPE/package.json "exports" is null or undefined, return.
4. If the SCOPE/package.json "name" is not the first segment of X, return.
5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),
"." + X.slice("name".length), `package.json` "exports", ["node", "require"])
<a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.
6. RESOLVE_ESM_MATCH(MATCH)
RESOLVE_ESM_MATCH(MATCH)
1. let RESOLVED_PATH = fileURLToPath(MATCH)
2. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension
format. STOP
3. THROW "not found"</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Caching<span><a class="mark" href="#all_modules_caching" id="all_modules_caching">#</a></span><a aria-hidden="true" class="legacy" id="modules_caching"></a></h3>
<p>Modules are cached after the first time they are loaded. This means (among other
things) that every call to <code>require('foo')</code> will get exactly the same object
returned, if it would resolve to the same file.</p>
<p>Provided <code>require.cache</code> is not modified, multiple calls to <code>require('foo')</code>
will not cause the module code to be executed multiple times. This is an
important feature. With it, "partially done" objects can be returned, thus
allowing transitive dependencies to be loaded even when they would cause cycles.</p>
<p>To have a module execute code multiple times, export a function, and call that
function.</p>
<h4>Module caching caveats<span><a class="mark" href="#all_modules_module-caching-caveats" id="all_modules_module-caching-caveats">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_caching_caveats"></a></h4>
<p>Modules are cached based on their resolved filename. Since modules may resolve
to a different filename based on the location of the calling module (loading
from <code>node_modules</code> folders), it is not a <em>guarantee</em> that <code>require('foo')</code> will
always return the exact same object, if it would resolve to different files.</p>
<p>Additionally, on case-insensitive file systems or operating systems, different
resolved filenames can point to the same file, but the cache will still treat
them as different modules and will reload the file multiple times. For example,
<code>require('./foo')</code> and <code>require('./FOO')</code> return two different objects,
irrespective of whether or not <code>./foo</code> and <code>./FOO</code> are the same file.</p>
</section><section><h3>Built-in modules<span><a class="mark" href="#all_modules_built-in-modules" id="all_modules_built-in-modules">#</a></span><a aria-hidden="true" class="legacy" id="modules_built_in_modules"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0, v14.18.0</td>
<td><p>Added <code>node:</code> import support to <code>require(...)</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Node.js has several modules compiled into the binary. These modules are
described in greater detail elsewhere in this documentation.</p>
<p>The built-in modules are defined within the Node.js source and are located in the
<code>lib/</code> folder.</p>
<p>Built-in modules can be identified using the <code>node:</code> prefix, in which case
it bypasses the <code>require</code> cache. For instance, <code>require('node:http')</code> will
always return the built in HTTP module, even if there is <code>require.cache</code> entry
by that name.</p>
<p>Some built-in modules are always preferentially loaded if their identifier is
passed to <code>require()</code>. For instance, <code>require('http')</code> will always
return the built-in HTTP module, even if there is a file by that name. The list
of built-in modules that can be loaded without using the <code>node:</code> prefix is exposed
as <a href="#all_module_modulebuiltinmodules"><code>module.builtinModules</code></a>.</p>
<h4>Built-in modules with mandatory <code>node:</code> prefix<span><a class="mark" href="#all_modules_built-in-modules-with-mandatory-node-prefix" id="all_modules_built-in-modules-with-mandatory-node-prefix">#</a></span><a aria-hidden="true" class="legacy" id="modules_built_in_modules_with_mandatory_node_prefix"></a></h4>
<p>When being loaded by <code>require()</code>, some built-in modules must be requested with the
<code>node:</code> prefix. This requirement exists to prevent newly introduced built-in
modules from having a conflict with user land packages that already have
taken the name. Currently the built-in modules that requires the <code>node:</code> prefix are:</p>
<ul>
<li><a href="#all_single-executable-applications_single-executable-application-api"><code>node:sea</code></a></li>
<li><a href="test.html"><code>node:test</code></a></li>
<li><a href="#all_test_test-reporters"><code>node:test/reporters</code></a></li>
</ul>
</section><section><h3>Cycles<span><a class="mark" href="#all_modules_cycles" id="all_modules_cycles">#</a></span><a aria-hidden="true" class="legacy" id="modules_cycles"></a></h3>
<p>When there are circular <code>require()</code> calls, a module might not have finished
executing when it is returned.</p>
<p>Consider this situation:</p>
<p><code>a.js</code>:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a starting'</span>);
<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">const</span> b = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./b.js'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'in a, b.done = %j'</span>, b.<span class="hljs-property">done</span>);
<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">true</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a done'</span>);</code> <button class="copy-button">copy</button></pre>
<p><code>b.js</code>:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b starting'</span>);
<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">const</span> a = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./a.js'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'in b, a.done = %j'</span>, a.<span class="hljs-property">done</span>);
<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">true</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b done'</span>);</code> <button class="copy-button">copy</button></pre>
<p><code>main.js</code>:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'main starting'</span>);
<span class="hljs-keyword">const</span> a = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./a.js'</span>);
<span class="hljs-keyword">const</span> b = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./b.js'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'in main, a.done = %j, b.done = %j'</span>, a.<span class="hljs-property">done</span>, b.<span class="hljs-property">done</span>);</code> <button class="copy-button">copy</button></pre>
<p>When <code>main.js</code> loads <code>a.js</code>, then <code>a.js</code> in turn loads <code>b.js</code>. At that
point, <code>b.js</code> tries to load <code>a.js</code>. In order to prevent an infinite
loop, an <strong>unfinished copy</strong> of the <code>a.js</code> exports object is returned to the
<code>b.js</code> module. <code>b.js</code> then finishes loading, and its <code>exports</code> object is
provided to the <code>a.js</code> module.</p>
<p>By the time <code>main.js</code> has loaded both modules, they're both finished.
The output of this program would thus be:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node main.js</span>
main starting
a starting
b starting
in b, a.done = false
b done
in a, b.done = true
a done
in main, a.done = true, b.done = true</code> <button class="copy-button">copy</button></pre>
<p>Careful planning is required to allow cyclic module dependencies to work
correctly within an application.</p>
</section><section><h3>File modules<span><a class="mark" href="#all_modules_file-modules" id="all_modules_file-modules">#</a></span><a aria-hidden="true" class="legacy" id="modules_file_modules"></a></h3>
<p>If the exact filename is not found, then Node.js will attempt to load the
required filename with the added extensions: <code>.js</code>, <code>.json</code>, and finally
<code>.node</code>. When loading a file that has a different extension (e.g. <code>.cjs</code>), its
full name must be passed to <code>require()</code>, including its file extension (e.g.
<code>require('./file.cjs')</code>).</p>
<p><code>.json</code> files are parsed as JSON text files, <code>.node</code> files are interpreted as
compiled addon modules loaded with <code>process.dlopen()</code>. Files using any other
extension (or no extension at all) are parsed as JavaScript text files. Refer to
the <a href="#all_packages_determining-module-system">Determining module system</a> section to understand what parse goal will be
used.</p>
<p>A required module prefixed with <code>'/'</code> is an absolute path to the file. For
example, <code>require('/home/marco/foo.js')</code> will load the file at
<code>/home/marco/foo.js</code>.</p>
<p>A required module prefixed with <code>'./'</code> is relative to the file calling
<code>require()</code>. That is, <code>circle.js</code> must be in the same directory as <code>foo.js</code> for
<code>require('./circle')</code> to find it.</p>
<p>Without a leading <code>'/'</code>, <code>'./'</code>, or <code>'../'</code> to indicate a file, the module must
either be a core module or is loaded from a <code>node_modules</code> folder.</p>
<p>If the given path does not exist, <code>require()</code> will throw a
<a href="#all_errors_module_not_found"><code>MODULE_NOT_FOUND</code></a> error.</p>
</section><section><h3>Folders as modules<span><a class="mark" href="#all_modules_folders-as-modules" id="all_modules_folders-as-modules">#</a></span><a aria-hidden="true" class="legacy" id="modules_folders_as_modules"></a></h3>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_packages_subpath-exports">subpath exports</a> or <a href="#all_packages_subpath-imports">subpath imports</a> instead.</div><p></p>
<p>There are three ways in which a folder may be passed to <code>require()</code> as
an argument.</p>
<p>The first is to create a <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file in the root of the folder,
which specifies a <code>main</code> module. An example <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file might
look like this:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span> <span class="hljs-attr">"name"</span> <span class="hljs-punctuation">:</span> <span class="hljs-string">"some-library"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"main"</span> <span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/some-library.js"</span> <span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>If this was in a folder at <code>./some-library</code>, then
<code>require('./some-library')</code> would attempt to load
<code>./some-library/lib/some-library.js</code>.</p>
<p>If there is no <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file present in the directory, or if the
<a href="#all_packages_main"><code>"main"</code></a> entry is missing or cannot be resolved, then Node.js
will attempt to load an <code>index.js</code> or <code>index.node</code> file out of that
directory. For example, if there was no <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file in the previous
example, then <code>require('./some-library')</code> would attempt to load:</p>
<ul>
<li><code>./some-library/index.js</code></li>
<li><code>./some-library/index.node</code></li>
</ul>
<p>If these attempts fail, then Node.js will report the entire module as missing
with the default error:</p>
<pre><code class="language-console">Error: Cannot find module 'some-library'</code> <button class="copy-button">copy</button></pre>
<p>In all three above cases, an <code>import('./some-library')</code> call would result in a
<a href="#all_errors_err_unsupported_dir_import"><code>ERR_UNSUPPORTED_DIR_IMPORT</code></a> error. Using package <a href="#all_packages_subpath-exports">subpath exports</a> or
<a href="#all_packages_subpath-imports">subpath imports</a> can provide the same containment organization benefits as
folders as modules, and work for both <code>require</code> and <code>import</code>.</p>
</section><section><h3>Loading from <code>node_modules</code> folders<span><a class="mark" href="#all_modules_loading-from-node_modules-folders" id="all_modules_loading-from-node_modules-folders">#</a></span><a aria-hidden="true" class="legacy" id="modules_loading_from_node_modules_folders"></a></h3>
<p>If the module identifier passed to <code>require()</code> is not a
<a href="#all_modules_built-in-modules">built-in</a> module, and does not begin with <code>'/'</code>, <code>'../'</code>, or
<code>'./'</code>, then Node.js starts at the directory of the current module, and
adds <code>/node_modules</code>, and attempts to load the module from that location.
Node.js will not append <code>node_modules</code> to a path already ending in
<code>node_modules</code>.</p>
<p>If it is not found there, then it moves to the parent directory, and so
on, until the root of the file system is reached.</p>
<p>For example, if the file at <code>'/home/ry/projects/foo.js'</code> called
<code>require('bar.js')</code>, then Node.js would look in the following locations, in
this order:</p>
<ul>
<li><code>/home/ry/projects/node_modules/bar.js</code></li>
<li><code>/home/ry/node_modules/bar.js</code></li>
<li><code>/home/node_modules/bar.js</code></li>
<li><code>/node_modules/bar.js</code></li>
</ul>
<p>This allows programs to localize their dependencies, so that they do not
clash.</p>
<p>It is possible to require specific files or sub modules distributed with a
module by including a path suffix after the module name. For instance
<code>require('example-module/path/to/file')</code> would resolve <code>path/to/file</code>
relative to where <code>example-module</code> is located. The suffixed path follows the
same module resolution semantics.</p>
</section><section><h3>Loading from the global folders<span><a class="mark" href="#all_modules_loading-from-the-global-folders" id="all_modules_loading-from-the-global-folders">#</a></span><a aria-hidden="true" class="legacy" id="modules_loading_from_the_global_folders"></a></h3>
<p>If the <code>NODE_PATH</code> environment variable is set to a colon-delimited list
of absolute paths, then Node.js will search those paths for modules if they
are not found elsewhere.</p>
<p>On Windows, <code>NODE_PATH</code> is delimited by semicolons (<code>;</code>) instead of colons.</p>
<p><code>NODE_PATH</code> was originally created to support loading modules from
varying paths before the current <a href="#all_modules_all-together">module resolution</a> algorithm was defined.</p>
<p><code>NODE_PATH</code> is still supported, but is less necessary now that the Node.js
ecosystem has settled on a convention for locating dependent modules.
Sometimes deployments that rely on <code>NODE_PATH</code> show surprising behavior
when people are unaware that <code>NODE_PATH</code> must be set. Sometimes a
module's dependencies change, causing a different version (or even a
different module) to be loaded as the <code>NODE_PATH</code> is searched.</p>
<p>Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:</p>
<ul>
<li>1: <code>$HOME/.node_modules</code></li>
<li>2: <code>$HOME/.node_libraries</code></li>
<li>3: <code>$PREFIX/lib/node</code></li>
</ul>
<p>Where <code>$HOME</code> is the user's home directory, and <code>$PREFIX</code> is the Node.js
configured <code>node_prefix</code>.</p>
<p>These are mostly for historic reasons.</p>
<p>It is strongly encouraged to place dependencies in the local <code>node_modules</code>
folder. These will be loaded faster, and more reliably.</p>
</section><section><h3>The module wrapper<span><a class="mark" href="#all_modules_the-module-wrapper" id="all_modules_the-module-wrapper">#</a></span><a aria-hidden="true" class="legacy" id="modules_the_module_wrapper"></a></h3>
<p>Before a module's code is executed, Node.js will wrap it with a function
wrapper that looks like the following:</p>
<pre><code class="language-js">(<span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-built_in">exports</span>, <span class="hljs-built_in">require</span>, <span class="hljs-variable language_">module</span>, __filename, __dirname</span>) {
<span class="hljs-comment">// Module code actually lives in here</span>
});</code> <button class="copy-button">copy</button></pre>
<p>By doing this, Node.js achieves a few things:</p>
<ul>
<li>It keeps top-level variables (defined with <code>var</code>, <code>const</code>, or <code>let</code>) scoped to
the module rather than the global object.</li>
<li>It helps to provide some global-looking variables that are actually specific
to the module, such as:
<ul>
<li>The <code>module</code> and <code>exports</code> objects that the implementor can use to export
values from the module.</li>
<li>The convenience variables <code>__filename</code> and <code>__dirname</code>, containing the
module's absolute filename and directory path.</li>
</ul>
</li>
</ul>
</section><section><h3>The module scope<span><a class="mark" href="#all_modules_the-module-scope" id="all_modules_the-module-scope">#</a></span><a aria-hidden="true" class="legacy" id="modules_the_module_scope"></a></h3>
<h4><code>__dirname</code><span><a class="mark" href="#all_modules___dirname" id="all_modules___dirname">#</a></span><a aria-hidden="true" class="legacy" id="modules_dirname"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The directory name of the current module. This is the same as the
<a href="#all_path_pathdirnamepath"><code>path.dirname()</code></a> of the <a href="#all_modules___filename"><code>__filename</code></a>.</p>
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(__dirname);
<span class="hljs-comment">// Prints: /Users/mjr</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(path.<span class="hljs-title function_">dirname</span>(__filename));
<span class="hljs-comment">// Prints: /Users/mjr</span></code> <button class="copy-button">copy</button></pre>
<h4><code>__filename</code><span><a class="mark" href="#all_modules___filename" id="all_modules___filename">#</a></span><a aria-hidden="true" class="legacy" id="modules_filename"></a></h4>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The file name of the current module. This is the current module file's absolute
path with symlinks resolved.</p>
<p>For a main program this is not necessarily the same as the file name used in the
command line.</p>
<p>See <a href="#all_modules___dirname"><code>__dirname</code></a> for the directory name of the current module.</p>
<p>Examples:</p>
<p>Running <code>node example.js</code> from <code>/Users/mjr</code></p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(__filename);
<span class="hljs-comment">// Prints: /Users/mjr/example.js</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(__dirname);
<span class="hljs-comment">// Prints: /Users/mjr</span></code> <button class="copy-button">copy</button></pre>
<p>Given two modules: <code>a</code> and <code>b</code>, where <code>b</code> is a dependency of
<code>a</code> and there is a directory structure of:</p>
<ul>
<li><code>/Users/mjr/app/a.js</code></li>
<li><code>/Users/mjr/app/node_modules/b/b.js</code></li>
</ul>
<p>References to <code>__filename</code> within <code>b.js</code> will return
<code>/Users/mjr/app/node_modules/b/b.js</code> while references to <code>__filename</code> within
<code>a.js</code> will return <code>/Users/mjr/app/a.js</code>.</p>
<h4><code>exports</code><span><a class="mark" href="#all_modules_exports" id="all_modules_exports">#</a></span><a aria-hidden="true" class="legacy" id="modules_exports"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.12</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>A reference to the <code>module.exports</code> that is shorter to type.
See the section about the <a href="#all_modules_exports-shortcut">exports shortcut</a> for details on when to use
<code>exports</code> and when to use <code>module.exports</code>.</p>
<h4><code>module</code><span><a class="mark" href="#all_modules_module" id="all_modules_module">#</a></span><a aria-hidden="true" class="legacy" id="modules_module"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><a href="#all_modules_the-module-object" class="type"><module></a></li>
</ul>
<p>A reference to the current module, see the section about the
<a href="#all_modules_the-module-object"><code>module</code> object</a>. In particular, <code>module.exports</code> is used for defining what
a module exports and makes available through <code>require()</code>.</p>
<h4><code>require(id)</code><span><a class="mark" href="#all_modules_requireid" id="all_modules_requireid">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_id"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.13</span>
</div>
<ul>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> module name or path</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> exported module content</li>
</ul>
<p>Used to import modules, <code>JSON</code>, and local files. Modules can be imported
from <code>node_modules</code>. Local modules and JSON files can be imported using
a relative path (e.g. <code>./</code>, <code>./foo</code>, <code>./bar/baz</code>, <code>../foo</code>) that will be
resolved against the directory named by <a href="#all_modules___dirname"><code>__dirname</code></a> (if defined) or
the current working directory. The relative paths of POSIX style are resolved
in an OS independent fashion, meaning that the examples above will work on
Windows in the same way they would on Unix systems.</p>
<pre><code class="language-js"><span class="hljs-comment">// Importing a local module with a path relative to the `__dirname` or current</span>
<span class="hljs-comment">// working directory. (On Windows, this would resolve to .\path\myLocalModule.)</span>
<span class="hljs-keyword">const</span> myLocalModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./path/myLocalModule'</span>);
<span class="hljs-comment">// Importing a JSON file:</span>
<span class="hljs-keyword">const</span> jsonData = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./path/filename.json'</span>);
<span class="hljs-comment">// Importing a module from node_modules or Node.js built-in module:</span>
<span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>require.cache</code><span><a class="mark" href="#all_modules_requirecache" id="all_modules_requirecache">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_cache"></a></h5>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Modules are cached in this object when they are required. By deleting a key
value from this object, the next <code>require</code> will reload the module.
This does not apply to <a href="addons.html">native addons</a>, for which reloading will result in an
error.</p>
<p>Adding or replacing entries is also possible. This cache is checked before
built-in modules and if a name matching a built-in module is added to the cache,
only <code>node:</code>-prefixed require calls are going to receive the built-in module.
Use with care!</p>
<!-- eslint-disable node-core/no-duplicate-requires -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> realFs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> fakeFs = {};
<span class="hljs-built_in">require</span>.<span class="hljs-property">cache</span>.<span class="hljs-property">fs</span> = { <span class="hljs-attr">exports</span>: fakeFs };
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>), fakeFs);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>), realFs);</code> <button class="copy-button">copy</button></pre>
<h5><code>require.extensions</code><span><a class="mark" href="#all_modules_requireextensions" id="all_modules_requireextensions">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_extensions"></a></h5>
<div class="api_metadata">
<span>Added in: v0.3.0</span><span>Deprecated since: v0.10.6</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Instruct <code>require</code> on how to handle certain file extensions.</p>
<p>Process files with the extension <code>.sjs</code> as <code>.js</code>:</p>
<pre><code class="language-js"><span class="hljs-built_in">require</span>.<span class="hljs-property">extensions</span>[<span class="hljs-string">'.sjs'</span>] = <span class="hljs-built_in">require</span>.<span class="hljs-property">extensions</span>[<span class="hljs-string">'.js'</span>];</code> <button class="copy-button">copy</button></pre>
<p><strong>Deprecated.</strong> In the past, this list has been used to load non-JavaScript
modules into Node.js by compiling them on-demand. However, in practice, there
are much better ways to do this, such as loading modules via some other Node.js
program, or compiling them to JavaScript ahead of time.</p>
<p>Avoid using <code>require.extensions</code>. Use could cause subtle bugs and resolving the
extensions gets slower with each registered extension.</p>
<h5><code>require.main</code><span><a class="mark" href="#all_modules_requiremain" id="all_modules_requiremain">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_main"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<ul>
<li><a href="#all_modules_the-module-object" class="type"><module></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>The <code>Module</code> object representing the entry script loaded when the Node.js
process launched, or <code>undefined</code> if the entry point of the program is not a
CommonJS module.
See <a href="#all_modules_accessing-the-main-module">"Accessing the main module"</a>.</p>
<p>In <code>entry.js</code> script:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-built_in">require</span>.<span class="hljs-property">main</span>);</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-bash">node entry.js</code> <button class="copy-button">copy</button></pre>
<!-- eslint-skip -->
<pre><code class="language-js"><span class="hljs-title class_">Module</span> {
<span class="hljs-attr">id</span>: <span class="hljs-string">'.'</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/absolute/path/to'</span>,
<span class="hljs-attr">exports</span>: {},
<span class="hljs-attr">filename</span>: <span class="hljs-string">'/absolute/path/to/entry.js'</span>,
<span class="hljs-attr">loaded</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">children</span>: [],
<span class="hljs-attr">paths</span>:
[ <span class="hljs-string">'/absolute/path/to/node_modules'</span>,
<span class="hljs-string">'/absolute/path/node_modules'</span>,
<span class="hljs-string">'/absolute/node_modules'</span>,
<span class="hljs-string">'/node_modules'</span> ] }</code> <button class="copy-button">copy</button></pre>
<h5><code>require.resolve(request[, options])</code><span><a class="mark" href="#all_modules_requireresolverequest-options" id="all_modules_requireresolverequest-options">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_resolve_request_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.9.0</td>
<td><p>The <code>paths</code> option is now supported.</p></td></tr>
<tr><td>v0.3.0</td>
<td><p><span>Added in: v0.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>request</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The module path to resolve.</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>paths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Paths to resolve module location from. If present, these
paths are used instead of the default resolution paths, with the exception
of <a href="#all_modules_loading-from-the-global-folders">GLOBAL_FOLDERS</a> like <code>$HOME/.node_modules</code>, which are
always included. Each of these paths is used as a starting point for
the module resolution algorithm, meaning that the <code>node_modules</code> hierarchy
is checked from this location.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Use the internal <code>require()</code> machinery to look up the location of a module,
but rather than loading the module, just return the resolved filename.</p>
<p>If the module can not be found, a <code>MODULE_NOT_FOUND</code> error is thrown.</p>
<h6><code>require.resolve.paths(request)</code><span><a class="mark" href="#all_modules_requireresolvepathsrequest" id="all_modules_requireresolvepathsrequest">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_resolve_paths_request"></a></h6>
<div class="api_metadata">
<span>Added in: v8.9.0</span>
</div>
<ul>
<li><code>request</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The module path whose lookup paths are being retrieved.</li>
<li>Returns: <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></li>
</ul>
<p>Returns an array containing the paths searched during resolution of <code>request</code> or
<code>null</code> if the <code>request</code> string references a core module, for example <code>http</code> or
<code>fs</code>.</p>
</section><section><h3>The <code>module</code> object<span><a class="mark" href="#all_modules_the-module-object" id="all_modules_the-module-object">#</a></span><a aria-hidden="true" class="legacy" id="modules_the_module_object"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>In each module, the <code>module</code> free variable is a reference to the object
representing the current module. For convenience, <code>module.exports</code> is
also accessible via the <code>exports</code> module-global. <code>module</code> is not actually
a global but rather local to each module.</p>
<h4><code>module.children</code><span><a class="mark" href="#all_modules_modulechildren" id="all_modules_modulechildren">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_children"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><a href="#all_modules_the-module-object" class="type"><module[]></a></li>
</ul>
<p>The module objects required for the first time by this one.</p>
<h4><code>module.exports</code><span><a class="mark" href="#all_modules_moduleexports" id="all_modules_moduleexports">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_exports"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>module.exports</code> object is created by the <code>Module</code> system. Sometimes this is
not acceptable; many want their module to be an instance of some class. To do
this, assign the desired export object to <code>module.exports</code>. Assigning
the desired object to <code>exports</code> will simply rebind the local <code>exports</code> variable,
which is probably not what is desired.</p>
<p>For example, suppose we were making a module called <code>a.js</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-comment">// Do some work, and after some time emit</span>
<span class="hljs-comment">// the 'ready' event from the module itself.</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ready'</span>);
}, <span class="hljs-number">1000</span>);</code> <button class="copy-button">copy</button></pre>
<p>Then in another file we could do:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> a = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./a'</span>);
a.<span class="hljs-title function_">on</span>(<span class="hljs-string">'ready'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'module "a" is ready'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Assignment to <code>module.exports</code> must be done immediately. It cannot be
done in any callbacks. This does not work:</p>
<p><code>x.js</code>:</p>
<pre><code class="language-js"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = { <span class="hljs-attr">a</span>: <span class="hljs-string">'hello'</span> };
}, <span class="hljs-number">0</span>);</code> <button class="copy-button">copy</button></pre>
<p><code>y.js</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> x = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./x'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x.<span class="hljs-property">a</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>exports</code> shortcut<span><a class="mark" href="#all_modules_exports-shortcut" id="all_modules_exports-shortcut">#</a></span><a aria-hidden="true" class="legacy" id="modules_exports_shortcut"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<p>The <code>exports</code> variable is available within a module's file-level scope, and is
assigned the value of <code>module.exports</code> before the module is evaluated.</p>
<p>It allows a shortcut, so that <code>module.exports.f = ...</code> can be written more
succinctly as <code>exports.f = ...</code>. However, be aware that like any variable, if a
new value is assigned to <code>exports</code>, it is no longer bound to <code>module.exports</code>:</p>
<pre><code class="language-js"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-property">hello</span> = <span class="hljs-literal">true</span>; <span class="hljs-comment">// Exported from require of module</span>
<span class="hljs-built_in">exports</span> = { <span class="hljs-attr">hello</span>: <span class="hljs-literal">false</span> }; <span class="hljs-comment">// Not exported, only available in the module</span></code> <button class="copy-button">copy</button></pre>
<p>When the <code>module.exports</code> property is being completely replaced by a new
object, it is common to also reassign <code>exports</code>:</p>
<!-- eslint-disable func-name-matching -->
<pre><code class="language-js"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-built_in">exports</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">Constructor</span>(<span class="hljs-params"></span>) {
<span class="hljs-comment">// ... etc.</span>
};</code> <button class="copy-button">copy</button></pre>
<p>To illustrate the behavior, imagine this hypothetical implementation of
<code>require()</code>, which is quite similar to what is actually done by <code>require()</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">require</span>(<span class="hljs-params"><span class="hljs-comment">/* ... */</span></span>) {
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = { <span class="hljs-attr">exports</span>: {} };
(<span class="hljs-function">(<span class="hljs-params"><span class="hljs-variable language_">module</span>, <span class="hljs-built_in">exports</span></span>) =></span> {
<span class="hljs-comment">// Module code here. In this example, define a function.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">someFunc</span>(<span class="hljs-params"></span>) {}
<span class="hljs-built_in">exports</span> = someFunc;
<span class="hljs-comment">// At this point, exports is no longer a shortcut to module.exports, and</span>
<span class="hljs-comment">// this module will still export an empty default object.</span>
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = someFunc;
<span class="hljs-comment">// At this point, the module will now export someFunc, instead of the</span>
<span class="hljs-comment">// default object.</span>
})(<span class="hljs-variable language_">module</span>, <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>);
<span class="hljs-keyword">return</span> <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>;
}</code> <button class="copy-button">copy</button></pre>
<h4><code>module.filename</code><span><a class="mark" href="#all_modules_modulefilename" id="all_modules_modulefilename">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_filename"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The fully resolved filename of the module.</p>
<h4><code>module.id</code><span><a class="mark" href="#all_modules_moduleid" id="all_modules_moduleid">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_id"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The identifier for the module. Typically this is the fully resolved
filename.</p>
<h4><code>module.isPreloading</code><span><a class="mark" href="#all_modules_moduleispreloading" id="all_modules_moduleispreloading">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_ispreloading"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0, v14.17.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the module is running during the Node.js preload
phase.</li>
</ul>
<h4><code>module.loaded</code><span><a class="mark" href="#all_modules_moduleloaded" id="all_modules_moduleloaded">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_loaded"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.16</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>Whether or not the module is done loading, or is in the process of
loading.</p>
<h4><code>module.parent</code><span><a class="mark" href="#all_modules_moduleparent" id="all_modules_moduleparent">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_parent"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.16</span><span>Deprecated since: v14.6.0, v12.19.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Please use <a href="#all_modules_requiremain"><code>require.main</code></a> and
<a href="#all_modules_modulechildren"><code>module.children</code></a> instead.</div><p></p>
<ul>
<li><a href="#all_modules_the-module-object" class="type"><module></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#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>The module that first required this one, or <code>null</code> if the current module is the
entry point of the current process, or <code>undefined</code> if the module was loaded by
something that is not a CommonJS module (E.G.: REPL or <code>import</code>).</p>
<h4><code>module.path</code><span><a class="mark" href="#all_modules_modulepath" id="all_modules_modulepath">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_path"></a></h4>
<div class="api_metadata">
<span>Added in: v11.14.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The directory name of the module. This is usually the same as the
<a href="#all_path_pathdirnamepath"><code>path.dirname()</code></a> of the <a href="#all_modules_moduleid"><code>module.id</code></a>.</p>
<h4><code>module.paths</code><span><a class="mark" href="#all_modules_modulepaths" id="all_modules_modulepaths">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_paths"></a></h4>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>The search paths for the module.</p>
<h4><code>module.require(id)</code><span><a class="mark" href="#all_modules_modulerequireid" id="all_modules_modulerequireid">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_require_id"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.1</span>
</div>
<ul>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> exported module content</li>
</ul>
<p>The <code>module.require()</code> method provides a way to load a module as if
<code>require()</code> was called from the original module.</p>
<p>In order to do this, it is necessary to get a reference to the <code>module</code> object.
Since <code>require()</code> returns the <code>module.exports</code>, and the <code>module</code> is typically
<em>only</em> available within a specific module's code, it must be explicitly exported
in order to be used.</p>
</section><section><h3>The <code>Module</code> object<span><a class="mark" href="#all_modules_the-module-object_1" id="all_modules_the-module-object_1">#</a></span><a aria-hidden="true" class="legacy" id="modules_the_module_object_1"></a></h3>
<p>This section was moved to
<a href="#all_module_the-module-object">Modules: <code>module</code> core module</a>.</p>
<!-- Anchors to make sure old links find a target -->
<ul>
<li><a id="modules_module_builtinmodules" href="module.html#modulebuiltinmodules"><code>module.builtinModules</code></a></li>
<li><a id="modules_module_createrequire_filename" href="module.html#modulecreaterequirefilename"><code>module.createRequire(filename)</code></a></li>
<li><a id="modules_module_syncbuiltinesmexports" href="module.html#modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li>
</ul>
</section><section><h3>Source map v3 support<span><a class="mark" href="#all_modules_source-map-v3-support" id="all_modules_source-map-v3-support">#</a></span><a aria-hidden="true" class="legacy" id="modules_source_map_v3_support"></a></h3>
<p>This section was moved to
<a href="#all_module_source-map-v3-support">Modules: <code>module</code> core module</a>.</p>
<!-- Anchors to make sure old links find a target -->
<ul>
<li><a id="modules_module_findsourcemap_path_error" href="module.html#modulefindsourcemappath"><code>module.findSourceMap(path)</code></a></li>
<li><a id="modules_class_module_sourcemap" href="module.html#class-modulesourcemap">Class: <code>module.SourceMap</code></a>
<ul>
<li><a id="modules_new_sourcemap_payload" href="module.html#new-sourcemappayload--linelengths-"><code>new SourceMap(payload)</code></a></li>
<li><a id="modules_sourcemap_payload" href="module.html#sourcemappayload"><code>sourceMap.payload</code></a></li>
<li><a id="modules_sourcemap_findentry_linenumber_columnnumber" href="module.html#sourcemapfindentrylineoffset-columnoffset"><code>sourceMap.findEntry(lineNumber, columnNumber)</code></a></li>
</ul>
</li>
</ul></section>
</section>
<section><h2>Modules: ECMAScript modules<span><a class="mark" href="#all_esm_modules-ecmascript-modules" id="all_esm_modules-ecmascript-modules">#</a></span><a aria-hidden="true" class="legacy" id="esm_modules_ecmascript_modules"></a></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.3</td>
<td><p>Import attributes are no longer experimental.</p></td></tr>
<tr><td>v20.10.0</td>
<td><p>Add experimental support for import attributes.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p>Module customization hooks are executed off the main thread.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining module customization hooks.</p></td></tr>
<tr><td>v17.1.0, v16.14.0</td>
<td><p>Add experimental support for import assertions.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Consolidate customization hooks, removed <code>getFormat</code>, <code>getSource</code>, <code>transformSource</code>, and <code>getGlobalPreloadCode</code> hooks added <code>load</code> and <code>globalPreload</code> hooks allowed returning <code>format</code> from either <code>resolve</code> or <code>load</code> hooks.</p></td></tr>
<tr><td>v14.8.0</td>
<td><p>Unflag Top-Level Await.</p></td></tr>
<tr><td>v15.3.0, v14.17.0, v12.22.0</td>
<td><p>Stabilize modules implementation.</p></td></tr>
<tr><td>v14.13.0, v12.20.0</td>
<td><p>Support for detection of CommonJS named exports.</p></td></tr>
<tr><td>v14.0.0, v13.14.0, v12.20.0</td>
<td><p>Remove experimental modules warning.</p></td></tr>
<tr><td>v13.2.0, v12.17.0</td>
<td><p>Loading ECMAScript modules no longer requires a command-line flag.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add support for ES modules using <code>.js</code> file extension via <code>package.json</code> <code>"type"</code> field.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<section><h3>Introduction<span><a class="mark" href="#all_esm_introduction" id="all_esm_introduction">#</a></span><a aria-hidden="true" class="legacy" id="esm_introduction"></a></h3>
<p>ECMAScript modules are <a href="https://tc39.github.io/ecma262/#sec-modules">the official standard format</a> to package JavaScript
code for reuse. Modules are defined using a variety of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import"><code>import</code></a> and
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export"><code>export</code></a> statements.</p>
<p>The following example of an ES module exports a function:</p>
<pre><code class="language-js"><span class="hljs-comment">// addTwo.mjs</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">addTwo</span>(<span class="hljs-params">num</span>) {
<span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
}
<span class="hljs-keyword">export</span> { addTwo };</code> <button class="copy-button">copy</button></pre>
<p>The following example of an ES module imports the function from <code>addTwo.mjs</code>:</p>
<pre><code class="language-js"><span class="hljs-comment">// app.mjs</span>
<span class="hljs-keyword">import</span> { addTwo } <span class="hljs-keyword">from</span> <span class="hljs-string">'./addTwo.mjs'</span>;
<span class="hljs-comment">// Prints: 6</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">addTwo</span>(<span class="hljs-number">4</span>));</code> <button class="copy-button">copy</button></pre>
<p>Node.js fully supports ECMAScript modules as they are currently specified and
provides interoperability between them and its original module format,
<a href="modules.html">CommonJS</a>.</p>
<!-- Anchors to make sure old links find a target -->
<p><i id="esm_package_json_type_field"></i><i id="esm_package_scope_and_file_extensions"></i><i id="esm_input_type_flag"></i></p>
</section><section><h3>Enabling<span><a class="mark" href="#all_esm_enabling" id="all_esm_enabling">#</a></span><a aria-hidden="true" class="legacy" id="esm_enabling"></a></h3>
<p>Node.js has two module systems: <a href="modules.html">CommonJS</a> modules and ECMAScript modules.</p>
<p>Authors can tell Node.js to interpret JavaScript as an ES module via the <code>.mjs</code>
file extension, the <code>package.json</code> <a href="#all_packages_type"><code>"type"</code></a> field with a value <code>"module"</code>,
the <a href="#all_cli_--input-typetype"><code>--input-type</code></a> flag with a value of <code>"module"</code>, or the
<a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type</code></a> flag with a value of <code>"module"</code>. These are
explicit markers of code being intended to run as an ES module.</p>
<p>Inversely, authors can tell Node.js to interpret JavaScript as CommonJS via the
<code>.cjs</code> file extension, the <code>package.json</code> <a href="#all_packages_type"><code>"type"</code></a> field with a value
<code>"commonjs"</code>, the <a href="#all_cli_--input-typetype"><code>--input-type</code></a> flag with a value of <code>"commonjs"</code>, or the
<a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type</code></a> flag with a value of <code>"commonjs"</code>.</p>
<p>When code lacks explicit markers for either module system, Node.js will inspect
the source code of a module to look for ES module syntax. If such syntax is
found, Node.js will run the code as an ES module; otherwise it will run the
module as CommonJS. See <a href="#all_packages_determining-module-system">Determining module system</a> for more details.</p>
<!-- Anchors to make sure old links find a target -->
<p><i id="esm_package_entry_points"></i><i id="esm_main_entry_point_export"></i><i id="esm_subpath_exports"></i><i id="esm_package_exports_fallbacks"></i><i id="esm_exports_sugar"></i><i id="esm_conditional_exports"></i><i id="esm_nested_conditions"></i><i id="esm_self_referencing_a_package_using_its_name"></i><i id="esm_internal_package_imports"></i><i id="esm_dual_commonjs_es_module_packages"></i><i id="esm_dual_package_hazard"></i><i id="esm_writing_dual_packages_while_avoiding_or_minimizing_hazards"></i><i id="esm_approach_1_use_an_es_module_wrapper"></i><i id="esm_approach_2_isolate_state"></i></p>
</section><section><h3>Packages<span><a class="mark" href="#all_esm_packages" id="all_esm_packages">#</a></span><a aria-hidden="true" class="legacy" id="esm_packages"></a></h3>
<p>This section was moved to <a href="packages.html">Modules: Packages</a>.</p>
</section><section><h3><code>import</code> Specifiers<span><a class="mark" href="#all_esm_import-specifiers" id="all_esm_import-specifiers">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_specifiers"></a></h3>
<h4>Terminology<span><a class="mark" href="#all_esm_terminology" id="all_esm_terminology">#</a></span><a aria-hidden="true" class="legacy" id="esm_terminology"></a></h4>
<p>The <em>specifier</em> of an <code>import</code> statement is the string after the <code>from</code> keyword,
e.g. <code>'node:path'</code> in <code>import { sep } from 'node:path'</code>. Specifiers are also
used in <code>export from</code> statements, and as the argument to an <code>import()</code>
expression.</p>
<p>There are three types of specifiers:</p>
<ul>
<li>
<p><em>Relative specifiers</em> like <code>'./startup.js'</code> or <code>'../config.mjs'</code>. They refer
to a path relative to the location of the importing file. <em>The file extension
is always necessary for these.</em></p>
</li>
<li>
<p><em>Bare specifiers</em> like <code>'some-package'</code> or <code>'some-package/shuffle'</code>. They can
refer to the main entry point of a package by the package name, or a
specific feature module within a package prefixed by the package name as per
the examples respectively. <em>Including the file extension is only necessary
for packages without an <a href="#all_packages_exports"><code>"exports"</code></a> field.</em></p>
</li>
<li>
<p><em>Absolute specifiers</em> like <code>'file:///opt/nodejs/config.js'</code>. They refer
directly and explicitly to a full path.</p>
</li>
</ul>
<p>Bare specifier resolutions are handled by the <a href="#all_esm_resolution-algorithm-specification">Node.js module
resolution and loading algorithm</a>.
All other specifier resolutions are always only resolved with
the standard relative <a href="https://url.spec.whatwg.org/">URL</a> resolution semantics.</p>
<p>Like in CommonJS, module files within packages can be accessed by appending a
path to the package name unless the package's <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> contains an
<a href="#all_packages_exports"><code>"exports"</code></a> field, in which case files within packages can only be accessed
via the paths defined in <a href="#all_packages_exports"><code>"exports"</code></a>.</p>
<p>For details on these package resolution rules that apply to bare specifiers in
the Node.js module resolution, see the <a href="packages.html">packages documentation</a>.</p>
<h4>Mandatory file extensions<span><a class="mark" href="#all_esm_mandatory-file-extensions" id="all_esm_mandatory-file-extensions">#</a></span><a aria-hidden="true" class="legacy" id="esm_mandatory_file_extensions"></a></h4>
<p>A file extension must be provided when using the <code>import</code> keyword to resolve
relative or absolute specifiers. Directory indexes (e.g. <code>'./startup/index.js'</code>)
must also be fully specified.</p>
<p>This behavior matches how <code>import</code> behaves in browser environments, assuming a
typically configured server.</p>
<h4>URLs<span><a class="mark" href="#all_esm_urls" id="all_esm_urls">#</a></span><a aria-hidden="true" class="legacy" id="esm_urls"></a></h4>
<p>ES modules are resolved and cached as URLs. This means that special characters
must be <a href="#all_url_percent-encoding-in-urls">percent-encoded</a>, such as <code>#</code> with <code>%23</code> and <code>?</code> with <code>%3F</code>.</p>
<p><code>file:</code>, <code>node:</code>, and <code>data:</code> URL schemes are supported. A specifier like
<code>'https://example.com/app.js'</code> is not supported natively in Node.js unless using
a <a href="#all_module_import-from-https">custom HTTPS loader</a>.</p>
<h5><code>file:</code> URLs<span><a class="mark" href="#all_esm_file-urls" id="all_esm_file-urls">#</a></span><a aria-hidden="true" class="legacy" id="esm_file_urls"></a></h5>
<p>Modules are loaded multiple times if the <code>import</code> specifier used to resolve
them has a different query or fragment.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'./foo.mjs?query=1'</span>; <span class="hljs-comment">// loads ./foo.mjs with query of "?query=1"</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./foo.mjs?query=2'</span>; <span class="hljs-comment">// loads ./foo.mjs with query of "?query=2"</span></code> <button class="copy-button">copy</button></pre>
<p>The volume root may be referenced via <code>/</code>, <code>//</code>, or <code>file:///</code>. Given the
differences between <a href="https://url.spec.whatwg.org/">URL</a> and path resolution (such as percent encoding
details), it is recommended to use <a href="#all_url_urlpathtofileurlpath-options">url.pathToFileURL</a> when importing a path.</p>
<h5><code>data:</code> imports<span><a class="mark" href="#all_esm_data-imports" id="all_esm_data-imports">#</a></span><a aria-hidden="true" class="legacy" id="esm_data_imports"></a></h5>
<div class="api_metadata">
<span>Added in: v12.10.0</span>
</div>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs"><code>data:</code> URLs</a> are supported for importing with the following MIME types:</p>
<ul>
<li><code>text/javascript</code> for ES modules</li>
<li><code>application/json</code> for JSON</li>
<li><code>application/wasm</code> for Wasm</li>
</ul>
<pre><code class="language-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'data:text/javascript,console.log("hello!");'</span>;
<span class="hljs-keyword">import</span> _ <span class="hljs-keyword">from</span> <span class="hljs-string">'data:application/json,"world!"'</span> <span class="hljs-keyword">with</span> { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };</code> <button class="copy-button">copy</button></pre>
<p><code>data:</code> URLs only resolve <a href="#all_esm_terminology">bare specifiers</a> for builtin modules
and <a href="#all_esm_terminology">absolute specifiers</a>. Resolving
<a href="#all_esm_terminology">relative specifiers</a> does not work because <code>data:</code> is not a
<a href="https://url.spec.whatwg.org/#special-scheme">special scheme</a>. For example, attempting to load <code>./foo</code>
from <code>data:text/javascript,import "./foo";</code> fails to resolve because there
is no concept of relative resolution for <code>data:</code> URLs.</p>
<h5><code>node:</code> imports<span><a class="mark" href="#all_esm_node-imports" id="all_esm_node-imports">#</a></span><a aria-hidden="true" class="legacy" id="esm_node_imports"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0, v14.18.0</td>
<td><p>Added <code>node:</code> import support to <code>require(...)</code>.</p></td></tr>
<tr><td>v14.13.1, v12.20.0</td>
<td><p><span>Added in: v14.13.1, v12.20.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p><code>node:</code> URLs are supported as an alternative means to load Node.js builtin
modules. This URL scheme allows for builtin modules to be referenced by valid
absolute URL strings.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;</code> <button class="copy-button">copy</button></pre>
<p><a id="import-assertions"></a></p>
</section><section><h3>Import attributes<span><a class="mark" href="#all_esm_import-attributes" id="all_esm_import-attributes">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_attributes"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>Switch from Import Assertions to Import Attributes.</p></td></tr>
<tr><td>v17.1.0, v16.14.0</td>
<td><p><span>Added in: v17.1.0, v16.14.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import/with">Import attributes</a> are an inline syntax for module import
statements to pass on more information alongside the module specifier.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> fooData <span class="hljs-keyword">from</span> <span class="hljs-string">'./foo.json'</span> <span class="hljs-keyword">with</span> { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };
<span class="hljs-keyword">const</span> { <span class="hljs-attr">default</span>: barData } =
<span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./bar.json'</span>, { <span class="hljs-attr">with</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> } });</code> <button class="copy-button">copy</button></pre>
<p>Node.js only supports the <code>type</code> attribute, for which it supports the following values:</p>
<table><thead><tr><th>Attribute <code>type</code></th><th>Needed for</th></tr></thead><tbody><tr><td><code>'json'</code></td><td><a href="#all_esm_json-modules">JSON modules</a></td></tr></tbody></table>
<p>The <code>type: 'json'</code> attribute is mandatory when importing JSON modules.</p>
</section><section><h3>Built-in modules<span><a class="mark" href="#all_esm_built-in-modules" id="all_esm_built-in-modules">#</a></span><a aria-hidden="true" class="legacy" id="esm_built_in_modules"></a></h3>
<p><a href="#all_modules_built-in-modules">Built-in modules</a> provide named exports of their public API. A
default export is also provided which is the value of the CommonJS exports.
The default export can be used for, among other things, modifying the named
exports. Named exports of built-in modules are updated only by calling
<a href="#all_module_modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> <span class="hljs-title class_">EventEmitter</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> e = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'./foo.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err, source</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>(source);
}
});</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">import</span> fs, { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { syncBuiltinESMExports } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
fs.<span class="hljs-property">readFileSync</span> = <span class="hljs-function">() =></span> <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello, ESM'</span>);
<span class="hljs-title function_">syncBuiltinESMExports</span>();
fs.<span class="hljs-property">readFileSync</span> === readFileSync;</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>import()</code> expressions<span><a class="mark" href="#all_esm_import-expressions" id="all_esm_import-expressions">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_expressions"></a></h3>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import">Dynamic <code>import()</code></a> is supported in both CommonJS and ES modules. In CommonJS
modules it can be used to load ES modules.</p>
</section><section><h3><code>import.meta</code><span><a class="mark" href="#all_esm_importmeta" id="all_esm_importmeta">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta"></a></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>import.meta</code> meta property is an <code>Object</code> that contains the following
properties. It is only supported in ES modules.</p>
<h4><code>import.meta.dirname</code><span><a class="mark" href="#all_esm_importmetadirname" id="all_esm_importmetadirname">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta_dirname"></a></h4>
<div class="api_metadata">
<span>Added in: v20.11.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The directory name of the current module. This is the same as the
<a href="#all_path_pathdirnamepath"><code>path.dirname()</code></a> of the <a href="#all_esm_importmetafilename"><code>import.meta.filename</code></a>.</li>
</ul>
<blockquote>
<p><strong>Caveat</strong>: only present on <code>file:</code> modules.</p>
</blockquote>
<h4><code>import.meta.filename</code><span><a class="mark" href="#all_esm_importmetafilename" id="all_esm_importmetafilename">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta_filename"></a></h4>
<div class="api_metadata">
<span>Added in: v20.11.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The full absolute path and filename of the current module, with
symlinks resolved.</li>
<li>This is the same as the <a href="#all_url_urlfileurltopathurl-options"><code>url.fileURLToPath()</code></a> of the
<a href="#all_esm_importmetaurl"><code>import.meta.url</code></a>.</li>
</ul>
<blockquote>
<p><strong>Caveat</strong> only local modules support this property. Modules not using the
<code>file:</code> protocol will not provide it.</p>
</blockquote>
<h4><code>import.meta.url</code><span><a class="mark" href="#all_esm_importmetaurl" id="all_esm_importmetaurl">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta_url"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The absolute <code>file:</code> URL of the module.</li>
</ul>
<p>This is defined exactly the same as it is in browsers providing the URL of the
current module file.</p>
<p>This enables useful patterns such as relative file loading:</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> buffer = <span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'./data.proto'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>));</code> <button class="copy-button">copy</button></pre>
<h4><code>import.meta.resolve(specifier)</code><span><a class="mark" href="#all_esm_importmetaresolvespecifier" id="all_esm_importmetaresolvespecifier">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta_resolve_specifier"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>Unflag <code>import.meta.resolve</code>, with <code>parentURL</code> parameter still flagged.</p></td></tr>
<tr><td>v20.6.0</td>
<td><p>This API no longer throws when targeting <code>file:</code> URLs that do not map to an existing file on the local FS.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p>This API now returns a string synchronously instead of a Promise.</p></td></tr>
<tr><td>v16.2.0, v14.18.0</td>
<td><p>Add support for WHATWG <code>URL</code> object to <code>parentURL</code> parameter.</p></td></tr>
<tr><td>v13.9.0, v12.16.2</td>
<td><p><span>Added in: v13.9.0, v12.16.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The module specifier to resolve relative to the
current module.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The absolute URL string that the specifier would resolve to.</li>
</ul>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta/resolve"><code>import.meta.resolve</code></a> is a module-relative resolution function scoped to
each module, returning the URL string.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> dependencyAsset = <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'component-lib/asset.css'</span>);
<span class="hljs-comment">// file:///app/node_modules/component-lib/asset.css</span>
<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'./dep.js'</span>);
<span class="hljs-comment">// file:///app/dep.js</span></code> <button class="copy-button">copy</button></pre>
<p>All features of the Node.js module resolution are supported. Dependency
resolutions are subject to the permitted exports resolutions within the package.</p>
<p><strong>Caveats</strong>:</p>
<ul>
<li>This can result in synchronous file-system operations, which
can impact performance similarly to <code>require.resolve</code>.</li>
<li>This feature is not available within custom loaders (it would
create a deadlock).</li>
</ul>
<p><strong>Non-standard API</strong>:</p>
<p>When using the <code>--experimental-import-meta-resolve</code> flag, that function accepts
a second argument:</p>
<ul>
<li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> An optional absolute parent module URL to resolve from.
<strong>Default:</strong> <code>import.meta.url</code></li>
</ul>
</section><section><h3>Interoperability with CommonJS<span><a class="mark" href="#all_esm_interoperability-with-commonjs" id="all_esm_interoperability-with-commonjs">#</a></span><a aria-hidden="true" class="legacy" id="esm_interoperability_with_commonjs"></a></h3>
<h4><code>import</code> statements<span><a class="mark" href="#all_esm_import-statements" id="all_esm_import-statements">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_statements"></a></h4>
<p>An <code>import</code> statement can reference an ES module or a CommonJS module.
<code>import</code> statements are permitted only in ES modules, but dynamic <a href="#all_esm_import-expressions"><code>import()</code></a>
expressions are supported in CommonJS for loading ES modules.</p>
<p>When importing <a href="#all_esm_commonjs-namespaces">CommonJS modules</a>, the
<code>module.exports</code> object is provided as the default export. Named exports may be
available, provided by static analysis as a convenience for better ecosystem
compatibility.</p>
<h4><code>require</code><span><a class="mark" href="#all_esm_require" id="all_esm_require">#</a></span><a aria-hidden="true" class="legacy" id="esm_require"></a></h4>
<p>The CommonJS module <code>require</code> currently only supports loading synchronous ES
modules (that is, ES modules that do not use top-level <code>await</code>).</p>
<p>See <a href="#all_modules_loading-ecmascript-modules-using-require">Loading ECMAScript modules using <code>require()</code></a> for details.</p>
<h4>CommonJS Namespaces<span><a class="mark" href="#all_esm_commonjs-namespaces" id="all_esm_commonjs-namespaces">#</a></span><a aria-hidden="true" class="legacy" id="esm_commonjs_namespaces"></a></h4>
<p>CommonJS modules consist of a <code>module.exports</code> object which can be of any type.</p>
<p>When importing a CommonJS module, it can be reliably imported using the ES
module default import or its corresponding sugar syntax:</p>
<!-- eslint-disable no-duplicate-imports -->
<pre><code class="language-js"><span class="hljs-keyword">import</span> { <span class="hljs-keyword">default</span> <span class="hljs-keyword">as</span> cjs } <span class="hljs-keyword">from</span> <span class="hljs-string">'cjs'</span>;
<span class="hljs-comment">// The following import statement is "syntax sugar" (equivalent but sweeter)</span>
<span class="hljs-comment">// for `{ default as cjsSugar }` in the above import statement:</span>
<span class="hljs-keyword">import</span> cjsSugar <span class="hljs-keyword">from</span> <span class="hljs-string">'cjs'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cjs);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cjs === cjsSugar);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// <module.exports></span>
<span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></pre>
<p>The ECMAScript Module Namespace representation of a CommonJS module is always
a namespace with a <code>default</code> export key pointing to the CommonJS
<code>module.exports</code> value.</p>
<p>This Module Namespace Exotic Object can be directly observed either when using
<code>import * as m from 'cjs'</code> or a dynamic import:</p>
<!-- eslint-skip -->
<pre><code class="language-js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> m <span class="hljs-keyword">from</span> <span class="hljs-string">'cjs'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(m);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(m === <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'cjs'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// [Module] { default: <module.exports> }</span>
<span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></pre>
<p>For better compatibility with existing usage in the JS ecosystem, Node.js
in addition attempts to determine the CommonJS named exports of every imported
CommonJS module to provide them as separate ES module exports using a static
analysis process.</p>
<p>For example, consider a CommonJS module written:</p>
<pre><code class="language-js cjs"><span class="hljs-comment">// cjs.cjs</span>
<span class="hljs-built_in">exports</span>.<span class="hljs-property">name</span> = <span class="hljs-string">'exported'</span>;</code> <button class="copy-button">copy</button></pre>
<p>The preceding module supports named imports in ES modules:</p>
<!-- eslint-disable no-duplicate-imports -->
<pre><code class="language-js"><span class="hljs-keyword">import</span> { name } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cjs.cjs'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name);
<span class="hljs-comment">// Prints: 'exported'</span>
<span class="hljs-keyword">import</span> cjs <span class="hljs-keyword">from</span> <span class="hljs-string">'./cjs.cjs'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cjs);
<span class="hljs-comment">// Prints: { name: 'exported' }</span>
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> m <span class="hljs-keyword">from</span> <span class="hljs-string">'./cjs.cjs'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(m);
<span class="hljs-comment">// Prints: [Module] { default: { name: 'exported' }, name: 'exported' }</span></code> <button class="copy-button">copy</button></pre>
<p>As can be seen from the last example of the Module Namespace Exotic Object being
logged, the <code>name</code> export is copied off of the <code>module.exports</code> object and set
directly on the ES module namespace when the module is imported.</p>
<p>Live binding updates or new exports added to <code>module.exports</code> are not detected
for these named exports.</p>
<p>The detection of named exports is based on common syntax patterns but does not
always correctly detect named exports. In these cases, using the default
import form described above can be a better option.</p>
<p>Named exports detection covers many common export patterns, reexport patterns
and build tool and transpiler outputs. See <a href="https://github.com/nodejs/cjs-module-lexer/tree/1.2.2">cjs-module-lexer</a> for the exact
semantics implemented.</p>
<h4>Differences between ES modules and CommonJS<span><a class="mark" href="#all_esm_differences-between-es-modules-and-commonjs" id="all_esm_differences-between-es-modules-and-commonjs">#</a></span><a aria-hidden="true" class="legacy" id="esm_differences_between_es_modules_and_commonjs"></a></h4>
<h5>No <code>require</code>, <code>exports</code>, or <code>module.exports</code><span><a class="mark" href="#all_esm_no-require-exports-or-moduleexports" id="all_esm_no-require-exports-or-moduleexports">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_require_exports_or_module_exports"></a></h5>
<p>In most cases, the ES module <code>import</code> can be used to load CommonJS modules.</p>
<p>If needed, a <code>require</code> function can be constructed within an ES module using
<a href="#all_module_modulecreaterequirefilename"><code>module.createRequire()</code></a>.</p>
<h5>No <code>__filename</code> or <code>__dirname</code><span><a class="mark" href="#all_esm_no-__filename-or-__dirname" id="all_esm_no-__filename-or-__dirname">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_filename_or_dirname"></a></h5>
<p>These CommonJS variables are not available in ES modules.</p>
<p><code>__filename</code> and <code>__dirname</code> use cases can be replicated via
<a href="#all_esm_importmetafilename"><code>import.meta.filename</code></a> and <a href="#all_esm_importmetadirname"><code>import.meta.dirname</code></a>.</p>
<h5>No Addon Loading<span><a class="mark" href="#all_esm_no-addon-loading" id="all_esm_no-addon-loading">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_addon_loading"></a></h5>
<p><a href="addons.html">Addons</a> are not currently supported with ES module imports.</p>
<p>They can instead be loaded with <a href="#all_module_modulecreaterequirefilename"><code>module.createRequire()</code></a> or
<a href="#all_process_processdlopenmodule-filename-flags"><code>process.dlopen</code></a>.</p>
<h5>No <code>require.resolve</code><span><a class="mark" href="#all_esm_no-requireresolve" id="all_esm_no-requireresolve">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_require_resolve"></a></h5>
<p>Relative resolution can be handled via <code>new URL('./local', import.meta.url)</code>.</p>
<p>For a complete <code>require.resolve</code> replacement, there is the
<a href="#all_esm_importmetaresolvespecifier">import.meta.resolve</a> API.</p>
<p>Alternatively <code>module.createRequire()</code> can be used.</p>
<h5>No <code>NODE_PATH</code><span><a class="mark" href="#all_esm_no-node_path" id="all_esm_no-node_path">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_node_path"></a></h5>
<p><code>NODE_PATH</code> is not part of resolving <code>import</code> specifiers. Please use symlinks
if this behavior is desired.</p>
<h5>No <code>require.extensions</code><span><a class="mark" href="#all_esm_no-requireextensions" id="all_esm_no-requireextensions">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_require_extensions"></a></h5>
<p><code>require.extensions</code> is not used by <code>import</code>. Module customization hooks can
provide a replacement.</p>
<h5>No <code>require.cache</code><span><a class="mark" href="#all_esm_no-requirecache" id="all_esm_no-requirecache">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_require_cache"></a></h5>
<p><code>require.cache</code> is not used by <code>import</code> as the ES module loader has its own
separate cache.</p>
<p><i id="esm_experimental_json_modules"></i></p>
</section><section><h3>JSON modules<span><a class="mark" href="#all_esm_json-modules" id="all_esm_json-modules">#</a></span><a aria-hidden="true" class="legacy" id="esm_json_modules"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.3</td>
<td><p>JSON modules are no longer experimental.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>JSON files can be referenced by <code>import</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> packageConfig <span class="hljs-keyword">from</span> <span class="hljs-string">'./package.json'</span> <span class="hljs-keyword">with</span> { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };</code> <button class="copy-button">copy</button></pre>
<p>The <code>with { type: 'json' }</code> syntax is mandatory; see <a href="#all_esm_import-attributes">Import Attributes</a>.</p>
<p>The imported JSON only exposes a <code>default</code> export. There is no support for named
exports. A cache entry is created in the CommonJS cache to avoid duplication.
The same object is returned in CommonJS if the JSON module has already been
imported from the same path.</p>
<p><i id="esm_experimental_wasm_modules"></i></p>
</section><section><h3>Wasm modules<span><a class="mark" href="#all_esm_wasm-modules" id="all_esm_wasm-modules">#</a></span><a aria-hidden="true" class="legacy" id="esm_wasm_modules"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Importing WebAssembly modules is supported under the
<code>--experimental-wasm-modules</code> flag, allowing any <code>.wasm</code> files to be
imported as normal modules while also supporting their module imports.</p>
<p>This integration is in line with the
<a href="https://github.com/webassembly/esm-integration">ES Module Integration Proposal for WebAssembly</a>.</p>
<p>For example, an <code>index.mjs</code> containing:</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> M <span class="hljs-keyword">from</span> <span class="hljs-string">'./module.wasm'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(M);</code> <button class="copy-button">copy</button></pre>
<p>executed under:</p>
<pre><code class="language-bash">node --experimental-wasm-modules index.mjs</code> <button class="copy-button">copy</button></pre>
<p>would provide the exports interface for the instantiation of <code>module.wasm</code>.</p>
<p><i id="esm_experimental_top_level_await"></i></p>
</section><section><h3>Top-level <code>await</code><span><a class="mark" href="#all_esm_top-level-await" id="all_esm_top-level-await">#</a></span><a aria-hidden="true" class="legacy" id="esm_top_level_await"></a></h3>
<div class="api_metadata">
<span>Added in: v14.8.0</span>
</div>
<p>The <code>await</code> keyword may be used in the top level body of an ECMAScript module.</p>
<p>Assuming an <code>a.mjs</code> with</p>
<pre><code class="language-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> five = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">5</span>);</code> <button class="copy-button">copy</button></pre>
<p>And a <code>b.mjs</code> with</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> { five } <span class="hljs-keyword">from</span> <span class="hljs-string">'./a.mjs'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(five); <span class="hljs-comment">// Logs `5`</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-bash">node b.mjs <span class="hljs-comment"># works</span></code> <button class="copy-button">copy</button></pre>
<p>If a top level <code>await</code> expression never resolves, the <code>node</code> process will exit
with a <code>13</code> <a href="#all_process_exit-codes">status code</a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> { execPath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-title function_">spawn</span>(execPath, [
<span class="hljs-string">'--input-type=module'</span>,
<span class="hljs-string">'--eval'</span>,
<span class="hljs-comment">// Never-resolving Promise:</span>
<span class="hljs-string">'await new Promise(() => {})'</span>,
]).<span class="hljs-title function_">once</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(code); <span class="hljs-comment">// Logs `13`</span>
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>HTTPS and HTTP imports<span><a class="mark" href="#all_esm_https-and-http-imports" id="all_esm_https-and-http-imports">#</a></span><a aria-hidden="true" class="legacy" id="esm_https_and_http_imports"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Importing network based modules using <code>https:</code> and <code>http:</code> is supported under
the <code>--experimental-network-imports</code> flag. This allows web browser-like imports
to work in Node.js with a few differences due to application stability and
security concerns that are different when running in a privileged environment
instead of a browser sandbox.</p>
<h4>Imports are limited to HTTP/1<span><a class="mark" href="#all_esm_imports-are-limited-to-http1" id="all_esm_imports-are-limited-to-http1">#</a></span><a aria-hidden="true" class="legacy" id="esm_imports_are_limited_to_http_1"></a></h4>
<p>Automatic protocol negotiation for HTTP/2 and HTTP/3 is not yet supported.</p>
<h4>HTTP is limited to loopback addresses<span><a class="mark" href="#all_esm_http-is-limited-to-loopback-addresses" id="all_esm_http-is-limited-to-loopback-addresses">#</a></span><a aria-hidden="true" class="legacy" id="esm_http_is_limited_to_loopback_addresses"></a></h4>
<p><code>http:</code> is vulnerable to man-in-the-middle attacks and is not allowed to be
used for addresses outside of the IPv4 address <code>127.0.0.0/8</code> (<code>127.0.0.1</code> to
<code>127.255.255.255</code>) and the IPv6 address <code>::1</code>. Support for <code>http:</code> is intended
to be used for local development.</p>
<h4>Authentication is never sent to the destination server.<span><a class="mark" href="#all_esm_authentication-is-never-sent-to-the-destination-server" id="all_esm_authentication-is-never-sent-to-the-destination-server">#</a></span><a aria-hidden="true" class="legacy" id="esm_authentication_is_never_sent_to_the_destination_server"></a></h4>
<p><code>Authorization</code>, <code>Cookie</code>, and <code>Proxy-Authorization</code> headers are not sent to the
server. Avoid including user info in parts of imported URLs. A security model
for safely using these on the server is being worked on.</p>
<h4>CORS is never checked on the destination server<span><a class="mark" href="#all_esm_cors-is-never-checked-on-the-destination-server" id="all_esm_cors-is-never-checked-on-the-destination-server">#</a></span><a aria-hidden="true" class="legacy" id="esm_cors_is_never_checked_on_the_destination_server"></a></h4>
<p>CORS is designed to allow a server to limit the consumers of an API to a
specific set of hosts. This is not supported as it does not make sense for a
server-based implementation.</p>
<h4>Cannot load non-network dependencies<span><a class="mark" href="#all_esm_cannot-load-non-network-dependencies" id="all_esm_cannot-load-non-network-dependencies">#</a></span><a aria-hidden="true" class="legacy" id="esm_cannot_load_non_network_dependencies"></a></h4>
<p>These modules cannot access other modules that are not over <code>http:</code> or <code>https:</code>.
To still access local modules while avoiding the security concern, pass in
references to the local dependencies:</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// file.mjs</span>
<span class="hljs-keyword">import</span> worker_threads <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
<span class="hljs-keyword">import</span> { configure, resize } <span class="hljs-keyword">from</span> <span class="hljs-string">'https://example.com/imagelib.mjs'</span>;
<span class="hljs-title function_">configure</span>({ worker_threads });</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js mjs"><span class="hljs-comment">// https://example.com/imagelib.mjs</span>
<span class="hljs-keyword">let</span> worker_threads;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">configure</span>(<span class="hljs-params">opts</span>) {
worker_threads = opts.<span class="hljs-property">worker_threads</span>;
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resize</span>(<span class="hljs-params">img, size</span>) {
<span class="hljs-comment">// Perform resizing in worker_thread to avoid main thread blocking</span>
}</code> <button class="copy-button">copy</button></pre>
<h4>Network-based loading is not enabled by default<span><a class="mark" href="#all_esm_network-based-loading-is-not-enabled-by-default" id="all_esm_network-based-loading-is-not-enabled-by-default">#</a></span><a aria-hidden="true" class="legacy" id="esm_network_based_loading_is_not_enabled_by_default"></a></h4>
<p>For now, the <code>--experimental-network-imports</code> flag is required to enable loading
resources over <code>http:</code> or <code>https:</code>. In the future, a different mechanism will be
used to enforce this. Opt-in is required to prevent transitive dependencies
inadvertently using potentially mutable state that could affect reliability
of Node.js applications.</p>
<p><i id="esm_experimental_loaders"></i></p>
</section><section><h3>Loaders<span><a class="mark" href="#all_esm_loaders" id="all_esm_loaders">#</a></span><a aria-hidden="true" class="legacy" id="esm_loaders"></a></h3>
<p>The former Loaders documentation is now at
<a href="#all_module_customization-hooks">Modules: Customization hooks</a>.</p>
</section><section><h3>Resolution and loading algorithm<span><a class="mark" href="#all_esm_resolution-and-loading-algorithm" id="all_esm_resolution-and-loading-algorithm">#</a></span><a aria-hidden="true" class="legacy" id="esm_resolution_and_loading_algorithm"></a></h3>
<h4>Features<span><a class="mark" href="#all_esm_features" id="all_esm_features">#</a></span><a aria-hidden="true" class="legacy" id="esm_features"></a></h4>
<p>The default resolver has the following properties:</p>
<ul>
<li>FileURL-based resolution as is used by ES modules</li>
<li>Relative and absolute URL resolution</li>
<li>No default extensions</li>
<li>No folder mains</li>
<li>Bare specifier package resolution lookup through node_modules</li>
<li>Does not fail on unknown extensions or protocols</li>
<li>Can optionally provide a hint of the format to the loading phase</li>
</ul>
<p>The default loader has the following properties</p>
<ul>
<li>Support for builtin module loading via <code>node:</code> URLs</li>
<li>Support for "inline" module loading via <code>data:</code> URLs</li>
<li>Support for <code>file:</code> module loading</li>
<li>Fails on any other URL protocol</li>
<li>Fails on unknown extensions for <code>file:</code> loading
(supports only <code>.cjs</code>, <code>.js</code>, and <code>.mjs</code>)</li>
</ul>
<h4>Resolution algorithm<span><a class="mark" href="#all_esm_resolution-algorithm" id="all_esm_resolution-algorithm">#</a></span><a aria-hidden="true" class="legacy" id="esm_resolution_algorithm"></a></h4>
<p>The algorithm to load an ES module specifier is given through the
<strong>ESM_RESOLVE</strong> method below. It returns the resolved URL for a
module specifier relative to a parentURL.</p>
<p>The resolution algorithm determines the full resolved URL for a module
load, along with its suggested module format. The resolution algorithm
does not determine whether the resolved URL protocol can be loaded,
or whether the file extensions are permitted, instead these validations
are applied by Node.js during the load phase
(for example, if it was asked to load a URL that has a protocol that is
not <code>file:</code>, <code>data:</code>, <code>node:</code>, or if <code>--experimental-network-imports</code>
is enabled, <code>https:</code>).</p>
<p>The algorithm also tries to determine the format of the file based
on the extension (see <code>ESM_FILE_FORMAT</code> algorithm below). If it does
not recognize the file extension (eg if it is not <code>.mjs</code>, <code>.cjs</code>, or
<code>.json</code>), then a format of <code>undefined</code> is returned,
which will throw during the load phase.</p>
<p>The algorithm to determine the module format of a resolved URL is
provided by <strong>ESM_FILE_FORMAT</strong>, which returns the unique module
format for any file. The <em>"module"</em> format is returned for an ECMAScript
Module, while the <em>"commonjs"</em> format is used to indicate loading through the
legacy CommonJS loader. Additional formats such as <em>"addon"</em> can be extended in
future updates.</p>
<p>In the following algorithms, all subroutine errors are propagated as errors
of these top-level routines unless stated otherwise.</p>
<p><em>defaultConditions</em> is the conditional environment name array,
<code>["node", "import"]</code>.</p>
<p>The resolver can throw the following errors:</p>
<ul>
<li><em>Invalid Module Specifier</em>: Module specifier is an invalid URL, package name
or package subpath specifier.</li>
<li><em>Invalid Package Configuration</em>: package.json configuration is invalid or
contains an invalid configuration.</li>
<li><em>Invalid Package Target</em>: Package exports or imports define a target module
for the package that is an invalid type or string target.</li>
<li><em>Package Path Not Exported</em>: Package exports do not define or permit a target
subpath in the package for the given module.</li>
<li><em>Package Import Not Defined</em>: Package imports do not define the specifier.</li>
<li><em>Module Not Found</em>: The package or module requested does not exist.</li>
<li><em>Unsupported Directory Import</em>: The resolved path corresponds to a directory,
which is not a supported target for module imports.</li>
</ul>
<h4>Resolution Algorithm Specification<span><a class="mark" href="#all_esm_resolution-algorithm-specification" id="all_esm_resolution-algorithm-specification">#</a></span><a aria-hidden="true" class="legacy" id="esm_resolution_algorithm_specification"></a></h4>
<p><strong>ESM_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>resolved</em> be <strong>undefined</strong>.</li>
<li>If <em>specifier</em> is a valid URL, then
<ol>
<li>Set <em>resolved</em> to the result of parsing and reserializing
<em>specifier</em> as a URL.</li>
</ol>
</li>
<li>Otherwise, if <em>specifier</em> starts with <em>"/"</em>, <em>"./"</em>, or <em>"../"</em>, then
<ol>
<li>Set <em>resolved</em> to the URL resolution of <em>specifier</em> relative to
<em>parentURL</em>.</li>
</ol>
</li>
<li>Otherwise, if <em>specifier</em> starts with <em>"#"</em>, then
<ol>
<li>Set <em>resolved</em> to the result of
<strong>PACKAGE_IMPORTS_RESOLVE</strong>(<em>specifier</em>,
<em>parentURL</em>, <em>defaultConditions</em>).</li>
</ol>
</li>
<li>Otherwise,
<ol>
<li>Note: <em>specifier</em> is now a bare specifier.</li>
<li>Set <em>resolved</em> the result of
<strong>PACKAGE_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>).</li>
</ol>
</li>
<li>Let <em>format</em> be <strong>undefined</strong>.</li>
<li>If <em>resolved</em> is a <em>"file:"</em> URL, then
<ol>
<li>If <em>resolved</em> contains any percent encodings of <em>"/"</em> or <em>"\"</em> (<em>"%2F"</em>
and <em>"%5C"</em> respectively), then
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>If the file at <em>resolved</em> is a directory, then
<ol>
<li>Throw an <em>Unsupported Directory Import</em> error.</li>
</ol>
</li>
<li>If the file at <em>resolved</em> does not exist, then
<ol>
<li>Throw a <em>Module Not Found</em> error.</li>
</ol>
</li>
<li>Set <em>resolved</em> to the real path of <em>resolved</em>, maintaining the
same URL querystring and fragment components.</li>
<li>Set <em>format</em> to the result of <strong>ESM_FILE_FORMAT</strong>(<em>resolved</em>).</li>
</ol>
</li>
<li>Otherwise,
<ol>
<li>Set <em>format</em> the module format of the content type associated with the
URL <em>resolved</em>.</li>
</ol>
</li>
<li>Return <em>format</em> and <em>resolved</em> to the loading phase</li>
</ol>
</blockquote>
<p><strong>PACKAGE_RESOLVE</strong>(<em>packageSpecifier</em>, <em>parentURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>packageName</em> be <strong>undefined</strong>.</li>
<li>If <em>packageSpecifier</em> is an empty string, then
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>If <em>packageSpecifier</em> is a Node.js builtin module name, then
<ol>
<li>Return the string <em>"node:"</em> concatenated with <em>packageSpecifier</em>.</li>
</ol>
</li>
<li>If <em>packageSpecifier</em> does not start with <em>"@"</em>, then
<ol>
<li>Set <em>packageName</em> to the substring of <em>packageSpecifier</em> until the first
<em>"/"</em> separator or the end of the string.</li>
</ol>
</li>
<li>Otherwise,
<ol>
<li>If <em>packageSpecifier</em> does not contain a <em>"/"</em> separator, then
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Set <em>packageName</em> to the substring of <em>packageSpecifier</em>
until the second <em>"/"</em> separator or the end of the string.</li>
</ol>
</li>
<li>If <em>packageName</em> starts with <em>"."</em> or contains <em>"\"</em> or <em>"%"</em>, then
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Let <em>packageSubpath</em> be <em>"."</em> concatenated with the substring of
<em>packageSpecifier</em> from the position at the length of <em>packageName</em>.</li>
<li>If <em>packageSubpath</em> ends in <em>"/"</em>, then
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Let <em>selfUrl</em> be the result of
<strong>PACKAGE_SELF_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>).</li>
<li>If <em>selfUrl</em> is not <strong>undefined</strong>, return <em>selfUrl</em>.</li>
<li>While <em>parentURL</em> is not the file system root,
<ol>
<li>Let <em>packageURL</em> be the URL resolution of <em>"node_modules/"</em>
concatenated with <em>packageSpecifier</em>, relative to <em>parentURL</em>.</li>
<li>Set <em>parentURL</em> to the parent folder URL of <em>parentURL</em>.</li>
<li>If the folder at <em>packageURL</em> does not exist, then
<ol>
<li>Continue the next loop iteration.</li>
</ol>
</li>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
<li>If <em>pjson</em> is not <strong>null</strong> and <em>pjson</em>.<em>exports</em> is not <strong>null</strong> or
<strong>undefined</strong>, then
<ol>
<li>Return the result of <strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>,
<em>packageSubpath</em>, <em>pjson.exports</em>, <em>defaultConditions</em>).</li>
</ol>
</li>
<li>Otherwise, if <em>packageSubpath</em> is equal to <em>"."</em>, then
<ol>
<li>If <em>pjson.main</em> is a string, then
<ol>
<li>Return the URL resolution of <em>main</em> in <em>packageURL</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Otherwise,
<ol>
<li>Return the URL resolution of <em>packageSubpath</em> in <em>packageURL</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Throw a <em>Module Not Found</em> error.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_SELF_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>packageURL</em> be the result of <strong>LOOKUP_PACKAGE_SCOPE</strong>(<em>parentURL</em>).</li>
<li>If <em>packageURL</em> is <strong>null</strong>, then
<ol>
<li>Return <strong>undefined</strong>.</li>
</ol>
</li>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
<li>If <em>pjson</em> is <strong>null</strong> or if <em>pjson</em>.<em>exports</em> is <strong>null</strong> or
<strong>undefined</strong>, then
<ol>
<li>Return <strong>undefined</strong>.</li>
</ol>
</li>
<li>If <em>pjson.name</em> is equal to <em>packageName</em>, then
<ol>
<li>Return the result of <strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>,
<em>packageSubpath</em>, <em>pjson.exports</em>, <em>defaultConditions</em>).</li>
</ol>
</li>
<li>Otherwise, return <strong>undefined</strong>.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>, <em>subpath</em>, <em>exports</em>, <em>conditions</em>)</p>
<blockquote>
<ol>
<li>If <em>exports</em> is an Object with both a key starting with <em>"."</em> and a key not
starting with <em>"."</em>, throw an <em>Invalid Package Configuration</em> error.</li>
<li>If <em>subpath</em> is equal to <em>"."</em>, then
<ol>
<li>Let <em>mainExport</em> be <strong>undefined</strong>.</li>
<li>If <em>exports</em> is a String or Array, or an Object containing no keys
starting with <em>"."</em>, then
<ol>
<li>Set <em>mainExport</em> to <em>exports</em>.</li>
</ol>
</li>
<li>Otherwise if <em>exports</em> is an Object containing a <em>"."</em> property, then
<ol>
<li>Set <em>mainExport</em> to <em>exports</em>[<em>"."</em>].</li>
</ol>
</li>
<li>If <em>mainExport</em> is not <strong>undefined</strong>, then
<ol>
<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(
<em>packageURL</em>, <em>mainExport</em>, <strong>null</strong>, <strong>false</strong>, <em>conditions</em>).</li>
<li>If <em>resolved</em> is not <strong>null</strong> or <strong>undefined</strong>, return <em>resolved</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Otherwise, if <em>exports</em> is an Object and all keys of <em>exports</em> start with
<em>"."</em>, then
<ol>
<li>Assert: <em>subpath</em> begins with <em>"./"</em>.</li>
<li>Let <em>resolved</em> be the result of <strong>PACKAGE_IMPORTS_EXPORTS_RESOLVE</strong>(
<em>subpath</em>, <em>exports</em>, <em>packageURL</em>, <strong>false</strong>, <em>conditions</em>).</li>
<li>If <em>resolved</em> is not <strong>null</strong> or <strong>undefined</strong>, return <em>resolved</em>.</li>
</ol>
</li>
<li>Throw a <em>Package Path Not Exported</em> error.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_IMPORTS_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>, <em>conditions</em>)</p>
<blockquote>
<ol>
<li>Assert: <em>specifier</em> begins with <em>"#"</em>.</li>
<li>If <em>specifier</em> is exactly equal to <em>"#"</em> or starts with <em>"#/"</em>, then
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Let <em>packageURL</em> be the result of <strong>LOOKUP_PACKAGE_SCOPE</strong>(<em>parentURL</em>).</li>
<li>If <em>packageURL</em> is not <strong>null</strong>, then
<ol>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
<li>If <em>pjson.imports</em> is a non-null Object, then
<ol>
<li>Let <em>resolved</em> be the result of
<strong>PACKAGE_IMPORTS_EXPORTS_RESOLVE</strong>(
<em>specifier</em>, <em>pjson.imports</em>, <em>packageURL</em>, <strong>true</strong>, <em>conditions</em>).</li>
<li>If <em>resolved</em> is not <strong>null</strong> or <strong>undefined</strong>, return <em>resolved</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Throw a <em>Package Import Not Defined</em> error.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_IMPORTS_EXPORTS_RESOLVE</strong>(<em>matchKey</em>, <em>matchObj</em>, <em>packageURL</em>,
<em>isImports</em>, <em>conditions</em>)</p>
<blockquote>
<ol>
<li>If <em>matchKey</em> is a key of <em>matchObj</em> and does not contain <em>"*"</em>, then
<ol>
<li>Let <em>target</em> be the value of <em>matchObj</em>[<em>matchKey</em>].</li>
<li>Return the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(<em>packageURL</em>,
<em>target</em>, <strong>null</strong>, <em>isImports</em>, <em>conditions</em>).</li>
</ol>
</li>
<li>Let <em>expansionKeys</em> be the list of keys of <em>matchObj</em> containing only a
single <em>"*"</em>, sorted by the sorting function <strong>PATTERN_KEY_COMPARE</strong>
which orders in descending order of specificity.</li>
<li>For each key <em>expansionKey</em> in <em>expansionKeys</em>, do
<ol>
<li>Let <em>patternBase</em> be the substring of <em>expansionKey</em> up to but excluding
the first <em>"*"</em> character.</li>
<li>If <em>matchKey</em> starts with but is not equal to <em>patternBase</em>, then
<ol>
<li>Let <em>patternTrailer</em> be the substring of <em>expansionKey</em> from the
index after the first <em>"*"</em> character.</li>
<li>If <em>patternTrailer</em> has zero length, or if <em>matchKey</em> ends with
<em>patternTrailer</em> and the length of <em>matchKey</em> is greater than or
equal to the length of <em>expansionKey</em>, then
<ol>
<li>Let <em>target</em> be the value of <em>matchObj</em>[<em>expansionKey</em>].</li>
<li>Let <em>patternMatch</em> be the substring of <em>matchKey</em> starting at the
index of the length of <em>patternBase</em> up to the length of
<em>matchKey</em> minus the length of <em>patternTrailer</em>.</li>
<li>Return the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(<em>packageURL</em>,
<em>target</em>, <em>patternMatch</em>, <em>isImports</em>, <em>conditions</em>).</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
<li>Return <strong>null</strong>.</li>
</ol>
</blockquote>
<p><strong>PATTERN_KEY_COMPARE</strong>(<em>keyA</em>, <em>keyB</em>)</p>
<blockquote>
<ol>
<li>Assert: <em>keyA</em> contains only a single <em>"*"</em>.</li>
<li>Assert: <em>keyB</em> contains only a single <em>"*"</em>.</li>
<li>Let <em>baseLengthA</em> be the index of <em>"*"</em> in <em>keyA</em>.</li>
<li>Let <em>baseLengthB</em> be the index of <em>"*"</em> in <em>keyB</em>.</li>
<li>If <em>baseLengthA</em> is greater than <em>baseLengthB</em>, return -1.</li>
<li>If <em>baseLengthB</em> is greater than <em>baseLengthA</em>, return 1.</li>
<li>If the length of <em>keyA</em> is greater than the length of <em>keyB</em>, return -1.</li>
<li>If the length of <em>keyB</em> is greater than the length of <em>keyA</em>, return 1.</li>
<li>Return 0.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>, <em>patternMatch</em>,
<em>isImports</em>, <em>conditions</em>)</p>
<blockquote>
<ol>
<li>If <em>target</em> is a String, then
<ol>
<li>If <em>target</em> does not start with <em>"./"</em>, then
<ol>
<li>If <em>isImports</em> is <strong>false</strong>, or if <em>target</em> starts with <em>"../"</em> or
<em>"/"</em>, or if <em>target</em> is a valid URL, then
<ol>
<li>Throw an <em>Invalid Package Target</em> error.</li>
</ol>
</li>
<li>If <em>patternMatch</em> is a String, then
<ol>
<li>Return <strong>PACKAGE_RESOLVE</strong>(<em>target</em> with every instance of <em>"*"</em>
replaced by <em>patternMatch</em>, <em>packageURL</em> + <em>"/"</em>).</li>
</ol>
</li>
<li>Return <strong>PACKAGE_RESOLVE</strong>(<em>target</em>, <em>packageURL</em> + <em>"/"</em>).</li>
</ol>
</li>
<li>If <em>target</em> split on <em>"/"</em> or <em>"\"</em> contains any <em>""</em>, <em>"."</em>, <em>".."</em>,
or <em>"node_modules"</em> segments after the first <em>"."</em> segment, case
insensitive and including percent encoded variants, throw an <em>Invalid
Package Target</em> error.</li>
<li>Let <em>resolvedTarget</em> be the URL resolution of the concatenation of
<em>packageURL</em> and <em>target</em>.</li>
<li>Assert: <em>packageURL</em> is contained in <em>resolvedTarget</em>.</li>
<li>If <em>patternMatch</em> is <strong>null</strong>, then
<ol>
<li>Return <em>resolvedTarget</em>.</li>
</ol>
</li>
<li>If <em>patternMatch</em> split on <em>"/"</em> or <em>"\"</em> contains any <em>""</em>, <em>"."</em>,
<em>".."</em>, or <em>"node_modules"</em> segments, case insensitive and including
percent encoded variants, throw an <em>Invalid Module Specifier</em> error.</li>
<li>Return the URL resolution of <em>resolvedTarget</em> with every instance of
<em>"*"</em> replaced with <em>patternMatch</em>.</li>
</ol>
</li>
<li>Otherwise, if <em>target</em> is a non-null Object, then
<ol>
<li>If <em>target</em> contains any index property keys, as defined in ECMA-262
<a href="https://tc39.es/ecma262/#integer-index">6.1.7 Array Index</a>, throw an <em>Invalid Package Configuration</em> error.</li>
<li>For each property <em>p</em> of <em>target</em>, in object insertion order as,
<ol>
<li>If <em>p</em> equals <em>"default"</em> or <em>conditions</em> contains an entry for <em>p</em>,
then
<ol>
<li>Let <em>targetValue</em> be the value of the <em>p</em> property in <em>target</em>.</li>
<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(
<em>packageURL</em>, <em>targetValue</em>, <em>patternMatch</em>, <em>isImports</em>,
<em>conditions</em>).</li>
<li>If <em>resolved</em> is equal to <strong>undefined</strong>, continue the loop.</li>
<li>Return <em>resolved</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Return <strong>undefined</strong>.</li>
</ol>
</li>
<li>Otherwise, if <em>target</em> is an Array, then
<ol>
<li>If _target.length is zero, return <strong>null</strong>.</li>
<li>For each item <em>targetValue</em> in <em>target</em>, do
<ol>
<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(
<em>packageURL</em>, <em>targetValue</em>, <em>patternMatch</em>, <em>isImports</em>,
<em>conditions</em>), continuing the loop on any <em>Invalid Package Target</em>
error.</li>
<li>If <em>resolved</em> is <strong>undefined</strong>, continue the loop.</li>
<li>Return <em>resolved</em>.</li>
</ol>
</li>
<li>Return or throw the last fallback resolution <strong>null</strong> return or error.</li>
</ol>
</li>
<li>Otherwise, if <em>target</em> is <em>null</em>, return <strong>null</strong>.</li>
<li>Otherwise throw an <em>Invalid Package Target</em> error.</li>
</ol>
</blockquote>
<p><strong>ESM_FILE_FORMAT</strong>(<em>url</em>)</p>
<blockquote>
<ol>
<li>Assert: <em>url</em> corresponds to an existing file.</li>
<li>If <em>url</em> ends in <em>".mjs"</em>, then
<ol>
<li>Return <em>"module"</em>.</li>
</ol>
</li>
<li>If <em>url</em> ends in <em>".cjs"</em>, then
<ol>
<li>Return <em>"commonjs"</em>.</li>
</ol>
</li>
<li>If <em>url</em> ends in <em>".json"</em>, then
<ol>
<li>Return <em>"json"</em>.</li>
</ol>
</li>
<li>If <code>--experimental-wasm-modules</code> is enabled and <em>url</em> ends in
<em>".wasm"</em>, then
<ol>
<li>Return <em>"wasm"</em>.</li>
</ol>
</li>
<li>Let <em>packageURL</em> be the result of <strong>LOOKUP_PACKAGE_SCOPE</strong>(<em>url</em>).</li>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
<li>Let <em>packageType</em> be <strong>null</strong>.</li>
<li>If <em>pjson?.type</em> is <em>"module"</em> or <em>"commonjs"</em>, then
<ol>
<li>Set <em>packageType</em> to <em>pjson.type</em>.</li>
</ol>
</li>
<li>If <em>url</em> ends in <em>".js"</em>, then
<ol>
<li>If <em>packageType</em> is not <strong>null</strong>, then
<ol>
<li>Return <em>packageType</em>.</li>
</ol>
</li>
<li>If the result of <strong>DETECT_MODULE_SYNTAX</strong>(<em>source</em>) is true, then
<ol>
<li>Return <em>"module"</em>.</li>
</ol>
</li>
<li>Return <em>"commonjs"</em>.</li>
</ol>
</li>
<li>If <em>url</em> does not have any extension, then
<ol>
<li>If <em>packageType</em> is <em>"module"</em> and <code>--experimental-wasm-modules</code> is
enabled and the file at <em>url</em> contains the header for a WebAssembly
module, then
<ol>
<li>Return <em>"wasm"</em>.</li>
</ol>
</li>
<li>If <em>packageType</em> is not <strong>null</strong>, then
<ol>
<li>Return <em>packageType</em>.</li>
</ol>
</li>
<li>If the result of <strong>DETECT_MODULE_SYNTAX</strong>(<em>source</em>) is true, then
<ol>
<li>Return <em>"module"</em>.</li>
</ol>
</li>
<li>Return <em>"commonjs"</em>.</li>
</ol>
</li>
<li>Return <strong>undefined</strong> (will throw during load phase).</li>
</ol>
</blockquote>
<p><strong>LOOKUP_PACKAGE_SCOPE</strong>(<em>url</em>)</p>
<blockquote>
<ol>
<li>Let <em>scopeURL</em> be <em>url</em>.</li>
<li>While <em>scopeURL</em> is not the file system root,
<ol>
<li>Set <em>scopeURL</em> to the parent URL of <em>scopeURL</em>.</li>
<li>If <em>scopeURL</em> ends in a <em>"node_modules"</em> path segment, return <strong>null</strong>.</li>
<li>Let <em>pjsonURL</em> be the resolution of <em>"package.json"</em> within
<em>scopeURL</em>.</li>
<li>if the file at <em>pjsonURL</em> exists, then
<ol>
<li>Return <em>scopeURL</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Return <strong>null</strong>.</li>
</ol>
</blockquote>
<p><strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>pjsonURL</em> be the resolution of <em>"package.json"</em> within <em>packageURL</em>.</li>
<li>If the file at <em>pjsonURL</em> does not exist, then
<ol>
<li>Return <strong>null</strong>.</li>
</ol>
</li>
<li>If the file at <em>packageURL</em> does not parse as valid JSON, then
<ol>
<li>Throw an <em>Invalid Package Configuration</em> error.</li>
</ol>
</li>
<li>Return the parsed JSON source of the file at <em>pjsonURL</em>.</li>
</ol>
</blockquote>
<p><strong>DETECT_MODULE_SYNTAX</strong>(<em>source</em>)</p>
<blockquote>
<ol>
<li>Parse <em>source</em> as an ECMAScript module.</li>
<li>If the parse is successful, then
<ol>
<li>If <em>source</em> contains top-level <code>await</code>, static <code>import</code> or <code>export</code>
statements, or <code>import.meta</code>, return <strong>true</strong>.</li>
<li>If <em>source</em> contains a top-level lexical declaration (<code>const</code>, <code>let</code>,
or <code>class</code>) of any of the CommonJS wrapper variables (<code>require</code>,
<code>exports</code>, <code>module</code>, <code>__filename</code>, or <code>__dirname</code>) then return <strong>true</strong>.</li>
</ol>
</li>
<li>Else return <strong>false</strong>.</li>
</ol>
</blockquote>
<h4>Customizing ESM specifier resolution algorithm<span><a class="mark" href="#all_esm_customizing-esm-specifier-resolution-algorithm" id="all_esm_customizing-esm-specifier-resolution-algorithm">#</a></span><a aria-hidden="true" class="legacy" id="esm_customizing_esm_specifier_resolution_algorithm"></a></h4>
<p><a href="#all_module_customization-hooks">Module customization hooks</a> provide a mechanism for customizing the ESM
specifier resolution algorithm. An example that provides CommonJS-style
resolution for ESM specifiers is <a href="https://github.com/nodejs/loaders-test/tree/main/commonjs-extension-resolution-loader">commonjs-extension-resolution-loader</a>.</p>
<!-- Note: The cjs-module-lexer link should be kept in-sync with the deps version --></section>
</section>
<section><h2>Modules: <code>node:module</code> API<span><a class="mark" href="#all_module_modules-nodemodule-api" id="all_module_modules-nodemodule-api">#</a></span><a aria-hidden="true" class="legacy" id="module_modules_node_module_api"></a></h2>
<div class="api_metadata">
<span>Added in: v0.3.7</span>
</div>
<section><h3>The <code>Module</code> object<span><a class="mark" href="#all_module_the-module-object" id="all_module_the-module-object">#</a></span><a aria-hidden="true" class="legacy" id="module_the_module_object"></a></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Provides general utility methods when interacting with instances of
<code>Module</code>, the <a href="#all_modules_the-module-object"><code>module</code></a> variable often seen in <a href="modules.html">CommonJS</a> modules. Accessed
via <code>import 'node:module'</code> or <code>require('node:module')</code>.</p>
<h4><code>module.builtinModules</code><span><a class="mark" href="#all_module_modulebuiltinmodules" id="all_module_modulebuiltinmodules">#</a></span><a aria-hidden="true" class="legacy" id="module_module_builtinmodules"></a></h4>
<div class="api_metadata">
<span>Added in: v9.3.0, v8.10.0, v6.13.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>A list of the names of all modules provided by Node.js. Can be used to verify
if a module is maintained by a third party or not.</p>
<p>Note: the list doesn't contain <a href="#all_modules_built-in-modules-with-mandatory-node-prefix">prefix-only modules</a> like <code>node:test</code>.</p>
<p><code>module</code> in this context isn't the same object that's provided
by the <a href="#all_modules_the-module-wrapper">module wrapper</a>. To access it, require the <code>Module</code> module:</p>
<pre class="with-26-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// module.mjs</span>
<span class="hljs-comment">// In an ECMAScript module</span>
<span class="hljs-keyword">import</span> { builtinModules <span class="hljs-keyword">as</span> builtin } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;</code><code class="language-js cjs"><span class="hljs-comment">// module.cjs</span>
<span class="hljs-comment">// In a CommonJS module</span>
<span class="hljs-keyword">const</span> builtin = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>).<span class="hljs-property">builtinModules</span>;</code><button class="copy-button">copy</button></pre>
<h4><code>module.createRequire(filename)</code><span><a class="mark" href="#all_module_modulecreaterequirefilename" id="all_module_modulecreaterequirefilename">#</a></span><a aria-hidden="true" class="legacy" id="module_module_createrequire_filename"></a></h4>
<div class="api_metadata">
<span>Added in: v12.2.0</span>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> Filename to be used to construct the require
function. Must be a file URL object, file URL string, or absolute path
string.</li>
<li>Returns: <a href="#all_modules_requireid" class="type"><require></a> Require function</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { createRequire } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-keyword">const</span> <span class="hljs-built_in">require</span> = <span class="hljs-title function_">createRequire</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
<span class="hljs-comment">// sibling-module.js is a CommonJS module.</span>
<span class="hljs-keyword">const</span> siblingModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./sibling-module'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>module.isBuiltin(moduleName)</code><span><a class="mark" href="#all_module_moduleisbuiltinmodulename" id="all_module_moduleisbuiltinmodulename">#</a></span><a aria-hidden="true" class="legacy" id="module_module_isbuiltin_modulename"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.0</span>
</div>
<ul>
<li><code>moduleName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> name of the module</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> returns true if the module is builtin else returns false</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { isBuiltin } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'node:fs'</span>); <span class="hljs-comment">// true</span>
<span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'fs'</span>); <span class="hljs-comment">// true</span>
<span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'wss'</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>module.register(specifier[, parentURL][, options])</code><span><a class="mark" href="#all_module_moduleregisterspecifier-parenturl-options" id="all_module_moduleregisterspecifier-parenturl-options">#</a></span><a aria-hidden="true" class="legacy" id="module_module_register_specifier_parenturl_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>v20.18.2</td>
<td><p>Using this feature with the permission model enabled requires passing <code>--allow-worker</code>.</p></td></tr>
<tr><td>v20.8.0</td>
<td><p>Add support for WHATWG URL instances.</p></td></tr>
<tr><td>v20.6.0</td>
<td><p><span>Added in: v20.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> Customization hooks to be registered; this should be
the same string that would be passed to <code>import()</code>, except that if it is
relative, it is resolved relative to <code>parentURL</code>.</li>
<li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> If you want to resolve <code>specifier</code> relative to a base
URL, such as <code>import.meta.url</code>, you can pass that URL here. <strong>Default:</strong>
<code>'data:'</code></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>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> If you want to resolve <code>specifier</code> relative to a
base URL, such as <code>import.meta.url</code>, you can pass that URL here. This
property is ignored if the <code>parentURL</code> is supplied as the second argument.
<strong>Default:</strong> <code>'data:'</code></li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any arbitrary, cloneable JavaScript value to pass into the
<a href="#all_module_initialize"><code>initialize</code></a> hook.</li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> <a href="#all_worker_threads_portpostmessagevalue-transferlist">transferrable objects</a> to be passed into the
<code>initialize</code> hook.</li>
</ul>
</li>
</ul>
<p>Register a module that exports <a href="#all_module_customization-hooks">hooks</a> that customize Node.js module
resolution and loading behavior. See <a href="#all_module_customization-hooks">Customization hooks</a>.</p>
<p>This feature requires <code>--allow-worker</code> if used with the <a href="#all_permissions_permission-model">Permission Model</a>.</p>
<h4><code>module.syncBuiltinESMExports()</code><span><a class="mark" href="#all_module_modulesyncbuiltinesmexports" id="all_module_modulesyncbuiltinesmexports">#</a></span><a aria-hidden="true" class="legacy" id="module_module_syncbuiltinesmexports"></a></h4>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<p>The <code>module.syncBuiltinESMExports()</code> method updates all the live bindings for
builtin <a href="esm.html">ES Modules</a> to match the properties of the <a href="modules.html">CommonJS</a> exports. It
does not add or remove exported names from the <a href="esm.html">ES Modules</a>.</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> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { syncBuiltinESMExports } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
fs.<span class="hljs-property">readFile</span> = newAPI;
<span class="hljs-keyword">delete</span> fs.<span class="hljs-property">readFileSync</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">newAPI</span>(<span class="hljs-params"></span>) {
<span class="hljs-comment">// ...</span>
}
fs.<span class="hljs-property">newAPI</span> = newAPI;
<span class="hljs-title function_">syncBuiltinESMExports</span>();
<span class="hljs-keyword">import</span>(<span class="hljs-string">'node:fs'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">esmFS</span>) =></span> {
<span class="hljs-comment">// It syncs the existing readFile property with the new value</span>
assert.<span class="hljs-title function_">strictEqual</span>(esmFS.<span class="hljs-property">readFile</span>, newAPI);
<span class="hljs-comment">// readFileSync has been deleted from the required fs</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-string">'readFileSync'</span> <span class="hljs-keyword">in</span> fs, <span class="hljs-literal">false</span>);
<span class="hljs-comment">// syncBuiltinESMExports() does not remove readFileSync from esmFS</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-string">'readFileSync'</span> <span class="hljs-keyword">in</span> esmFS, <span class="hljs-literal">true</span>);
<span class="hljs-comment">// syncBuiltinESMExports() does not add names</span>
assert.<span class="hljs-title function_">strictEqual</span>(esmFS.<span class="hljs-property">newAPI</span>, <span class="hljs-literal">undefined</span>);
});</code> <button class="copy-button">copy</button></pre>
<p><i id="module_customization_hooks"></i></p>
</section><section><h3>Customization Hooks<span><a class="mark" href="#all_module_customization-hooks" id="all_module_customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_customization_hooks"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>Added <code>initialize</code> hook to replace <code>globalPreload</code>.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining loaders.</p></td></tr>
<tr><td>v16.12.0</td>
<td><p>Removed <code>getFormat</code>, <code>getSource</code>, <code>transformSource</code>, and <code>globalPreload</code>; added <code>load</code> hook and <code>getGlobalPreload</code> hook.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p><span>Added in: v8.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<p><i id="enabling_module_customization_hooks"></i></p>
<h4>Enabling<span><a class="mark" href="#all_module_enabling" id="all_module_enabling">#</a></span><a aria-hidden="true" class="legacy" id="module_enabling"></a></h4>
<p>Module resolution and loading can be customized by registering a file which
exports a set of hooks. This can be done using the <a href="#all_module_moduleregisterspecifier-parenturl-options"><code>register</code></a> method
from <code>node:module</code>, which you can run before your application code by
using the <code>--import</code> flag:</p>
<pre><code class="language-bash">node --import ./register-hooks.js ./my-app.js</code> <button class="copy-button">copy</button></pre>
<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// register-hooks.js</span>
<span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./hooks.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);</code><code class="language-js cjs"><span class="hljs-comment">// register-hooks.js</span>
<span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./hooks.mjs'</span>, <span class="hljs-title function_">pathToFileURL</span>(__filename));</code><button class="copy-button">copy</button></pre>
<p>The file passed to <code>--import</code> can also be an export from a dependency:</p>
<pre><code class="language-bash">node --import some-package/register ./my-app.js</code> <button class="copy-button">copy</button></pre>
<p>Where <code>some-package</code> has an <a href="#all_packages_exports"><code>"exports"</code></a> field defining the <code>/register</code>
export to map to a file that calls <code>register()</code>, like the following <code>register-hooks.js</code>
example.</p>
<p>Using <code>--import</code> ensures that the hooks are registered before any application
files are imported, including the entry point of the application. Alternatively,
<code>register</code> can be called from the entry point, but dynamic <code>import()</code> must be
used for any code that should be run after the hooks are registered:</p>
<pre class="with-46-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> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-title function_">register</span>(<span class="hljs-string">'http-to-https'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
<span class="hljs-comment">// Because this is a dynamic `import()`, the `http-to-https` hooks will run</span>
<span class="hljs-comment">// to handle `./my-app.js` and any other files it imports or requires.</span>
<span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.js'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-title function_">register</span>(<span class="hljs-string">'http-to-https'</span>, <span class="hljs-title function_">pathToFileURL</span>(__filename));
<span class="hljs-comment">// Because this is a dynamic `import()`, the `http-to-https` hooks will run</span>
<span class="hljs-comment">// to handle `./my-app.js` and any other files it imports or requires.</span>
<span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.js'</span>);</code><button class="copy-button">copy</button></pre>
<p>In this example, we are registering the <code>http-to-https</code> hooks, but they will
only be available for subsequently imported modules—in this case, <code>my-app.js</code>
and anything it references via <code>import</code> (and optionally <code>require</code>). If the
<code>import('./my-app.js')</code> had instead been a static <code>import './my-app.js'</code>, the
app would have <em>already</em> been loaded <strong>before</strong> the <code>http-to-https</code> hooks were
registered. This due to the ES modules specification, where static imports are
evaluated from the leaves of the tree first, then back to the trunk. There can
be static imports <em>within</em> <code>my-app.js</code>, which will not be evaluated until
<code>my-app.js</code> is dynamically imported.</p>
<p><code>my-app.js</code> can also be CommonJS. Customization hooks will run for any
modules that it references via <code>import</code> (and optionally <code>require</code>).</p>
<p>Finally, if all you want to do is register hooks before your app runs and you
don't want to create a separate file for that purpose, you can pass a <code>data:</code>
URL to <code>--import</code>:</p>
<pre><code class="language-bash">node --import <span class="hljs-string">'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("http-to-https", pathToFileURL("./"));'</span> ./my-app.js</code> <button class="copy-button">copy</button></pre>
<h4>Chaining<span><a class="mark" href="#all_module_chaining" id="all_module_chaining">#</a></span><a aria-hidden="true" class="legacy" id="module_chaining"></a></h4>
<p>It's possible to call <code>register</code> more than once:</p>
<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// entrypoint.mjs</span>
<span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./foo.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./bar.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
<span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.mjs'</span>);</code><code class="language-js cjs"><span class="hljs-comment">// entrypoint.cjs</span>
<span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> parentURL = <span class="hljs-title function_">pathToFileURL</span>(__filename);
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./foo.mjs'</span>, parentURL);
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./bar.mjs'</span>, parentURL);
<span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.mjs'</span>);</code><button class="copy-button">copy</button></pre>
<p>In this example, the registered hooks will form chains. These chains run
last-in, first out (LIFO). If both <code>foo.mjs</code> and <code>bar.mjs</code> define a <code>resolve</code>
hook, they will be called like so (note the right-to-left):
node's default ← <code>./foo.mjs</code> ← <code>./bar.mjs</code>
(starting with <code>./bar.mjs</code>, then <code>./foo.mjs</code>, then the Node.js default).
The same applies to all the other hooks.</p>
<p>The registered hooks also affect <code>register</code> itself. In this example,
<code>bar.mjs</code> will be resolved and loaded via the hooks registered by <code>foo.mjs</code>
(because <code>foo</code>'s hooks will have already been added to the chain). This allows
for things like writing hooks in non-JavaScript languages, so long as
earlier registered hooks transpile into JavaScript.</p>
<p>The <code>register</code> method cannot be called from within the module that defines the
hooks.</p>
<h4>Communication with module customization hooks<span><a class="mark" href="#all_module_communication-with-module-customization-hooks" id="all_module_communication-with-module-customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_communication_with_module_customization_hooks"></a></h4>
<p>Module customization hooks run on a dedicated thread, separate from the main
thread that runs application code. This means mutating global variables won't
affect the other thread(s), and message channels must be used to communicate
between the threads.</p>
<p>The <code>register</code> method can be used to pass data to an <a href="#all_module_initialize"><code>initialize</code></a> hook. The
data passed to the hook may include transferrable objects like ports.</p>
<pre class="with-53-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> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">MessageChannel</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
<span class="hljs-comment">// This example demonstrates how a message channel can be used to</span>
<span class="hljs-comment">// communicate with the hooks, by sending `port2` to the hooks.</span>
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg);
});
port1.<span class="hljs-title function_">unref</span>();
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./my-hooks.mjs'</span>, {
<span class="hljs-attr">parentURL</span>: <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>,
<span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
<span class="hljs-attr">transferList</span>: [port2],
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-comment">// This example showcases how a message channel can be used to</span>
<span class="hljs-comment">// communicate with the hooks, by sending `port2` to the hooks.</span>
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg);
});
port1.<span class="hljs-title function_">unref</span>();
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./my-hooks.mjs'</span>, {
<span class="hljs-attr">parentURL</span>: <span class="hljs-title function_">pathToFileURL</span>(__filename),
<span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
<span class="hljs-attr">transferList</span>: [port2],
});</code><button class="copy-button">copy</button></pre>
<h4>Hooks<span><a class="mark" href="#all_module_hooks" id="all_module_hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_hooks"></a></h4>
<p>The <a href="#all_module_moduleregisterspecifier-parenturl-options"><code>register</code></a> method can be used to register a module that exports a set of
hooks. The hooks are functions that are called by Node.js to customize the
module resolution and loading process. The exported functions must have specific
names and signatures, and they must be exported as named exports.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">initialize</span>(<span class="hljs-params">{ number, port }</span>) {
<span class="hljs-comment">// Receives data from `register`.</span>
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
<span class="hljs-comment">// Take an `import` or `require` specifier and resolve it to a URL.</span>
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
<span class="hljs-comment">// Take a resolved URL and return the source code to be evaluated.</span>
}</code> <button class="copy-button">copy</button></pre>
<p>Hooks are part of a <a href="#all_module_chaining">chain</a>, even if that chain consists of only one
custom (user-provided) hook and the default hook, which is always present. Hook
functions nest: each one must always return a plain object, and chaining happens
as a result of each function calling <code>next<hookName>()</code>, which is a reference to
the subsequent loader's hook (in LIFO order).</p>
<p>A hook that returns a value lacking a required property triggers an exception. A
hook that returns without calling <code>next<hookName>()</code> <em>and</em> without returning
<code>shortCircuit: true</code> also triggers an exception. These errors are to help
prevent unintentional breaks in the chain. Return <code>shortCircuit: true</code> from a
hook to signal that the chain is intentionally ending at your hook.</p>
<p>Hooks are run in a separate thread, isolated from the main thread where
application code runs. That means it is a different <a href="https://tc39.es/ecma262/#realm">realm</a>. The hooks thread
may be terminated by the main thread at any time, so do not depend on
asynchronous operations (like <code>console.log</code>) to complete.</p>
<h5><code>initialize()</code><span><a class="mark" href="#all_module_initialize" id="all_module_initialize">#</a></span><a aria-hidden="true" class="legacy" id="module_initialize"></a></h5>
<div class="api_metadata">
<span>Added in: v20.6.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The data from <code>register(loader, import.meta.url, { data })</code>.</li>
</ul>
<p>The <code>initialize</code> hook provides a way to define a custom function that runs in
the hooks thread when the hooks module is initialized. Initialization happens
when the hooks module is registered via <a href="#all_module_moduleregisterspecifier-parenturl-options"><code>register</code></a>.</p>
<p>This hook can receive data from a <a href="#all_module_moduleregisterspecifier-parenturl-options"><code>register</code></a> invocation, including
ports and other transferrable objects. The return value of <code>initialize</code> can be a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a>, in which case it will be awaited before the main application thread
execution resumes.</p>
<p>Module customization code:</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// path-to-my-hooks.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">initialize</span>(<span class="hljs-params">{ number, port }</span>) {
port.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">`increment: <span class="hljs-subst">${number + <span class="hljs-number">1</span>}</span>`</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>Caller code:</p>
<pre class="with-44-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">MessageChannel</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
<span class="hljs-comment">// This example showcases how a message channel can be used to communicate</span>
<span class="hljs-comment">// between the main (application) thread and the hooks running on the hooks</span>
<span class="hljs-comment">// thread, by sending `port2` to the `initialize` hook.</span>
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
assert.<span class="hljs-title function_">strictEqual</span>(msg, <span class="hljs-string">'increment: 2'</span>);
});
port1.<span class="hljs-title function_">unref</span>();
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./path-to-my-hooks.js'</span>, {
<span class="hljs-attr">parentURL</span>: <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>,
<span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
<span class="hljs-attr">transferList</span>: [port2],
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-comment">// This example showcases how a message channel can be used to communicate</span>
<span class="hljs-comment">// between the main (application) thread and the hooks running on the hooks</span>
<span class="hljs-comment">// thread, by sending `port2` to the `initialize` hook.</span>
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
assert.<span class="hljs-title function_">strictEqual</span>(msg, <span class="hljs-string">'increment: 2'</span>);
});
port1.<span class="hljs-title function_">unref</span>();
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./path-to-my-hooks.js'</span>, {
<span class="hljs-attr">parentURL</span>: <span class="hljs-title function_">pathToFileURL</span>(__filename),
<span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
<span class="hljs-attr">transferList</span>: [port2],
});</code><button class="copy-button">copy</button></pre>
<h5><code>resolve(specifier, context, nextResolve)</code><span><a class="mark" href="#all_module_resolvespecifier-context-nextresolve" id="all_module_resolvespecifier-context-nextresolve">#</a></span><a aria-hidden="true" class="legacy" id="module_resolve_specifier_context_nextresolve"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The property <code>context.importAssertions</code> is replaced with <code>context.importAttributes</code>. Using the old name is still supported and will emit an experimental warning.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining resolve hooks. Each hook must either call <code>nextResolve()</code> or include a <code>shortCircuit</code> property set to <code>true</code> in its return.</p></td></tr>
<tr><td>v17.1.0, v16.14.0</td>
<td><p>Add support for import assertions.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Export conditions of the relevant <code>package.json</code></li>
<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object whose key-value pairs represent the
attributes for the module to import</li>
<li><code>parentURL</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#Undefined_type" class="type"><undefined></a> The module importing this one, or undefined
if this is the Node.js entry point</li>
</ul>
</li>
<li><code>nextResolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The subsequent <code>resolve</code> hook in the chain, or the
Node.js default <code>resolve</code> hook after the last user-supplied <code>resolve</code> hook
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a>
<ul>
<li><code>format</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> A hint to the load hook (it might be
ignored)
<code>'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'</code></li>
<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The import attributes to use when
caching the module (optional; if excluded the input will be used)</li>
<li><code>shortCircuit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> A signal that this hook intends to
terminate the chain of <code>resolve</code> hooks. <strong>Default:</strong> <code>false</code></li>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The absolute URL to which this input resolves</li>
</ul>
</li>
</ul>
<blockquote>
<p><strong>Warning</strong> Despite support for returning promises and async functions, calls
to <code>resolve</code> may block the main thread which can impact performance.</p>
</blockquote>
<p>The <code>resolve</code> hook chain is responsible for telling Node.js where to find and
how to cache a given <code>import</code> statement or expression, or <code>require</code> call. It can
optionally return a format (such as <code>'module'</code>) as a hint to the <code>load</code> hook. If
a format is specified, the <code>load</code> hook is ultimately responsible for providing
the final <code>format</code> value (and it is free to ignore the hint provided by
<code>resolve</code>); if <code>resolve</code> provides a <code>format</code>, a custom <code>load</code> hook is required
even if only to pass the value to the Node.js default <code>load</code> hook.</p>
<p>Import type attributes are part of the cache key for saving loaded modules into
the internal module cache. The <code>resolve</code> hook is responsible for returning an
<code>importAttributes</code> object if the module should be cached with different
attributes than were present in the source code.</p>
<p>The <code>conditions</code> property in <code>context</code> is an array of conditions for
<a href="#all_packages_conditional-exports">package exports conditions</a> that apply to this resolution
request. They can be used for looking up conditional mappings elsewhere or to
modify the list when calling the default resolution logic.</p>
<p>The current <a href="#all_packages_conditional-exports">package exports conditions</a> are always in
the <code>context.conditions</code> array passed into the hook. To guarantee <em>default
Node.js module specifier resolution behavior</em> when calling <code>defaultResolve</code>, the
<code>context.conditions</code> array passed to it <em>must</em> include <em>all</em> elements of the
<code>context.conditions</code> array originally passed into the <code>resolve</code> hook.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
<span class="hljs-keyword">const</span> { parentURL = <span class="hljs-literal">null</span> } = context;
<span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() > <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Some condition.</span>
<span class="hljs-comment">// For some or all specifiers, do some custom logic for resolving.</span>
<span class="hljs-comment">// Always return an object of the form {url: <string>}.</span>
<span class="hljs-keyword">return</span> {
<span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">url</span>: parentURL ?
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier, parentURL).<span class="hljs-property">href</span> :
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier).<span class="hljs-property">href</span>,
};
}
<span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() < <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Another condition.</span>
<span class="hljs-comment">// When calling `defaultResolve`, the arguments can be modified. In this</span>
<span class="hljs-comment">// case it's adding another value for matching conditional exports.</span>
<span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, {
...context,
<span class="hljs-attr">conditions</span>: [...context.<span class="hljs-property">conditions</span>, <span class="hljs-string">'another-condition'</span>],
});
}
<span class="hljs-comment">// Defer to the next hook in the chain, which would be the</span>
<span class="hljs-comment">// Node.js default resolve if this is the last user-specified loader.</span>
<span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier);
}</code> <button class="copy-button">copy</button></pre>
<h5><code>load(url, context, nextLoad)</code><span><a class="mark" href="#all_module_loadurl-context-nextload" id="all_module_loadurl-context-nextload">#</a></span><a aria-hidden="true" class="legacy" id="module_load_url_context_nextload"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>Add support for <code>source</code> with format <code>commonjs</code>.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining load hooks. Each hook must either call <code>nextLoad()</code> or include a <code>shortCircuit</code> property set to <code>true</code> in its return.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The URL returned by the <code>resolve</code> chain</li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Export conditions of the relevant <code>package.json</code></li>
<li><code>format</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The format optionally supplied by the
<code>resolve</code> hook chain</li>
<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
</li>
<li><code>nextLoad</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The subsequent <code>load</code> hook in the chain, or the
Node.js default <code>load</code> hook after the last user-supplied <code>load</code> hook
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
</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>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>shortCircuit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> A signal that this hook intends to
terminate the chain of <code>load</code> hooks. <strong>Default:</strong> <code>false</code></li>
<li><code>source</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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> The source for Node.js to evaluate</li>
</ul>
</li>
</ul>
<p>The <code>load</code> hook provides a way to define a custom method of determining how a
URL should be interpreted, retrieved, and parsed. It is also in charge of
validating the import assertion.</p>
<p>The final value of <code>format</code> must be one of the following:</p>
<table><thead><tr><th><code>format</code></th><th>Description</th><th>Acceptable types for <code>source</code> returned by <code>load</code></th></tr></thead><tbody><tr><td><code>'builtin'</code></td><td>Load a Node.js builtin module</td><td>Not applicable</td></tr><tr><td><code>'commonjs'</code></td><td>Load a Node.js CommonJS module</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String"><code>string</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>, <code>null</code>, <code>undefined</code> }</td></tr><tr><td><code>'json'</code></td><td>Load a JSON file</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String"><code>string</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> }</td></tr><tr><td><code>'module'</code></td><td>Load an ES module</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String"><code>string</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> }</td></tr><tr><td><code>'wasm'</code></td><td>Load a WebAssembly module</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> }</td></tr></tbody></table>
<p>The value of <code>source</code> is ignored for type <code>'builtin'</code> because currently it is
not possible to replace the value of a Node.js builtin (core) module.</p>
<p>Omitting vs providing a <code>source</code> for <code>'commonjs'</code> has very different effects:</p>
<ul>
<li>When a <code>source</code> is provided, all <code>require</code> calls from this module will be
processed by the ESM loader with registered <code>resolve</code> and <code>load</code> hooks; all
<code>require.resolve</code> calls from this module will be processed by the ESM loader
with registered <code>resolve</code> hooks; only a subset of the CommonJS API will be
available (e.g. no <code>require.extensions</code>, no <code>require.cache</code>, no
<code>require.resolve.paths</code>) and monkey-patching on the CommonJS module loader
will not apply.</li>
<li>If <code>source</code> is undefined or <code>null</code>, it will be handled by the CommonJS module
loader and <code>require</code>/<code>require.resolve</code> calls will not go through the
registered hooks. This behavior for nullish <code>source</code> is temporary — in the
future, nullish <code>source</code> will not be supported.</li>
</ul>
<p>When <code>node</code> is run with <code>--experimental-default-type=commonjs</code>, the Node.js
internal <code>load</code> implementation, which is the value of <code>next</code> for the
last hook in the <code>load</code> chain, returns <code>null</code> for <code>source</code> when <code>format</code> is
<code>'commonjs'</code> for backward compatibility. Here is an example hook that would
opt-in to using the non-default behavior:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> <span class="hljs-title function_">nextLoad</span>(url, context);
<span class="hljs-keyword">if</span> (result.<span class="hljs-property">format</span> === <span class="hljs-string">'commonjs'</span>) {
result.<span class="hljs-property">source</span> ??= <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(result.<span class="hljs-property">responseURL</span> ?? url));
}
<span class="hljs-keyword">return</span> result;
}</code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Warning</strong>: The ESM <code>load</code> hook and namespaced exports from CommonJS modules
are incompatible. Attempting to use them together will result in an empty
object from the import. This may be addressed in the future.</p>
</blockquote>
<blockquote>
<p>These types all correspond to classes defined in ECMAScript.</p>
</blockquote>
<ul>
<li>The specific <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> object is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a>.</li>
<li>The specific <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> object is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>.</li>
</ul>
<p>If the source value of a text-based format (i.e., <code>'json'</code>, <code>'module'</code>)
is not a string, it is converted to a string using <a href="#all_util_class-utiltextdecoder"><code>util.TextDecoder</code></a>.</p>
<p>The <code>load</code> hook provides a way to define a custom method for retrieving the
source code of a resolved URL. This would allow a loader to potentially avoid
reading files from disk. It could also be used to map an unrecognized format to
a supported one, for example <code>yaml</code> to <code>module</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
<span class="hljs-keyword">const</span> { format } = context;
<span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() > <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Some condition</span>
<span class="hljs-comment">/*
For some or all URLs, do some custom logic for retrieving the source.
Always return an object of the form {
format: <string>,
source: <string|buffer>,
}.
*/</span>
<span class="hljs-keyword">return</span> {
format,
<span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">source</span>: <span class="hljs-string">'...'</span>,
};
}
<span class="hljs-comment">// Defer to the next hook in the chain.</span>
<span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
}</code> <button class="copy-button">copy</button></pre>
<p>In a more advanced scenario, this can also be used to transform an unsupported
source to a supported one (see <a href="#all_module_examples">Examples</a> below).</p>
<h5><code>globalPreload()</code><span><a class="mark" href="#all_module_globalpreload" id="all_module_globalpreload">#</a></span><a aria-hidden="true" class="legacy" id="module_globalpreload"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining globalPreload hooks.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.0 - Early development</div><p></p>
<blockquote>
<p><strong>Warning:</strong> This hook will be removed in a future version. Use
<a href="#all_module_initialize"><code>initialize</code></a> instead. When a hooks module has an <code>initialize</code> export,
<code>globalPreload</code> will be ignored.</p>
</blockquote>
<ul>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Information to assist the preload code
<ul>
<li><code>port</code> <a href="#all_worker_threads_class-messageport" class="type"><MessagePort></a></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Code to run before application startup</li>
</ul>
<p>Sometimes it might be necessary to run some code inside of the same global
scope that the application runs in. This hook allows the return of a string
that is run as a sloppy-mode script on startup.</p>
<p>Similar to how CommonJS wrappers work, the code runs in an implicit function
scope. The only argument is a <code>require</code>-like function that can be used to load
builtins like "fs": <code>getBuiltin(request: string)</code>.</p>
<p>If the code needs more advanced <code>require</code> features, it has to construct
its own <code>require</code> using <code>module.createRequire()</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">globalPreload</span>(<span class="hljs-params">context</span>) {
<span class="hljs-keyword">return</span> <span class="hljs-string">`\
globalThis.someInjectedProperty = 42;
console.log('I just set some globals!');
const { createRequire } = getBuiltin('module');
const { cwd } = getBuiltin('process');
const require = createRequire(cwd() + '/<preload>');
// [...]
`</span>;
}</code> <button class="copy-button">copy</button></pre>
<p>Another argument is provided to the preload code: <code>port</code>. This is available as a
parameter to the hook and inside of the source text returned by the hook. This
functionality has been moved to the <code>initialize</code> hook.</p>
<p>Care must be taken in order to properly call <a href="#all_worker_threads_portref"><code>port.ref()</code></a> and
<a href="#all_worker_threads_portunref"><code>port.unref()</code></a> to prevent a process from being in a state where it won't
close normally.</p>
<pre><code class="language-js mjs"><span class="hljs-comment">/**
* This example has the application context send a message to the hook
* and sends the message back to the application context
*/</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">globalPreload</span>(<span class="hljs-params">{ port }</span>) {
port.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">evt</span>) =></span> {
port.<span class="hljs-title function_">postMessage</span>(evt.<span class="hljs-property">data</span>);
};
<span class="hljs-keyword">return</span> <span class="hljs-string">`\
port.postMessage('console.log("I went to the hook and back");');
port.onmessage = (evt) => {
eval(evt.data);
};
`</span>;
}</code> <button class="copy-button">copy</button></pre>
<h4>Examples<span><a class="mark" href="#all_module_examples" id="all_module_examples">#</a></span><a aria-hidden="true" class="legacy" id="module_examples"></a></h4>
<p>The various module customization hooks can be used together to accomplish
wide-ranging customizations of the Node.js code loading and evaluation
behaviors.</p>
<h5>Import from HTTPS<span><a class="mark" href="#all_module_import-from-https" id="all_module_import-from-https">#</a></span><a aria-hidden="true" class="legacy" id="module_import_from_https"></a></h5>
<p>In current Node.js, specifiers starting with <code>https://</code> are experimental (see
<a href="#all_esm_https-and-http-imports">HTTPS and HTTP imports</a>).</p>
<p>The hook below registers hooks to enable rudimentary support for such
specifiers. While this may seem like a significant improvement to Node.js core
functionality, there are substantial downsides to actually using these hooks:
performance is much slower than loading files from disk, there is no caching,
and there is no security.</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// https-hooks.mjs</span>
<span class="hljs-keyword">import</span> { get } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
<span class="hljs-comment">// For JavaScript to be loaded over the network, we need to fetch and</span>
<span class="hljs-comment">// return it.</span>
<span class="hljs-keyword">if</span> (url.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'https://'</span>)) {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
<span class="hljs-title function_">get</span>(url, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> data += chunk);
res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">resolve</span>({
<span class="hljs-comment">// This example assumes all network-provided JavaScript is ES module</span>
<span class="hljs-comment">// code.</span>
<span class="hljs-attr">format</span>: <span class="hljs-string">'module'</span>,
<span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">source</span>: data,
}));
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> <span class="hljs-title function_">reject</span>(err));
});
}
<span class="hljs-comment">// Let Node.js handle all other URLs.</span>
<span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
}</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js mjs"><span class="hljs-comment">// main.mjs</span>
<span class="hljs-keyword">import</span> { <span class="hljs-variable constant_">VERSION</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'https://coffeescript.org/browser-compiler-modern/coffeescript.js'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable constant_">VERSION</span>);</code> <button class="copy-button">copy</button></pre>
<p>With the preceding hooks module, running
<code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjs</code>
prints the current version of CoffeeScript per the module at the URL in
<code>main.mjs</code>.</p>
<h5>Transpilation<span><a class="mark" href="#all_module_transpilation" id="all_module_transpilation">#</a></span><a aria-hidden="true" class="legacy" id="module_transpilation"></a></h5>
<p>Sources that are in formats Node.js doesn't understand can be converted into
JavaScript using the <a href="#all_module_loadurl-context-nextload"><code>load</code> hook</a>.</p>
<p>This is less performant than transpiling source files before running Node.js;
transpiler hooks should only be used for development and testing purposes.</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// coffeescript-hooks.mjs</span>
<span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { dirname, extname, resolve <span class="hljs-keyword">as</span> resolvePath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-keyword">import</span> { cwd } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> { fileURLToPath, pathToFileURL } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">import</span> coffeescript <span class="hljs-keyword">from</span> <span class="hljs-string">'coffeescript'</span>;
<span class="hljs-keyword">const</span> extensionsRegex = <span class="hljs-regexp">/\.(coffee|litcoffee|coffee\.md)$/</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
<span class="hljs-keyword">if</span> (extensionsRegex.<span class="hljs-title function_">test</span>(url)) {
<span class="hljs-comment">// CoffeeScript files can be either CommonJS or ES modules, so we want any</span>
<span class="hljs-comment">// CoffeeScript file to be treated by Node.js the same as a .js file at the</span>
<span class="hljs-comment">// same location. To determine how Node.js would interpret an arbitrary .js</span>
<span class="hljs-comment">// file, search up the file system for the nearest parent package.json file</span>
<span class="hljs-comment">// and read its "type" field.</span>
<span class="hljs-keyword">const</span> format = <span class="hljs-keyword">await</span> <span class="hljs-title function_">getPackageType</span>(url);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">source</span>: rawSource } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">nextLoad</span>(url, { ...context, format });
<span class="hljs-comment">// This hook converts CoffeeScript source code into JavaScript source code</span>
<span class="hljs-comment">// for all imported CoffeeScript files.</span>
<span class="hljs-keyword">const</span> transformedSource = coffeescript.<span class="hljs-title function_">compile</span>(rawSource.<span class="hljs-title function_">toString</span>(), url);
<span class="hljs-keyword">return</span> {
format,
<span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">source</span>: transformedSource,
};
}
<span class="hljs-comment">// Let Node.js handle all other URLs.</span>
<span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
}
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getPackageType</span>(<span class="hljs-params">url</span>) {
<span class="hljs-comment">// `url` is only a file path during the first iteration when passed the</span>
<span class="hljs-comment">// resolved url from the load() hook</span>
<span class="hljs-comment">// an actual file path from load() will contain a file extension as it's</span>
<span class="hljs-comment">// required by the spec</span>
<span class="hljs-comment">// this simple truthy check for whether `url` contains a file extension will</span>
<span class="hljs-comment">// work for most projects but does not cover some edge-cases (such as</span>
<span class="hljs-comment">// extensionless files or a url ending in a trailing space)</span>
<span class="hljs-keyword">const</span> isFilePath = !!<span class="hljs-title function_">extname</span>(url);
<span class="hljs-comment">// If it is a file path, get the directory it's in</span>
<span class="hljs-keyword">const</span> dir = isFilePath ?
<span class="hljs-title function_">dirname</span>(<span class="hljs-title function_">fileURLToPath</span>(url)) :
url;
<span class="hljs-comment">// Compose a file path to a package.json in the same directory,</span>
<span class="hljs-comment">// which may or may not exist</span>
<span class="hljs-keyword">const</span> packagePath = <span class="hljs-title function_">resolvePath</span>(dir, <span class="hljs-string">'package.json'</span>);
<span class="hljs-comment">// Try to read the possibly nonexistent package.json</span>
<span class="hljs-keyword">const</span> type = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(packagePath, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span> })
.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">filestring</span>) =></span> <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(filestring).<span class="hljs-property">type</span>)
.<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err?.<span class="hljs-property">code</span> !== <span class="hljs-string">'ENOENT'</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
});
<span class="hljs-comment">// If package.json existed and contained a `type` field with a value, voilà</span>
<span class="hljs-keyword">if</span> (type) <span class="hljs-keyword">return</span> type;
<span class="hljs-comment">// Otherwise, (if not at the root) continue checking the next directory up</span>
<span class="hljs-comment">// If at the root, stop and return false</span>
<span class="hljs-keyword">return</span> dir.<span class="hljs-property">length</span> > <span class="hljs-number">1</span> && <span class="hljs-title function_">getPackageType</span>(<span class="hljs-title function_">resolvePath</span>(dir, <span class="hljs-string">'..'</span>));
}</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-coffee"><span class="hljs-comment"># main.coffee</span>
<span class="hljs-keyword">import</span> { scream } <span class="hljs-keyword">from</span> <span class="hljs-string">'./scream.coffee'</span>
console.log scream <span class="hljs-string">'hello, world'</span>
<span class="hljs-keyword">import</span> { version } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>
console.log <span class="hljs-string">"Brought to you by Node.js version <span class="hljs-subst">#{version}</span>"</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-coffee"><span class="hljs-comment"># scream.coffee</span>
<span class="hljs-keyword">export</span> scream = <span class="hljs-function"><span class="hljs-params">(str)</span> -></span> str.toUpperCase()</code> <button class="copy-button">copy</button></pre>
<p>With the preceding hooks module, running
<code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee</code>
causes <code>main.coffee</code> to be turned into JavaScript after its source code is
loaded from disk but before Node.js executes it; and so on for any <code>.coffee</code>,
<code>.litcoffee</code> or <code>.coffee.md</code> files referenced via <code>import</code> statements of any
loaded file.</p>
<h5>Import maps<span><a class="mark" href="#all_module_import-maps" id="all_module_import-maps">#</a></span><a aria-hidden="true" class="legacy" id="module_import_maps"></a></h5>
<p>The previous two examples defined <code>load</code> hooks. This is an example of a
<code>resolve</code> hook. This hooks module reads an <code>import-map.json</code> file that defines
which specifiers to override to other URLs (this is a very simplistic
implementation of a small subset of the "import maps" specification).</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// import-map-hooks.js</span>
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">const</span> { imports } = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-keyword">await</span> fs.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'import-map.json'</span>));
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
<span class="hljs-keyword">if</span> (<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">hasOwn</span>(imports, specifier)) {
<span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(imports[specifier], context);
}
<span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, context);
}</code> <button class="copy-button">copy</button></pre>
<p>With these files:</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'a-module'</span>;</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-json"><span class="hljs-comment">// import-map.json</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"a-module"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./some-module.js"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js mjs"><span class="hljs-comment">// some-module.js</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'some module!'</span>);</code> <button class="copy-button">copy</button></pre>
<p>Running <code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.js</code>
should print <code>some module!</code>.</p>
</section><section><h3>Source map v3 support<span><a class="mark" href="#all_module_source-map-v3-support" id="all_module_source-map-v3-support">#</a></span><a aria-hidden="true" class="legacy" id="module_source_map_v3_support"></a></h3>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Helpers for interacting with the source map cache. This cache is
populated when source map parsing is enabled and
<a href="https://sourcemaps.info/spec.html#h.lmz475t4mvbx">source map include directives</a> are found in a modules' footer.</p>
<p>To enable source map parsing, Node.js must be run with the flag
<a href="#all_cli_--enable-source-maps"><code>--enable-source-maps</code></a>, or with code coverage enabled by setting
<a href="#all_cli_node_v8_coveragedir"><code>NODE_V8_COVERAGE=dir</code></a>.</p>
<pre class="with-26-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// module.mjs</span>
<span class="hljs-comment">// In an ECMAScript module</span>
<span class="hljs-keyword">import</span> { findSourceMap, <span class="hljs-title class_">SourceMap</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;</code><code class="language-js cjs"><span class="hljs-comment">// module.cjs</span>
<span class="hljs-comment">// In a CommonJS module</span>
<span class="hljs-keyword">const</span> { findSourceMap, <span class="hljs-title class_">SourceMap</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);</code><button class="copy-button">copy</button></pre>
<!-- Anchors to make sure old links find a target -->
<p><a id="module_module_findsourcemap_path_error"></a></p>
<h4><code>module.findSourceMap(path)</code><span><a class="mark" href="#all_module_modulefindsourcemappath" id="all_module_modulefindsourcemappath">#</a></span><a aria-hidden="true" class="legacy" id="module_module_findsourcemap_path"></a></h4>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="#all_module_class-modulesourcemap" class="type"><module.SourceMap></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> Returns <code>module.SourceMap</code> if a source
map is found, <code>undefined</code> otherwise.</li>
</ul>
<p><code>path</code> is the resolved path for the file for which a corresponding source map
should be fetched.</p>
<h4>Class: <code>module.SourceMap</code><span><a class="mark" href="#all_module_class-modulesourcemap" id="all_module_class-modulesourcemap">#</a></span><a aria-hidden="true" class="legacy" id="module_class_module_sourcemap"></a></h4>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0</span>
</div>
<h5><code>new SourceMap(payload[, { lineLengths }])</code><span><a class="mark" href="#all_module_new-sourcemappayload--linelengths-" id="all_module_new-sourcemappayload--linelengths-">#</a></span><a aria-hidden="true" class="legacy" id="module_new_sourcemap_payload_linelengths"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.5.0</td>
<td><p>Add support for <code>lineLengths</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>payload</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>lineLengths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number[]></a></li>
</ul>
<p>Creates a new <code>sourceMap</code> instance.</p>
<p><code>payload</code> is an object with keys matching the <a href="https://sourcemaps.info/spec.html#h.mofvlxcwqzej">Source map v3 format</a>:</p>
<ul>
<li><code>file</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>version</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>sources</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
<li><code>sourcesContent</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
<li><code>names</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
<li><code>mappings</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>sourceRoot</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p><code>lineLengths</code> is an optional array of the length of each line in the
generated code.</p>
<h5><code>sourceMap.payload</code><span><a class="mark" href="#all_module_sourcemappayload" id="all_module_sourcemappayload">#</a></span><a aria-hidden="true" class="legacy" id="module_sourcemap_payload"></a></h5>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Getter for the payload used to construct the <a href="#all_module_class-modulesourcemap"><code>SourceMap</code></a> instance.</p>
<h5><code>sourceMap.findEntry(lineOffset, columnOffset)</code><span><a class="mark" href="#all_module_sourcemapfindentrylineoffset-columnoffset" id="all_module_sourcemapfindentrylineoffset-columnoffset">#</a></span><a aria-hidden="true" class="legacy" id="module_sourcemap_findentry_lineoffset_columnoffset"></a></h5>
<ul>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The zero-indexed line number offset in
the generated source</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The zero-indexed column number offset
in the generated source</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Given a line offset and column offset in the generated source
file, returns an object representing the SourceMap range in the
original file if found, or an empty object if not.</p>
<p>The object returned contains the following keys:</p>
<ul>
<li>generatedLine: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The line offset of the start of the
range in the generated source</li>
<li>generatedColumn: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The column offset of start of the
range in the generated source</li>
<li>originalSource: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The file name of the original source,
as reported in the SourceMap</li>
<li>originalLine: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The line offset of the start of the
range in the original source</li>
<li>originalColumn: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The column offset of start of the
range in the original source</li>
<li>name: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The returned value represents the raw range as it appears in the
SourceMap, based on zero-indexed offsets, <em>not</em> 1-indexed line and
column numbers as they appear in Error messages and CallSite
objects.</p>
<p>To get the corresponding 1-indexed line and column numbers from a
lineNumber and columnNumber as they are reported by Error stacks
and CallSite objects, use <code>sourceMap.findOrigin(lineNumber, columnNumber)</code></p>
<h5><code>sourceMap.findOrigin(lineNumber, columnNumber)</code><span><a class="mark" href="#all_module_sourcemapfindoriginlinenumber-columnnumber" id="all_module_sourcemapfindoriginlinenumber-columnnumber">#</a></span><a aria-hidden="true" class="legacy" id="module_sourcemap_findorigin_linenumber_columnnumber"></a></h5>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<ul>
<li><code>lineNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The 1-indexed line number of the call
site in the generated source</li>
<li><code>columnNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The 1-indexed column number
of the call site in the generated source</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Given a 1-indexed <code>lineNumber</code> and <code>columnNumber</code> from a call site in
the generated source, find the corresponding call site location
in the original source.</p>
<p>If the <code>lineNumber</code> and <code>columnNumber</code> provided are not found in any
source map, then an empty object is returned. Otherwise, the
returned object contains the following keys:</p>
<ul>
<li>name: <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#Undefined_type" class="type"><undefined></a> The name of the range in the
source map, if one was provided</li>
<li>fileName: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The file name of the original source, as
reported in the SourceMap</li>
<li>lineNumber: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The 1-indexed lineNumber of the
corresponding call site in the original source</li>
<li>columnNumber: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The 1-indexed columnNumber of the
corresponding call site in the original source</li>
</ul></section>
</section>
<section><h2>Modules: Packages<span><a class="mark" href="#all_packages_modules-packages" id="all_packages_modules-packages">#</a></span><a aria-hidden="true" class="legacy" id="packages_modules_packages"></a></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.13.0, v12.20.0</td>
<td><p>Add support for <code>"exports"</code> patterns.</p></td></tr>
<tr><td>v14.6.0, v12.19.0</td>
<td><p>Add package <code>"imports"</code> field.</p></td></tr>
<tr><td>v13.7.0, v12.17.0</td>
<td><p>Unflag conditional exports.</p></td></tr>
<tr><td>v13.7.0, v12.16.0</td>
<td><p>Remove the <code>--experimental-conditional-exports</code> option. In 12.16.0, conditional exports are still behind <code>--experimental-modules</code>.</p></td></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p>Unflag self-referencing a package using its name.</p></td></tr>
<tr><td>v12.7.0</td>
<td><p>Introduce <code>"exports"</code> <code>package.json</code> field as a more powerful alternative to the classic <code>"main"</code> field.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add support for ES modules using <code>.js</code> file extension via <code>package.json</code> <code>"type"</code> field.</p></td></tr>
</tbody></table>
</details>
</div>
<section><h3>Introduction<span><a class="mark" href="#all_packages_introduction" id="all_packages_introduction">#</a></span><a aria-hidden="true" class="legacy" id="packages_introduction"></a></h3>
<p>A package is a folder tree described by a <code>package.json</code> file. The package
consists of the folder containing the <code>package.json</code> file and all subfolders
until the next folder containing another <code>package.json</code> file, or a folder
named <code>node_modules</code>.</p>
<p>This page provides guidance for package authors writing <code>package.json</code> files
along with a reference for the <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> fields defined by Node.js.</p>
</section><section><h3>Determining module system<span><a class="mark" href="#all_packages_determining-module-system" id="all_packages_determining-module-system">#</a></span><a aria-hidden="true" class="legacy" id="packages_determining_module_system"></a></h3>
<h4>Introduction<span><a class="mark" href="#all_packages_introduction_1" id="all_packages_introduction_1">#</a></span><a aria-hidden="true" class="legacy" id="packages_introduction_1"></a></h4>
<p>Node.js will treat the following as <a href="esm.html">ES modules</a> when passed to <code>node</code> as the
initial input, or when referenced by <code>import</code> statements or <code>import()</code>
expressions:</p>
<ul>
<li>
<p>Files with an <code>.mjs</code> extension.</p>
</li>
<li>
<p>Files with a <code>.js</code> extension when the nearest parent <code>package.json</code> file
contains a top-level <a href="#all_packages_type"><code>"type"</code></a> field with a value of <code>"module"</code>.</p>
</li>
<li>
<p>Strings passed in as an argument to <code>--eval</code>, or piped to <code>node</code> via <code>STDIN</code>,
with the flag <code>--input-type=module</code>.</p>
</li>
<li>
<p>Code containing syntax only successfully parsed as <a href="esm.html">ES modules</a>, such as
<code>import</code> or <code>export</code> statements or <code>import.meta</code>, with no explicit marker of
how it should be interpreted. Explicit markers are <code>.mjs</code> or <code>.cjs</code>
extensions, <code>package.json</code> <code>"type"</code> fields with either <code>"module"</code> or
<code>"commonjs"</code> values, or <code>--input-type</code> or <code>--experimental-default-type</code> flags.
Dynamic <code>import()</code> expressions are supported in either CommonJS or ES modules
and would not force a file to be treated as an ES module. See
<a href="#all_packages_syntax-detection">Syntax detection</a>.</p>
</li>
</ul>
<p>Node.js will treat the following as <a href="modules.html">CommonJS</a> when passed to <code>node</code> as the
initial input, or when referenced by <code>import</code> statements or <code>import()</code>
expressions:</p>
<ul>
<li>
<p>Files with a <code>.cjs</code> extension.</p>
</li>
<li>
<p>Files with a <code>.js</code> extension when the nearest parent <code>package.json</code> file
contains a top-level field <a href="#all_packages_type"><code>"type"</code></a> with a value of <code>"commonjs"</code>.</p>
</li>
<li>
<p>Strings passed in as an argument to <code>--eval</code> or <code>--print</code>, or piped to <code>node</code>
via <code>STDIN</code>, with the flag <code>--input-type=commonjs</code>.</p>
</li>
</ul>
<p>Aside from these explicit cases, there are other cases where Node.js defaults to
one module system or the other based on the value of the
<a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type</code></a> flag:</p>
<ul>
<li>
<p>Files ending in <code>.js</code> or with no extension, if there is no <code>package.json</code> file
present in the same folder or any parent folder.</p>
</li>
<li>
<p>Files ending in <code>.js</code> or with no extension, if the nearest parent
<code>package.json</code> field lacks a <code>"type"</code> field; unless the folder is inside a
<code>node_modules</code> folder. (Package scopes under <code>node_modules</code> are always treated
as CommonJS when the <code>package.json</code> file lacks a <code>"type"</code> field, regardless
of <code>--experimental-default-type</code>, for backward compatibility.)</p>
</li>
<li>
<p>Strings passed in as an argument to <code>--eval</code> or piped to <code>node</code> via <code>STDIN</code>,
when <code>--input-type</code> is unspecified.</p>
</li>
</ul>
<p>This flag currently defaults to <code>"commonjs"</code>, but it may change in the future to
default to <code>"module"</code>. For this reason it is best to be explicit wherever
possible; in particular, package authors should always include the <a href="#all_packages_type"><code>"type"</code></a>
field in their <code>package.json</code> files, even in packages where all sources are
CommonJS. Being explicit about the <code>type</code> of the package will future-proof the
package in case the default type of Node.js ever changes, and it will also make
things easier for build tools and loaders to determine how the files in the
package should be interpreted.</p>
<h4>Syntax detection<span><a class="mark" href="#all_packages_syntax-detection" id="all_packages_syntax-detection">#</a></span><a aria-hidden="true" class="legacy" id="packages_syntax_detection"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.19.0</td>
<td><p>Syntax detection is enabled by default.</p></td></tr>
<tr><td>v21.1.0, v20.10.0</td>
<td><p><span>Added in: v21.1.0, v20.10.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<p>Node.js will inspect the source code of ambiguous input to determine whether it
contains ES module syntax; if such syntax is detected, the input will be treated
as an ES module.</p>
<p>Ambiguous input is defined as:</p>
<ul>
<li>Files with a <code>.js</code> extension or no extension; and either no controlling
<code>package.json</code> file or one that lacks a <code>type</code> field; and
<code>--experimental-default-type</code> is not specified.</li>
<li>String input (<code>--eval</code> or STDIN) when neither <code>--input-type</code> nor
<code>--experimental-default-type</code> are specified.</li>
</ul>
<p>ES module syntax is defined as syntax that would throw when evaluated as
CommonJS. This includes the following:</p>
<ul>
<li><code>import</code> statements (but <em>not</em> <code>import()</code> expressions, which are valid in
CommonJS).</li>
<li><code>export</code> statements.</li>
<li><code>import.meta</code> references.</li>
<li><code>await</code> at the top level of a module.</li>
<li>Lexical redeclarations of the CommonJS wrapper variables (<code>require</code>, <code>module</code>,
<code>exports</code>, <code>__dirname</code>, <code>__filename</code>).</li>
</ul>
<h4>Modules loaders<span><a class="mark" href="#all_packages_modules-loaders" id="all_packages_modules-loaders">#</a></span><a aria-hidden="true" class="legacy" id="packages_modules_loaders"></a></h4>
<p>Node.js has two systems for resolving a specifier and loading modules.</p>
<p>There is the CommonJS module loader:</p>
<ul>
<li>It is fully synchronous.</li>
<li>It is responsible for handling <code>require()</code> calls.</li>
<li>It is monkey patchable.</li>
<li>It supports <a href="#all_modules_folders-as-modules">folders as modules</a>.</li>
<li>When resolving a specifier, if no exact match is found, it will try to add
extensions (<code>.js</code>, <code>.json</code>, and finally <code>.node</code>) and then attempt to resolve
<a href="#all_modules_folders-as-modules">folders as modules</a>.</li>
<li>It treats <code>.json</code> as JSON text files.</li>
<li><code>.node</code> files are interpreted as compiled addon modules loaded with
<code>process.dlopen()</code>.</li>
<li>It treats all files that lack <code>.json</code> or <code>.node</code> extensions as JavaScript
text files.</li>
<li>It can only be used to <a href="#all_modules_loading-ecmascript-modules-using-require">load ECMASCript modules from CommonJS modules</a> if
the module graph is synchronous (that contains no top-level <code>await</code>).
When used to load a JavaScript text file that is not an ECMAScript module,
the file will be loaded as a CommonJS module.</li>
</ul>
<p>There is the ECMAScript module loader:</p>
<ul>
<li>It is asynchronous, unless it's being used to load modules for <code>require()</code>.</li>
<li>It is responsible for handling <code>import</code> statements and <code>import()</code> expressions.</li>
<li>It is not monkey patchable, can be customized using <a href="#all_esm_loaders">loader hooks</a>.</li>
<li>It does not support folders as modules, directory indexes (e.g.
<code>'./startup/index.js'</code>) must be fully specified.</li>
<li>It does no extension searching. A file extension must be provided
when the specifier is a relative or absolute file URL.</li>
<li>It can load JSON modules, but an import assertion is required.</li>
<li>It accepts only <code>.js</code>, <code>.mjs</code>, and <code>.cjs</code> extensions for JavaScript text
files.</li>
<li>It can be used to load JavaScript CommonJS modules. Such modules
are passed through the <code>cjs-module-lexer</code> to try to identify named exports,
which are available if they can be determined through static analysis.
Imported CommonJS modules have their URLs converted to absolute
paths and are then loaded via the CommonJS module loader.</li>
</ul>
<h4><code>package.json</code> and file extensions<span><a class="mark" href="#all_packages_packagejson-and-file-extensions" id="all_packages_packagejson-and-file-extensions">#</a></span><a aria-hidden="true" class="legacy" id="packages_package_json_and_file_extensions"></a></h4>
<p>Within a package, the <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> <a href="#all_packages_type"><code>"type"</code></a> field defines how
Node.js should interpret <code>.js</code> files. If a <code>package.json</code> file does not have a
<code>"type"</code> field, <code>.js</code> files are treated as <a href="modules.html">CommonJS</a>.</p>
<p>A <code>package.json</code> <code>"type"</code> value of <code>"module"</code> tells Node.js to interpret <code>.js</code>
files within that package as using <a href="esm.html">ES module</a> syntax.</p>
<p>The <code>"type"</code> field applies not only to initial entry points (<code>node my-app.js</code>)
but also to files referenced by <code>import</code> statements and <code>import()</code> expressions.</p>
<pre><code class="language-js"><span class="hljs-comment">// my-app.js, treated as an ES module because there is a package.json</span>
<span class="hljs-comment">// file in the same folder with "type": "module".</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./startup/init.js'</span>;
<span class="hljs-comment">// Loaded as ES module since ./startup contains no package.json file,</span>
<span class="hljs-comment">// and therefore inherits the "type" value from one level up.</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'commonjs-package'</span>;
<span class="hljs-comment">// Loaded as CommonJS since ./node_modules/commonjs-package/package.json</span>
<span class="hljs-comment">// lacks a "type" field or contains "type": "commonjs".</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./node_modules/commonjs-package/index.js'</span>;
<span class="hljs-comment">// Loaded as CommonJS since ./node_modules/commonjs-package/package.json</span>
<span class="hljs-comment">// lacks a "type" field or contains "type": "commonjs".</span></code> <button class="copy-button">copy</button></pre>
<p>Files ending with <code>.mjs</code> are always loaded as <a href="esm.html">ES modules</a> regardless of
the nearest parent <code>package.json</code>.</p>
<p>Files ending with <code>.cjs</code> are always loaded as <a href="modules.html">CommonJS</a> regardless of the
nearest parent <code>package.json</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'./legacy-file.cjs'</span>;
<span class="hljs-comment">// Loaded as CommonJS since .cjs is always loaded as CommonJS.</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'commonjs-package/src/index.mjs'</span>;
<span class="hljs-comment">// Loaded as ES module since .mjs is always loaded as ES module.</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>.mjs</code> and <code>.cjs</code> extensions can be used to mix types within the same
package:</p>
<ul>
<li>
<p>Within a <code>"type": "module"</code> package, Node.js can be instructed to
interpret a particular file as <a href="modules.html">CommonJS</a> by naming it with a <code>.cjs</code>
extension (since both <code>.js</code> and <code>.mjs</code> files are treated as ES modules within
a <code>"module"</code> package).</p>
</li>
<li>
<p>Within a <code>"type": "commonjs"</code> package, Node.js can be instructed to
interpret a particular file as an <a href="esm.html">ES module</a> by naming it with an <code>.mjs</code>
extension (since both <code>.js</code> and <code>.cjs</code> files are treated as CommonJS within a
<code>"commonjs"</code> package).</p>
</li>
</ul>
<h4><code>--input-type</code> flag<span><a class="mark" href="#all_packages_--input-type-flag" id="all_packages_--input-type-flag">#</a></span><a aria-hidden="true" class="legacy" id="packages_input_type_flag"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Strings passed in as an argument to <code>--eval</code> (or <code>-e</code>), or piped to <code>node</code> via
<code>STDIN</code>, are treated as <a href="esm.html">ES modules</a> when the <code>--input-type=module</code> flag
is set.</p>
<pre><code class="language-bash">node --input-type=module --<span class="hljs-built_in">eval</span> <span class="hljs-string">"import { sep } from 'node:path'; console.log(sep);"</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"import { sep } from 'node:path'; console.log(sep);"</span> | node --input-type=module</code> <button class="copy-button">copy</button></pre>
<p>For completeness there is also <code>--input-type=commonjs</code>, for explicitly running
string input as CommonJS. This is the default behavior if <code>--input-type</code> is
unspecified.</p>
</section><section><h3>Determining package manager<span><a class="mark" href="#all_packages_determining-package-manager" id="all_packages_determining-package-manager">#</a></span><a aria-hidden="true" class="legacy" id="packages_determining_package_manager"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>While all Node.js projects are expected to be installable by all package
managers once published, their development teams are often required to use one
specific package manager. To make this process easier, Node.js ships with a
tool called <a href="corepack.html">Corepack</a> that aims to make all package managers transparently
available in your environment - provided you have Node.js installed.</p>
<p>By default Corepack won't enforce any specific package manager and will use
the generic "Last Known Good" versions associated with each Node.js release,
but you can improve this experience by setting the <a href="#all_packages_packagemanager"><code>"packageManager"</code></a> field
in your project's <code>package.json</code>.</p>
</section><section><h3>Package entry points<span><a class="mark" href="#all_packages_package-entry-points" id="all_packages_package-entry-points">#</a></span><a aria-hidden="true" class="legacy" id="packages_package_entry_points"></a></h3>
<p>In a package's <code>package.json</code> file, two fields can define entry points for a
package: <a href="#all_packages_main"><code>"main"</code></a> and <a href="#all_packages_exports"><code>"exports"</code></a>. Both fields apply to both ES module
and CommonJS module entry points.</p>
<p>The <a href="#all_packages_main"><code>"main"</code></a> field is supported in all versions of Node.js, but its
capabilities are limited: it only defines the main entry point of the package.</p>
<p>The <a href="#all_packages_exports"><code>"exports"</code></a> provides a modern alternative to <a href="#all_packages_main"><code>"main"</code></a> allowing
multiple entry points to be defined, conditional entry resolution support
between environments, and <strong>preventing any other entry points besides those
defined in <a href="#all_packages_exports"><code>"exports"</code></a></strong>. This encapsulation allows module authors to
clearly define the public interface for their package.</p>
<p>For new packages targeting the currently supported versions of Node.js, the
<a href="#all_packages_exports"><code>"exports"</code></a> field is recommended. For packages supporting Node.js 10 and
below, the <a href="#all_packages_main"><code>"main"</code></a> field is required. If both <a href="#all_packages_exports"><code>"exports"</code></a> and
<a href="#all_packages_main"><code>"main"</code></a> are defined, the <a href="#all_packages_exports"><code>"exports"</code></a> field takes precedence over
<a href="#all_packages_main"><code>"main"</code></a> in supported versions of Node.js.</p>
<p><a href="#all_packages_conditional-exports">Conditional exports</a> can be used within <a href="#all_packages_exports"><code>"exports"</code></a> to define different
package entry points per environment, including whether the package is
referenced via <code>require</code> or via <code>import</code>. For more information about supporting
both CommonJS and ES modules in a single package please consult
<a href="#all_packages_dual-commonjses-module-packages">the dual CommonJS/ES module packages section</a>.</p>
<p>Existing packages introducing the <a href="#all_packages_exports"><code>"exports"</code></a> field will prevent consumers
of the package from using any entry points that are not defined, including the
<a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> (e.g. <code>require('your-package/package.json')</code>). <strong>This will
likely be a breaking change.</strong></p>
<p>To make the introduction of <a href="#all_packages_exports"><code>"exports"</code></a> non-breaking, ensure that every
previously supported entry point is exported. It is best to explicitly specify
entry points so that the package's public API is well-defined. For example,
a project that previously exported <code>main</code>, <code>lib</code>,
<code>feature</code>, and the <code>package.json</code> could use the following <code>package.exports</code>:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"my-package"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./lib"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./lib/index"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./lib/index.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./feature"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./feature/index"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./feature/index.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./package.json"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./package.json"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Alternatively a project could choose to export entire folders both with and
without extensioned subpaths using export patterns:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"my-package"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./lib"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./lib/*"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/*.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./lib/*.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/*.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./feature"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./feature/*"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/*.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./feature/*.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/*.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./package.json"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./package.json"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>With the above providing backwards-compatibility for any minor package versions,
a future major change for the package can then properly restrict the exports
to only the specific feature exports exposed:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"my-package"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./feature/*.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/*.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./feature/internal/*"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">null</span></span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h4>Main entry point export<span><a class="mark" href="#all_packages_main-entry-point-export" id="all_packages_main-entry-point-export">#</a></span><a aria-hidden="true" class="legacy" id="packages_main_entry_point_export"></a></h4>
<p>When writing a new package, it is recommended to use the <a href="#all_packages_exports"><code>"exports"</code></a> field:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>When the <a href="#all_packages_exports"><code>"exports"</code></a> field is defined, all subpaths of the package are
encapsulated and no longer available to importers. For example,
<code>require('pkg/subpath.js')</code> throws an <a href="#all_errors_err_package_path_not_exported"><code>ERR_PACKAGE_PATH_NOT_EXPORTED</code></a>
error.</p>
<p>This encapsulation of exports provides more reliable guarantees
about package interfaces for tools and when handling semver upgrades for a
package. It is not a strong encapsulation since a direct require of any
absolute subpath of the package such as
<code>require('/path/to/node_modules/pkg/subpath.js')</code> will still load <code>subpath.js</code>.</p>
<p>All currently supported versions of Node.js and modern build tools support the
<code>"exports"</code> field. For projects using an older version of Node.js or a related
build tool, compatibility can be achieved by including the <code>"main"</code> field
alongside <code>"exports"</code> pointing to the same module:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"main"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h4>Subpath exports<span><a class="mark" href="#all_packages_subpath-exports" id="all_packages_subpath-exports">#</a></span><a aria-hidden="true" class="legacy" id="packages_subpath_exports"></a></h4>
<div class="api_metadata">
<span>Added in: v12.7.0</span>
</div>
<p>When using the <a href="#all_packages_exports"><code>"exports"</code></a> field, custom subpaths can be defined along
with the main entry point by treating the main entry point as the
<code>"."</code> subpath:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./submodule.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./src/submodule.js"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Now only the defined subpath in <a href="#all_packages_exports"><code>"exports"</code></a> can be imported by a consumer:</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> submodule <span class="hljs-keyword">from</span> <span class="hljs-string">'es-module-package/submodule.js'</span>;
<span class="hljs-comment">// Loads ./node_modules/es-module-package/src/submodule.js</span></code> <button class="copy-button">copy</button></pre>
<p>While other subpaths will error:</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> submodule <span class="hljs-keyword">from</span> <span class="hljs-string">'es-module-package/private-module.js'</span>;
<span class="hljs-comment">// Throws ERR_PACKAGE_PATH_NOT_EXPORTED</span></code> <button class="copy-button">copy</button></pre>
<h5>Extensions in subpaths<span><a class="mark" href="#all_packages_extensions-in-subpaths" id="all_packages_extensions-in-subpaths">#</a></span><a aria-hidden="true" class="legacy" id="packages_extensions_in_subpaths"></a></h5>
<p>Package authors should provide either extensioned (<code>import 'pkg/subpath.js'</code>) or
extensionless (<code>import 'pkg/subpath'</code>) subpaths in their exports. This ensures
that there is only one subpath for each exported module so that all dependents
import the same consistent specifier, keeping the package contract clear for
consumers and simplifying package subpath completions.</p>
<p>Traditionally, packages tended to use the extensionless style, which has the
benefits of readability and of masking the true path of the file within the
package.</p>
<p>With <a href="https://github.com/WICG/import-maps">import maps</a> now providing a standard for package resolution in browsers
and other JavaScript runtimes, using the extensionless style can result in
bloated import map definitions. Explicit file extensions can avoid this issue by
enabling the import map to utilize a <a href="https://github.com/WICG/import-maps#packages-via-trailing-slashes">packages folder mapping</a> to map multiple
subpaths where possible instead of a separate map entry per package subpath
export. This also mirrors the requirement of using <a href="#all_esm_mandatory-file-extensions">the full specifier path</a>
in relative and absolute import specifiers.</p>
<h4>Exports sugar<span><a class="mark" href="#all_packages_exports-sugar" id="all_packages_exports-sugar">#</a></span><a aria-hidden="true" class="legacy" id="packages_exports_sugar"></a></h4>
<div class="api_metadata">
<span>Added in: v12.11.0</span>
</div>
<p>If the <code>"."</code> export is the only export, the <a href="#all_packages_exports"><code>"exports"</code></a> field provides sugar
for this case being the direct <a href="#all_packages_exports"><code>"exports"</code></a> field value.</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>can be written:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h4>Subpath imports<span><a class="mark" href="#all_packages_subpath-imports" id="all_packages_subpath-imports">#</a></span><a aria-hidden="true" class="legacy" id="packages_subpath_imports"></a></h4>
<div class="api_metadata">
<span>Added in: v14.6.0, v12.19.0</span>
</div>
<p>In addition to the <a href="#all_packages_exports"><code>"exports"</code></a> field, there is a package <code>"imports"</code> field
to create private mappings that only apply to import specifiers from within the
package itself.</p>
<p>Entries in the <code>"imports"</code> field must always start with <code>#</code> to ensure they are
disambiguated from external package specifiers.</p>
<p>For example, the imports field can be used to gain the benefits of conditional
exports for internal modules:</p>
<pre><code class="language-json"><span class="hljs-comment">// package.json</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"#dep"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"node"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"dep-node-native"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"default"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./dep-polyfill.js"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"dep-node-native"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"^1.0.0"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>where <code>import '#dep'</code> does not get the resolution of the external package
<code>dep-node-native</code> (including its exports in turn), and instead gets the local
file <code>./dep-polyfill.js</code> relative to the package in other environments.</p>
<p>Unlike the <code>"exports"</code> field, the <code>"imports"</code> field permits mapping to external
packages.</p>
<p>The resolution rules for the imports field are otherwise analogous to the
exports field.</p>
<h4>Subpath patterns<span><a class="mark" href="#all_packages_subpath-patterns" id="all_packages_subpath-patterns">#</a></span><a aria-hidden="true" class="legacy" id="packages_subpath_patterns"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.10.0, v14.19.0</td>
<td><p>Support pattern trailers in "imports" field.</p></td></tr>
<tr><td>v16.9.0, v14.19.0</td>
<td><p>Support pattern trailers.</p></td></tr>
<tr><td>v14.13.0, v12.20.0</td>
<td><p><span>Added in: v14.13.0, v12.20.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>For packages with a small number of exports or imports, we recommend
explicitly listing each exports subpath entry. But for packages that have
large numbers of subpaths, this might cause <code>package.json</code> bloat and
maintenance issues.</p>
<p>For these use cases, subpath export patterns can be used instead:</p>
<pre><code class="language-json"><span class="hljs-comment">// ./node_modules/es-module-package/package.json</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"./features/*.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./src/features/*.js"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"#internal/*.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./src/internal/*.js"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p><strong><code>*</code> maps expose nested subpaths as it is a string replacement syntax
only.</strong></p>
<p>All instances of <code>*</code> on the right hand side will then be replaced with this
value, including if it contains any <code>/</code> separators.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> featureX <span class="hljs-keyword">from</span> <span class="hljs-string">'es-module-package/features/x.js'</span>;
<span class="hljs-comment">// Loads ./node_modules/es-module-package/src/features/x.js</span>
<span class="hljs-keyword">import</span> featureY <span class="hljs-keyword">from</span> <span class="hljs-string">'es-module-package/features/y/y.js'</span>;
<span class="hljs-comment">// Loads ./node_modules/es-module-package/src/features/y/y.js</span>
<span class="hljs-keyword">import</span> internalZ <span class="hljs-keyword">from</span> <span class="hljs-string">'#internal/z.js'</span>;
<span class="hljs-comment">// Loads ./node_modules/es-module-package/src/internal/z.js</span></code> <button class="copy-button">copy</button></pre>
<p>This is a direct static matching and replacement without any special handling
for file extensions. Including the <code>"*.js"</code> on both sides of the mapping
restricts the exposed package exports to only JS files.</p>
<p>The property of exports being statically enumerable is maintained with exports
patterns since the individual exports for a package can be determined by
treating the right hand side target pattern as a <code>**</code> glob against the list of
files within the package. Because <code>node_modules</code> paths are forbidden in exports
targets, this expansion is dependent on only the files of the package itself.</p>
<p>To exclude private subfolders from patterns, <code>null</code> targets can be used:</p>
<pre><code class="language-json"><span class="hljs-comment">// ./node_modules/es-module-package/package.json</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"./features/*.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./src/features/*.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./features/private-internal/*"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">null</span></span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">import</span> featureInternal <span class="hljs-keyword">from</span> <span class="hljs-string">'es-module-package/features/private-internal/m.js'</span>;
<span class="hljs-comment">// Throws: ERR_PACKAGE_PATH_NOT_EXPORTED</span>
<span class="hljs-keyword">import</span> featureX <span class="hljs-keyword">from</span> <span class="hljs-string">'es-module-package/features/x.js'</span>;
<span class="hljs-comment">// Loads ./node_modules/es-module-package/src/features/x.js</span></code> <button class="copy-button">copy</button></pre>
<h4>Conditional exports<span><a class="mark" href="#all_packages_conditional-exports" id="all_packages_conditional-exports">#</a></span><a aria-hidden="true" class="legacy" id="packages_conditional_exports"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.7.0, v12.16.0</td>
<td><p>Unflag conditional exports.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p><span>Added in: v13.2.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Conditional exports provide a way to map to different paths depending on
certain conditions. They are supported for both CommonJS and ES module imports.</p>
<p>For example, a package that wants to provide different ES module exports for
<code>require()</code> and <code>import</code> can be written:</p>
<pre><code class="language-json"><span class="hljs-comment">// package.json</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"import"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index-module.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"require"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index-require.cjs"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"module"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Node.js implements the following conditions, listed in order from most
specific to least specific as conditions should be defined:</p>
<ul>
<li><code>"node-addons"</code> - similar to <code>"node"</code> and matches for any Node.js environment.
This condition can be used to provide an entry point which uses native C++
addons as opposed to an entry point which is more universal and doesn't rely
on native addons. This condition can be disabled via the
<a href="#all_cli_--no-addons"><code>--no-addons</code> flag</a>.</li>
<li><code>"node"</code> - matches for any Node.js environment. Can be a CommonJS or ES
module file. <em>In most cases explicitly calling out the Node.js platform is
not necessary.</em></li>
<li><code>"import"</code> - matches when the package is loaded via <code>import</code> or
<code>import()</code>, or via any top-level import or resolve operation by the
ECMAScript module loader. Applies regardless of the module format of the
target file. <em>Always mutually exclusive with <code>"require"</code>.</em></li>
<li><code>"require"</code> - matches when the package is loaded via <code>require()</code>. The
referenced file should be loadable with <code>require()</code> although the condition
matches regardless of the module format of the target file. Expected
formats include CommonJS, JSON, native addons, and ES modules. <em>Always mutually
exclusive with <code>"import"</code>.</em></li>
<li><code>"module-sync"</code> - matches no matter the package is loaded via <code>import</code>,
<code>import()</code> or <code>require()</code>. The format is expected to be ES modules that does
not contain top-level await in its module graph - if it does,
<code>ERR_REQUIRE_ASYNC_MODULE</code> will be thrown when the module is <code>require()</code>-ed.</li>
<li><code>"default"</code> - the generic fallback that always matches. Can be a CommonJS
or ES module file. <em>This condition should always come last.</em></li>
</ul>
<p>Within the <a href="#all_packages_exports"><code>"exports"</code></a> object, key order is significant. During condition
matching, earlier entries have higher priority and take precedence over later
entries. <em>The general rule is that conditions should be from most specific to
least specific in object order</em>.</p>
<p>Using the <code>"import"</code> and <code>"require"</code> conditions can lead to some hazards,
which are further explained in <a href="#all_packages_dual-commonjses-module-packages">the dual CommonJS/ES module packages section</a>.</p>
<p>The <code>"node-addons"</code> condition can be used to provide an entry point which
uses native C++ addons. However, this condition can be disabled via the
<a href="#all_cli_--no-addons"><code>--no-addons</code> flag</a>. When using <code>"node-addons"</code>, it's recommended to treat
<code>"default"</code> as an enhancement that provides a more universal entry point, e.g.
using WebAssembly instead of a native addon.</p>
<p>Conditional exports can also be extended to exports subpaths, for example:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./feature.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"node"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature-node.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"default"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature.js"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Defines a package where <code>require('pkg/feature.js')</code> and
<code>import 'pkg/feature.js'</code> could provide different implementations between
Node.js and other JS environments.</p>
<p>When using environment branches, always include a <code>"default"</code> condition where
possible. Providing a <code>"default"</code> condition ensures that any unknown JS
environments are able to use this universal implementation, which helps avoid
these JS environments from having to pretend to be existing environments in
order to support packages with conditional exports. For this reason, using
<code>"node"</code> and <code>"default"</code> condition branches is usually preferable to using
<code>"node"</code> and <code>"browser"</code> condition branches.</p>
<h4>Nested conditions<span><a class="mark" href="#all_packages_nested-conditions" id="all_packages_nested-conditions">#</a></span><a aria-hidden="true" class="legacy" id="packages_nested_conditions"></a></h4>
<p>In addition to direct mappings, Node.js also supports nested condition objects.</p>
<p>For example, to define a package that only has dual mode entry points for
use in Node.js but not the browser:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"node"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"import"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature-node.mjs"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"require"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature-node.cjs"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"default"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature.mjs"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Conditions continue to be matched in order as with flat conditions. If
a nested condition does not have any mapping it will continue checking
the remaining conditions of the parent condition. In this way nested
conditions behave analogously to nested JavaScript <code>if</code> statements.</p>
<h4>Resolving user conditions<span><a class="mark" href="#all_packages_resolving-user-conditions" id="all_packages_resolving-user-conditions">#</a></span><a aria-hidden="true" class="legacy" id="packages_resolving_user_conditions"></a></h4>
<div class="api_metadata">
<span>Added in: v14.9.0, v12.19.0</span>
</div>
<p>When running Node.js, custom user conditions can be added with the
<code>--conditions</code> flag:</p>
<pre><code class="language-bash">node --conditions=development index.js</code> <button class="copy-button">copy</button></pre>
<p>which would then resolve the <code>"development"</code> condition in package imports and
exports, while resolving the existing <code>"node"</code>, <code>"node-addons"</code>, <code>"default"</code>,
<code>"import"</code>, and <code>"require"</code> conditions as appropriate.</p>
<p>Any number of custom conditions can be set with repeat flags.</p>
<p>Typical conditions should only contain alphanumerical characters,
using ":", "-", or "=" as separators if necessary. Anything else may run
into compability issues outside of node.</p>
<p>In node, conditions have very few restrictions, but specifically these include:</p>
<ol>
<li>They must contain at least one character.</li>
<li>They cannot start with "." since they may appear in places that also
allow relative paths.</li>
<li>They cannot contain "," since they may be parsed as a comma-separated
list by some CLI tools.</li>
<li>They cannot be integer property keys like "10" since that can have
unexpected effects on property key ordering for JS objects.</li>
</ol>
<h4>Community Conditions Definitions<span><a class="mark" href="#all_packages_community-conditions-definitions" id="all_packages_community-conditions-definitions">#</a></span><a aria-hidden="true" class="legacy" id="packages_community_conditions_definitions"></a></h4>
<p>Condition strings other than the <code>"import"</code>, <code>"require"</code>, <code>"node"</code>, <code>"module-sync"</code>,
<code>"node-addons"</code> and <code>"default"</code> conditions
<a href="#all_packages_conditional-exports">implemented in Node.js core</a> are ignored by default.</p>
<p>Other platforms may implement other conditions and user conditions can be
enabled in Node.js via the <a href="#all_packages_resolving-user-conditions"><code>--conditions</code> / <code>-C</code> flag</a>.</p>
<p>Since custom package conditions require clear definitions to ensure correct
usage, a list of common known package conditions and their strict definitions
is provided below to assist with ecosystem coordination.</p>
<ul>
<li><code>"types"</code> - can be used by typing systems to resolve the typing file for
the given export. <em>This condition should always be included first.</em></li>
<li><code>"browser"</code> - any web browser environment.</li>
<li><code>"development"</code> - can be used to define a development-only environment
entry point, for example to provide additional debugging context such as
better error messages when running in a development mode. <em>Must always be
mutually exclusive with <code>"production"</code>.</em></li>
<li><code>"production"</code> - can be used to define a production environment entry
point. <em>Must always be mutually exclusive with <code>"development"</code>.</em></li>
</ul>
<p>For other runtimes, platform-specific condition key definitions are maintained
by the <a href="https://wintercg.org/">WinterCG</a> in the <a href="https://runtime-keys.proposal.wintercg.org/">Runtime Keys</a> proposal specification.</p>
<p>New conditions definitions may be added to this list by creating a pull request
to the <a href="https://github.com/nodejs/node/blob/HEAD/doc/api/packages.md#conditions-definitions">Node.js documentation for this section</a>. The requirements for listing
a new condition definition here are that:</p>
<ul>
<li>The definition should be clear and unambiguous for all implementers.</li>
<li>The use case for why the condition is needed should be clearly justified.</li>
<li>There should exist sufficient existing implementation usage.</li>
<li>The condition name should not conflict with another condition definition or
condition in wide usage.</li>
<li>The listing of the condition definition should provide a coordination
benefit to the ecosystem that wouldn't otherwise be possible. For example,
this would not necessarily be the case for company-specific or
application-specific conditions.</li>
<li>The condition should be such that a Node.js user would expect it to be in
Node.js core documentation. The <code>"types"</code> condition is a good example: It
doesn't really belong in the <a href="https://runtime-keys.proposal.wintercg.org/">Runtime Keys</a> proposal but is a good fit
here in the Node.js docs.</li>
</ul>
<p>The above definitions may be moved to a dedicated conditions registry in due
course.</p>
<h4>Self-referencing a package using its name<span><a class="mark" href="#all_packages_self-referencing-a-package-using-its-name" id="all_packages_self-referencing-a-package-using-its-name">#</a></span><a aria-hidden="true" class="legacy" id="packages_self_referencing_a_package_using_its_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p>Unflag self-referencing a package using its name.</p></td></tr>
<tr><td>v13.1.0, v12.16.0</td>
<td><p><span>Added in: v13.1.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Within a package, the values defined in the package's
<code>package.json</code> <a href="#all_packages_exports"><code>"exports"</code></a> field can be referenced via the package's name.
For example, assuming the <code>package.json</code> is:</p>
<pre><code class="language-json"><span class="hljs-comment">// package.json</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"a-package"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.mjs"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./foo.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./foo.js"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Then any module <em>in that package</em> can reference an export in the package itself:</p>
<pre><code class="language-js"><span class="hljs-comment">// ./a-module.mjs</span>
<span class="hljs-keyword">import</span> { something } <span class="hljs-keyword">from</span> <span class="hljs-string">'a-package'</span>; <span class="hljs-comment">// Imports "something" from ./index.mjs.</span></code> <button class="copy-button">copy</button></pre>
<p>Self-referencing is available only if <code>package.json</code> has <a href="#all_packages_exports"><code>"exports"</code></a>, and
will allow importing only what that <a href="#all_packages_exports"><code>"exports"</code></a> (in the <code>package.json</code>)
allows. So the code below, given the previous package, will generate a runtime
error:</p>
<pre><code class="language-js"><span class="hljs-comment">// ./another-module.mjs</span>
<span class="hljs-comment">// Imports "another" from ./m.mjs. Fails because</span>
<span class="hljs-comment">// the "package.json" "exports" field</span>
<span class="hljs-comment">// does not provide an export named "./m.mjs".</span>
<span class="hljs-keyword">import</span> { another } <span class="hljs-keyword">from</span> <span class="hljs-string">'a-package/m.mjs'</span>;</code> <button class="copy-button">copy</button></pre>
<p>Self-referencing is also available when using <code>require</code>, both in an ES module,
and in a CommonJS one. For example, this code will also work:</p>
<pre><code class="language-js cjs"><span class="hljs-comment">// ./a-module.js</span>
<span class="hljs-keyword">const</span> { something } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'a-package/foo.js'</span>); <span class="hljs-comment">// Loads from ./foo.js.</span></code> <button class="copy-button">copy</button></pre>
<p>Finally, self-referencing also works with scoped packages. For example, this
code will also work:</p>
<pre><code class="language-json"><span class="hljs-comment">// package.json</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"@my/package"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js cjs"><span class="hljs-comment">// ./index.js</span>
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-number">42</span>;</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js cjs"><span class="hljs-comment">// ./other.js</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'@my/package'</span>));</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node other.js</span>
42</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Dual CommonJS/ES module packages<span><a class="mark" href="#all_packages_dual-commonjses-module-packages" id="all_packages_dual-commonjses-module-packages">#</a></span><a aria-hidden="true" class="legacy" id="packages_dual_commonjs_es_module_packages"></a></h3>
<p>See <a href="https://github.com/nodejs/package-examples">the package examples repository</a> for details.</p>
</section><section><h3>Node.js <code>package.json</code> field definitions<span><a class="mark" href="#all_packages_nodejs-packagejson-field-definitions" id="all_packages_nodejs-packagejson-field-definitions">#</a></span><a aria-hidden="true" class="legacy" id="packages_node_js_package_json_field_definitions"></a></h3>
<p>This section describes the fields used by the Node.js runtime. Other tools (such
as <a href="https://docs.npmjs.com/cli/v8/configuring-npm/package-json">npm</a>) use
additional fields which are ignored by Node.js and not documented here.</p>
<p>The following fields in <code>package.json</code> files are used in Node.js:</p>
<ul>
<li><a href="#all_packages_name"><code>"name"</code></a> - Relevant when using named imports within a package. Also used
by package managers as the name of the package.</li>
<li><a href="#all_packages_main"><code>"main"</code></a> - The default module when loading the package, if exports is not
specified, and in versions of Node.js prior to the introduction of exports.</li>
<li><a href="#all_packages_packagemanager"><code>"packageManager"</code></a> - The package manager recommended when contributing to
the package. Leveraged by the <a href="corepack.html">Corepack</a> shims.</li>
<li><a href="#all_packages_type"><code>"type"</code></a> - The package type determining whether to load <code>.js</code> files as
CommonJS or ES modules.</li>
<li><a href="#all_packages_exports"><code>"exports"</code></a> - Package exports and conditional exports. When present,
limits which submodules can be loaded from within the package.</li>
<li><a href="#all_packages_imports"><code>"imports"</code></a> - Package imports, for use by modules within the package
itself.</li>
</ul>
<h4><code>"name"</code><span><a class="mark" href="#all_packages_name" id="all_packages_name">#</a></span><a aria-hidden="true" class="legacy" id="packages_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p>Remove the <code>--experimental-resolve-self</code> option.</p></td></tr>
<tr><td>v13.1.0, v12.16.0</td>
<td><p><span>Added in: v13.1.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"package-name"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>"name"</code> field defines your package's name. Publishing to the
<em>npm</em> registry requires a name that satisfies
<a href="https://docs.npmjs.com/files/package.json#name">certain requirements</a>.</p>
<p>The <code>"name"</code> field can be used in addition to the <a href="#all_packages_exports"><code>"exports"</code></a> field to
<a href="#all_packages_self-referencing-a-package-using-its-name">self-reference</a> a package using its name.</p>
<h4><code>"main"</code><span><a class="mark" href="#all_packages_main" id="all_packages_main">#</a></span><a aria-hidden="true" class="legacy" id="packages_main"></a></h4>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"main"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>"main"</code> field defines the entry point of a package when imported by name
via a <code>node_modules</code> lookup. Its value is a path.</p>
<p>When a package has an <a href="#all_packages_exports"><code>"exports"</code></a> field, this will take precedence over the
<code>"main"</code> field when importing the package by name.</p>
<p>It also defines the script that is used when the <a href="#all_modules_folders-as-modules">package directory is loaded
via <code>require()</code></a>.</p>
<pre><code class="language-js cjs"><span class="hljs-comment">// This resolves to ./path/to/directory/index.js.</span>
<span class="hljs-built_in">require</span>(<span class="hljs-string">'./path/to/directory'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>"packageManager"</code><span><a class="mark" href="#all_packages_packagemanager" id="all_packages_packagemanager">#</a></span><a aria-hidden="true" class="legacy" id="packages_packagemanager"></a></h4>
<div class="api_metadata">
<span>Added in: v16.9.0, v14.19.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"packageManager"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"<package manager name>@<version>"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>"packageManager"</code> field defines which package manager is expected to be
used when working on the current project. It can be set to any of the
<a href="#all_corepack_supported-package-managers">supported package managers</a>, and will ensure that your teams use the exact
same package manager versions without having to install anything else other than
Node.js.</p>
<p>This field is currently experimental and needs to be opted-in; check the
<a href="corepack.html">Corepack</a> page for details about the procedure.</p>
<h4><code>"type"</code><span><a class="mark" href="#all_packages_type" id="all_packages_type">#</a></span><a aria-hidden="true" class="legacy" id="packages_type"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.2.0, v12.17.0</td>
<td><p>Unflag <code>--experimental-modules</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p><span>Added in: v12.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>"type"</code> field defines the module format that Node.js uses for all
<code>.js</code> files that have that <code>package.json</code> file as their nearest parent.</p>
<p>Files ending with <code>.js</code> are loaded as ES modules when the nearest parent
<code>package.json</code> file contains a top-level field <code>"type"</code> with a value of
<code>"module"</code>.</p>
<p>The nearest parent <code>package.json</code> is defined as the first <code>package.json</code> found
when searching in the current folder, that folder's parent, and so on up
until a node_modules folder or the volume root is reached.</p>
<pre><code class="language-json"><span class="hljs-comment">// package.json</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"module"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-bash"><span class="hljs-comment"># In same folder as preceding package.json</span>
node my-app.js <span class="hljs-comment"># Runs as ES module</span></code> <button class="copy-button">copy</button></pre>
<p>If the nearest parent <code>package.json</code> lacks a <code>"type"</code> field, or contains
<code>"type": "commonjs"</code>, <code>.js</code> files are treated as <a href="modules.html">CommonJS</a>. If the volume
root is reached and no <code>package.json</code> is found, <code>.js</code> files are treated as
<a href="modules.html">CommonJS</a>.</p>
<p><code>import</code> statements of <code>.js</code> files are treated as ES modules if the nearest
parent <code>package.json</code> contains <code>"type": "module"</code>.</p>
<pre><code class="language-js"><span class="hljs-comment">// my-app.js, part of the same example as above</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./startup.js'</span>; <span class="hljs-comment">// Loaded as ES module because of package.json</span></code> <button class="copy-button">copy</button></pre>
<p>Regardless of the value of the <code>"type"</code> field, <code>.mjs</code> files are always treated
as ES modules and <code>.cjs</code> files are always treated as CommonJS.</p>
<h4><code>"exports"</code><span><a class="mark" href="#all_packages_exports" id="all_packages_exports">#</a></span><a aria-hidden="true" class="legacy" id="packages_exports"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.13.0, v12.20.0</td>
<td><p>Add support for <code>"exports"</code> patterns.</p></td></tr>
<tr><td>v13.7.0, v12.17.0</td>
<td><p>Unflag conditional exports.</p></td></tr>
<tr><td>v13.7.0, v12.16.0</td>
<td><p>Implement logical conditional exports ordering.</p></td></tr>
<tr><td>v13.7.0, v12.16.0</td>
<td><p>Remove the <code>--experimental-conditional-exports</code> option. In 12.16.0, conditional exports are still behind <code>--experimental-modules</code>.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>Implement conditional exports.</p></td></tr>
<tr><td>v12.7.0</td>
<td><p><span>Added in: v12.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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#String_type" class="type"><string[]></a></li>
</ul>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>"exports"</code> field allows defining the <a href="#all_packages_package-entry-points">entry points</a> of a package when
imported by name loaded either via a <code>node_modules</code> lookup or a
<a href="#all_packages_self-referencing-a-package-using-its-name">self-reference</a> to its own name. It is supported in Node.js 12+ as an
alternative to the <a href="#all_packages_main"><code>"main"</code></a> that can support defining <a href="#all_packages_subpath-exports">subpath exports</a>
and <a href="#all_packages_conditional-exports">conditional exports</a> while encapsulating internal unexported modules.</p>
<p><a href="#all_packages_conditional-exports">Conditional Exports</a> can also be used within <code>"exports"</code> to define different
package entry points per environment, including whether the package is
referenced via <code>require</code> or via <code>import</code>.</p>
<p>All paths defined in the <code>"exports"</code> must be relative file URLs starting with
<code>./</code>.</p>
<h4><code>"imports"</code><span><a class="mark" href="#all_packages_imports" id="all_packages_imports">#</a></span><a aria-hidden="true" class="legacy" id="packages_imports"></a></h4>
<div class="api_metadata">
<span>Added in: v14.6.0, v12.19.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<pre><code class="language-json"><span class="hljs-comment">// package.json</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"#dep"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"node"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"dep-node-native"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"default"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./dep-polyfill.js"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"dep-node-native"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"^1.0.0"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Entries in the imports field must be strings starting with <code>#</code>.</p>
<p>Package imports permit mapping to external packages.</p>
<p>This field defines <a href="#all_packages_subpath-imports">subpath imports</a> for the current package.</p></section>
</section>
<section><h2>Net<span><a class="mark" href="#all_net_net" id="all_net_net">#</a></span><a aria-hidden="true" class="legacy" id="net_net"></a></h2>
<!--lint disable maximum-line-length-->
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/net.js">lib/net.js</a></p>
<p>The <code>node:net</code> module provides an asynchronous network API for creating stream-based
TCP or <a href="#all_net_ipc-support">IPC</a> servers (<a href="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer()</code></a>) and clients
(<a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a>).</p>
<p>It can be accessed using:</p>
<pre class="with-32-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> net <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>IPC support<span><a class="mark" href="#all_net_ipc-support" id="all_net_ipc-support">#</a></span><a aria-hidden="true" class="legacy" id="net_ipc_support"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.8.0</td>
<td><p>Support binding to abstract Unix domain socket path like <code>\0abstract</code>. We can bind '\0' for Node.js <code>< v20.4.0</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>node:net</code> module supports IPC with named pipes on Windows, and Unix domain
sockets on other operating systems.</p>
<h4>Identifying paths for IPC connections<span><a class="mark" href="#all_net_identifying-paths-for-ipc-connections" id="all_net_identifying-paths-for-ipc-connections">#</a></span><a aria-hidden="true" class="legacy" id="net_identifying_paths_for_ipc_connections"></a></h4>
<p><a href="#all_net_netconnect"><code>net.connect()</code></a>, <a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a>, <a href="#all_net_serverlisten"><code>server.listen()</code></a>, and
<a href="#all_net_socketconnect"><code>socket.connect()</code></a> take a <code>path</code> parameter to identify IPC endpoints.</p>
<p>On Unix, the local domain is also known as the Unix domain. The path is a
file system pathname. It gets truncated to an OS-dependent length of
<code>sizeof(sockaddr_un.sun_path) - 1</code>. Typical values are 107 bytes on Linux and
103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket,
it will unlink the Unix domain socket as well. For example,
<a href="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer()</code></a> may create a Unix domain socket and
<a href="#all_net_serverclosecallback"><code>server.close()</code></a> will unlink it. But if a user creates the Unix domain
socket outside of these abstractions, the user will need to remove it. The same
applies when a Node.js API creates a Unix domain socket but the program then
crashes. In short, a Unix domain socket will be visible in the file system and
will persist until unlinked. On Linux, You can use Unix abstract socket by adding
<code>\0</code> to the beginning of the path, such as <code>\0abstract</code>. The path to the Unix
abstract socket is not visible in the file system and it will disappear automatically
when all open references to the socket are closed.</p>
<p>On Windows, the local domain is implemented using a named pipe. The path <em>must</em>
refer to an entry in <code>\\?\pipe\</code> or <code>\\.\pipe\</code>. Any characters are permitted,
but the latter may do some processing of pipe names, such as resolving <code>..</code>
sequences. Despite how it might look, the pipe namespace is flat. Pipes will
<em>not persist</em>. They are removed when the last reference to them is closed.
Unlike Unix domain sockets, Windows will close and remove the pipe when the
owning process exits.</p>
<p>JavaScript string escaping requires paths to be specified with extra backslash
escaping such as:</p>
<pre><code class="language-js">net.<span class="hljs-title function_">createServer</span>().<span class="hljs-title function_">listen</span>(
path.<span class="hljs-title function_">join</span>(<span class="hljs-string">'\\\\?\\pipe'</span>, process.<span class="hljs-title function_">cwd</span>(), <span class="hljs-string">'myctl'</span>));</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>net.BlockList</code><span><a class="mark" href="#all_net_class-netblocklist" id="all_net_class-netblocklist">#</a></span><a aria-hidden="true" class="legacy" id="net_class_net_blocklist"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<p>The <code>BlockList</code> object can be used with some network APIs to specify rules for
disabling inbound or outbound access to specific IP addresses, IP ranges, or
IP subnets.</p>
<h4><code>blockList.addAddress(address[, type])</code><span><a class="mark" href="#all_net_blocklistaddaddressaddress-type" id="all_net_blocklistaddaddressaddress-type">#</a></span><a aria-hidden="true" class="legacy" id="net_blocklist_addaddress_address_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_net_class-netsocketaddress" class="type"><net.SocketAddress></a> An IPv4 or IPv6 address.</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>'ipv4'</code> or <code>'ipv6'</code>. <strong>Default:</strong> <code>'ipv4'</code>.</li>
</ul>
<p>Adds a rule to block the given IP address.</p>
<h4><code>blockList.addRange(start, end[, type])</code><span><a class="mark" href="#all_net_blocklistaddrangestart-end-type" id="all_net_blocklistaddrangestart-end-type">#</a></span><a aria-hidden="true" class="legacy" id="net_blocklist_addrange_start_end_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_net_class-netsocketaddress" class="type"><net.SocketAddress></a> The starting IPv4 or IPv6 address in the
range.</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_net_class-netsocketaddress" class="type"><net.SocketAddress></a> The ending IPv4 or IPv6 address in the range.</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>'ipv4'</code> or <code>'ipv6'</code>. <strong>Default:</strong> <code>'ipv4'</code>.</li>
</ul>
<p>Adds a rule to block a range of IP addresses from <code>start</code> (inclusive) to
<code>end</code> (inclusive).</p>
<h4><code>blockList.addSubnet(net, prefix[, type])</code><span><a class="mark" href="#all_net_blocklistaddsubnetnet-prefix-type" id="all_net_blocklistaddsubnetnet-prefix-type">#</a></span><a aria-hidden="true" class="legacy" id="net_blocklist_addsubnet_net_prefix_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<ul>
<li><code>net</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_net_class-netsocketaddress" class="type"><net.SocketAddress></a> The network IPv4 or IPv6 address.</li>
<li><code>prefix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of CIDR prefix bits. For IPv4, this
must be a value between <code>0</code> and <code>32</code>. For IPv6, this must be between
<code>0</code> and <code>128</code>.</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>'ipv4'</code> or <code>'ipv6'</code>. <strong>Default:</strong> <code>'ipv4'</code>.</li>
</ul>
<p>Adds a rule to block a range of IP addresses specified as a subnet mask.</p>
<h4><code>blockList.check(address[, type])</code><span><a class="mark" href="#all_net_blocklistcheckaddress-type" id="all_net_blocklistcheckaddress-type">#</a></span><a aria-hidden="true" class="legacy" id="net_blocklist_check_address_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_net_class-netsocketaddress" class="type"><net.SocketAddress></a> The IP address to check</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>'ipv4'</code> or <code>'ipv6'</code>. <strong>Default:</strong> <code>'ipv4'</code>.</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 <code>true</code> if the given IP address matches any of the rules added to the
<code>BlockList</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> blockList = <span class="hljs-keyword">new</span> net.<span class="hljs-title class_">BlockList</span>();
blockList.<span class="hljs-title function_">addAddress</span>(<span class="hljs-string">'123.123.123.123'</span>);
blockList.<span class="hljs-title function_">addRange</span>(<span class="hljs-string">'10.0.0.1'</span>, <span class="hljs-string">'10.0.0.10'</span>);
blockList.<span class="hljs-title function_">addSubnet</span>(<span class="hljs-string">'8592:757c:efae:4e45::'</span>, <span class="hljs-number">64</span>, <span class="hljs-string">'ipv6'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(blockList.<span class="hljs-title function_">check</span>(<span class="hljs-string">'123.123.123.123'</span>)); <span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(blockList.<span class="hljs-title function_">check</span>(<span class="hljs-string">'10.0.0.3'</span>)); <span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(blockList.<span class="hljs-title function_">check</span>(<span class="hljs-string">'222.111.111.222'</span>)); <span class="hljs-comment">// Prints: false</span>
<span class="hljs-comment">// IPv6 notation for IPv4 addresses works:</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(blockList.<span class="hljs-title function_">check</span>(<span class="hljs-string">'::ffff:7b7b:7b7b'</span>, <span class="hljs-string">'ipv6'</span>)); <span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(blockList.<span class="hljs-title function_">check</span>(<span class="hljs-string">'::ffff:123.123.123.123'</span>, <span class="hljs-string">'ipv6'</span>)); <span class="hljs-comment">// Prints: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>blockList.rules</code><span><a class="mark" href="#all_net_blocklistrules" id="all_net_blocklistrules">#</a></span><a aria-hidden="true" class="legacy" id="net_blocklist_rules"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>The list of rules added to the blocklist.</p>
</section><section><h3>Class: <code>net.SocketAddress</code><span><a class="mark" href="#all_net_class-netsocketaddress" id="all_net_class-netsocketaddress">#</a></span><a aria-hidden="true" class="legacy" id="net_class_net_socketaddress"></a></h3>
<div class="api_metadata">
<span>Added in: v15.14.0, v14.18.0</span>
</div>
<h4><code>new net.SocketAddress([options])</code><span><a class="mark" href="#all_net_new-netsocketaddressoptions" id="all_net_new-netsocketaddressoptions">#</a></span><a aria-hidden="true" class="legacy" id="net_new_net_socketaddress_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.14.0, v14.18.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>
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The network address as either an IPv4 or IPv6 string.
<strong>Default</strong>: <code>'127.0.0.1'</code> if <code>family</code> is <code>'ipv4'</code>; <code>'::'</code> if <code>family</code> is
<code>'ipv6'</code>.</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> One of either <code>'ipv4'</code> or <code>'ipv6'</code>.
<strong>Default</strong>: <code>'ipv4'</code>.</li>
<li><code>flowlabel</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> An IPv6 flow-label used only if <code>family</code> is <code>'ipv6'</code>.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> An IP port.</li>
</ul>
</li>
</ul>
<h4><code>socketaddress.address</code><span><a class="mark" href="#all_net_socketaddressaddress" id="all_net_socketaddressaddress">#</a></span><a aria-hidden="true" class="legacy" id="net_socketaddress_address"></a></h4>
<div class="api_metadata">
<span>Added in: v15.14.0, v14.18.0</span>
</div>
<ul>
<li>Type <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<h4><code>socketaddress.family</code><span><a class="mark" href="#all_net_socketaddressfamily" id="all_net_socketaddressfamily">#</a></span><a aria-hidden="true" class="legacy" id="net_socketaddress_family"></a></h4>
<div class="api_metadata">
<span>Added in: v15.14.0, v14.18.0</span>
</div>
<ul>
<li>Type <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>'ipv4'</code> or <code>'ipv6'</code>.</li>
</ul>
<h4><code>socketaddress.flowlabel</code><span><a class="mark" href="#all_net_socketaddressflowlabel" id="all_net_socketaddressflowlabel">#</a></span><a aria-hidden="true" class="legacy" id="net_socketaddress_flowlabel"></a></h4>
<div class="api_metadata">
<span>Added in: v15.14.0, v14.18.0</span>
</div>
<ul>
<li>Type <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<h4><code>socketaddress.port</code><span><a class="mark" href="#all_net_socketaddressport" id="all_net_socketaddressport">#</a></span><a aria-hidden="true" class="legacy" id="net_socketaddress_port"></a></h4>
<div class="api_metadata">
<span>Added in: v15.14.0, v14.18.0</span>
</div>
<ul>
<li>Type <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</section><section><h3>Class: <code>net.Server</code><span><a class="mark" href="#all_net_class-netserver" id="all_net_class-netserver">#</a></span><a aria-hidden="true" class="legacy" id="net_class_net_server"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>This class is used to create a TCP or <a href="#all_net_ipc-support">IPC</a> server.</p>
<h4><code>new net.Server([options][, connectionListener])</code><span><a class="mark" href="#all_net_new-netserveroptions-connectionlistener" id="all_net_new-netserveroptions-connectionlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_new_net_server_options_connectionlistener"></a></h4>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See
<a href="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer([options][, connectionListener])</code></a>.</li>
<li><code>connectionListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Automatically set as a listener for the
<a href="#all_net_event-connection"><code>'connection'</code></a> event.</li>
<li>Returns: <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<p><code>net.Server</code> is an <a href="#all_events_class-eventemitter"><code>EventEmitter</code></a> with the following events:</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_net_event-close" id="all_net_event-close">#</a></span><a aria-hidden="true" class="legacy" id="net_event_close"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<p>Emitted when the server closes. If connections exist, this
event is not emitted until all connections are ended.</p>
<h4>Event: <code>'connection'</code><span><a class="mark" href="#all_net_event-connection" id="all_net_event-connection">#</a></span><a aria-hidden="true" class="legacy" id="net_event_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#all_net_class-netsocket" class="type"><net.Socket></a> The connection object</li>
</ul>
<p>Emitted when a new connection is made. <code>socket</code> is an instance of
<code>net.Socket</code>.</p>
<h4>Event: <code>'error'</code><span><a class="mark" href="#all_net_event-error" id="all_net_event-error">#</a></span><a aria-hidden="true" class="legacy" id="net_event_error"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</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>Emitted when an error occurs. Unlike <a href="#all_net_class-netsocket"><code>net.Socket</code></a>, the <a href="#all_net_event-close"><code>'close'</code></a>
event will <strong>not</strong> be emitted directly following this event unless
<a href="#all_net_serverclosecallback"><code>server.close()</code></a> is manually called. See the example in discussion of
<a href="#all_net_serverlisten"><code>server.listen()</code></a>.</p>
<h4>Event: <code>'listening'</code><span><a class="mark" href="#all_net_event-listening" id="all_net_event-listening">#</a></span><a aria-hidden="true" class="legacy" id="net_event_listening"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<p>Emitted when the server has been bound after calling <a href="#all_net_serverlisten"><code>server.listen()</code></a>.</p>
<h4>Event: <code>'drop'</code><span><a class="mark" href="#all_net_event-drop" id="all_net_event-drop">#</a></span><a aria-hidden="true" class="legacy" id="net_event_drop"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.0</span>
</div>
<p>When the number of connections reaches the threshold of <code>server.maxConnections</code>,
the server will drop new connections and emit <code>'drop'</code> event instead. If it is a
TCP server, the argument is as follows, otherwise the argument is <code>undefined</code>.</p>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The argument passed to event listener.
<ul>
<li><code>localAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Local address.</li>
<li><code>localPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Local port.</li>
<li><code>localFamily</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Local family.</li>
<li><code>remoteAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Remote address.</li>
<li><code>remotePort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Remote port.</li>
<li><code>remoteFamily</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Remote IP family. <code>'IPv4'</code> or <code>'IPv6'</code>.</li>
</ul>
</li>
</ul>
<h4><code>server.address()</code><span><a class="mark" href="#all_net_serveraddress" id="all_net_serveraddress">#</a></span><a aria-hidden="true" class="legacy" id="net_server_address"></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.4.0</td>
<td><p>The <code>family</code> property now returns a string instead of a number.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>family</code> property now returns a number instead of a string.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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></li>
</ul>
<p>Returns the bound <code>address</code>, the address <code>family</code> name, and <code>port</code> of the server
as reported by the operating system if listening on an IP socket
(useful to find which port was assigned when getting an OS-assigned address):
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code>.</p>
<p>For a server listening on a pipe or Unix domain socket, the name is returned
as a string.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> server = 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_">end</span>(<span class="hljs-string">'goodbye\n'</span>);
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-comment">// Handle errors here.</span>
<span class="hljs-keyword">throw</span> err;
});
<span class="hljs-comment">// Grab an arbitrary unused port.</span>
server.<span class="hljs-title function_">listen</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'opened server on'</span>, server.<span class="hljs-title function_">address</span>());
});</code> <button class="copy-button">copy</button></pre>
<p><code>server.address()</code> returns <code>null</code> before the <code>'listening'</code> event has been
emitted or after calling <code>server.close()</code>.</p>
<h4><code>server.close([callback])</code><span><a class="mark" href="#all_net_serverclosecallback" id="all_net_serverclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="net_server_close_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</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> Called when the server is closed.</li>
<li>Returns: <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<p>Stops the server from accepting new connections and keeps existing
connections. This function is asynchronous, the server is finally closed
when all connections are ended and the server emits a <a href="#all_net_event-close"><code>'close'</code></a> event.
The optional <code>callback</code> will be called once the <code>'close'</code> event occurs. Unlike
that event, it will be called with an <code>Error</code> as its only argument if the server
was not open when it was closed.</p>
<h4><code>server[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_net_serversymbolasyncdispose" id="all_net_serversymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="net_server_symbol_asyncdispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_net_serverclosecallback"><code>server.close()</code></a> and returns a promise that fulfills when the
server has closed.</p>
<h4><code>server.getConnections(callback)</code><span><a class="mark" href="#all_net_servergetconnectionscallback" id="all_net_servergetconnectionscallback">#</a></span><a aria-hidden="true" class="legacy" id="net_server_getconnections_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.7</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></li>
<li>Returns: <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<p>Asynchronously get the number of concurrent connections on the server. Works
when sockets were sent to forks.</p>
<p>Callback should take two arguments <code>err</code> and <code>count</code>.</p>
<h4><code>server.listen()</code><span><a class="mark" href="#all_net_serverlisten" id="all_net_serverlisten">#</a></span><a aria-hidden="true" class="legacy" id="net_server_listen"></a></h4>
<p>Start a server listening for connections. A <code>net.Server</code> can be a TCP or
an <a href="#all_net_ipc-support">IPC</a> server depending on what it listens to.</p>
<p>Possible signatures:</p>
<ul>
<li><a href="#all_net_serverlistenhandle-backlog-callback"><code>server.listen(handle[, backlog][, callback])</code></a></li>
<li><a href="#all_net_serverlistenoptions-callback"><code>server.listen(options[, callback])</code></a></li>
<li><a href="#all_net_serverlistenpath-backlog-callback"><code>server.listen(path[, backlog][, callback])</code></a>
for <a href="#all_net_ipc-support">IPC</a> servers</li>
<li><a href="#all_net_serverlistenport-host-backlog-callback"><code>server.listen([port[, host[, backlog]]][, callback])</code></a>
for TCP servers</li>
</ul>
<p>This function is asynchronous. When the server starts listening, the
<a href="#all_net_event-listening"><code>'listening'</code></a> event will be emitted. The last parameter <code>callback</code>
will be added as a listener for the <a href="#all_net_event-listening"><code>'listening'</code></a> event.</p>
<p>All <code>listen()</code> methods can take a <code>backlog</code> parameter to specify the maximum
length of the queue of pending connections. The actual length will be determined
by the OS through sysctl settings such as <code>tcp_max_syn_backlog</code> and <code>somaxconn</code>
on Linux. The default value of this parameter is 511 (not 512).</p>
<p>All <a href="#all_net_class-netsocket"><code>net.Socket</code></a> are set to <code>SO_REUSEADDR</code> (see <a href="https://man7.org/linux/man-pages/man7/socket.7.html"><code>socket(7)</code></a> for
details).</p>
<p>The <code>server.listen()</code> method can be called again if and only if there was an
error during the first <code>server.listen()</code> call or <code>server.close()</code> has been
called. Otherwise, an <code>ERR_SERVER_ALREADY_LISTEN</code> error will be thrown.</p>
<p>One of the most common errors raised when listening is <code>EADDRINUSE</code>.
This happens when another server is already listening on the requested
<code>port</code>/<code>path</code>/<code>handle</code>. One way to handle this would be to retry
after a certain amount of time:</p>
<pre><code class="language-js">server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
<span class="hljs-keyword">if</span> (e.<span class="hljs-property">code</span> === <span class="hljs-string">'EADDRINUSE'</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Address in use, retrying...'</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
server.<span class="hljs-title function_">close</span>();
server.<span class="hljs-title function_">listen</span>(<span class="hljs-variable constant_">PORT</span>, <span class="hljs-variable constant_">HOST</span>);
}, <span class="hljs-number">1000</span>);
}
});</code> <button class="copy-button">copy</button></pre>
<h5><code>server.listen(handle[, backlog][, callback])</code><span><a class="mark" href="#all_net_serverlistenhandle-backlog-callback" id="all_net_serverlistenhandle-backlog-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_server_listen_handle_backlog_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v0.5.10</span>
</div>
<ul>
<li><code>handle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>backlog</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Common parameter of <a href="#all_net_serverlisten"><code>server.listen()</code></a> functions</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<p>Start a server listening for connections on a given <code>handle</code> that has
already been bound to a port, a Unix domain socket, or a Windows named pipe.</p>
<p>The <code>handle</code> object can be either a server, a socket (anything with an
underlying <code>_handle</code> member), or an object with an <code>fd</code> member that is a
valid file descriptor.</p>
<p>Listening on a file descriptor is not supported on Windows.</p>
<h5><code>server.listen(options[, callback])</code><span><a class="mark" href="#all_net_serverlistenoptions-callback" id="all_net_serverlistenoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_server_listen_options_callback"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.6.0</td>
<td><p>AbortSignal support was added.</p></td></tr>
<tr><td>v11.4.0</td>
<td><p>The <code>ipv6Only</code> option is supported.</p></td></tr>
<tr><td>v0.11.14</td>
<td><p><span>Added in: v0.11.14</span></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> Required. Supports the following properties:
<ul>
<li><code>backlog</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Common parameter of <a href="#all_net_serverlisten"><code>server.listen()</code></a>
functions.</li>
<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>ipv6Only</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> For TCP servers, setting <code>ipv6Only</code> to <code>true</code> will
disable dual-stack support, i.e., binding to host <code>::</code> won't make
<code>0.0.0.0</code> be bound. <strong>Default:</strong> <code>false</code>.</li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Will be ignored if <code>port</code> is specified. See
<a href="#all_net_identifying-paths-for-ipc-connections">Identifying paths for IPC connections</a>.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>readableAll</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> For IPC servers makes the pipe readable
for all users. <strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> An AbortSignal that may be used to close a listening
server.</li>
<li><code>writableAll</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> For IPC servers makes the pipe writable
for all users. <strong>Default:</strong> <code>false</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>
functions.</li>
<li>Returns: <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<p>If <code>port</code> is specified, it behaves the same as
<a href="#all_net_serverlistenport-host-backlog-callback"><code>server.listen([port[, host[, backlog]]][, callback])</code></a>.
Otherwise, if <code>path</code> is specified, it behaves the same as
<a href="#all_net_serverlistenpath-backlog-callback"><code>server.listen(path[, backlog][, callback])</code></a>.
If none of them is specified, an error will be thrown.</p>
<p>If <code>exclusive</code> is <code>false</code> (default), then cluster workers will use the same
underlying handle, allowing connection handling duties to be shared. When
<code>exclusive</code> is <code>true</code>, the handle is not shared, and attempted port sharing
results in an error. An example which listens on an exclusive port is
shown below.</p>
<pre><code class="language-js">server.<span class="hljs-title function_">listen</span>({
<span class="hljs-attr">host</span>: <span class="hljs-string">'localhost'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
<span class="hljs-attr">exclusive</span>: <span class="hljs-literal">true</span>,
});</code> <button class="copy-button">copy</button></pre>
<p>When <code>exclusive</code> is <code>true</code> and the underlying handle is shared, it is
possible that several workers query a handle with different backlogs.
In this case, the first <code>backlog</code> passed to the master process will be used.</p>
<p>Starting an IPC server as root may cause the server path to be inaccessible for
unprivileged users. Using <code>readableAll</code> and <code>writableAll</code> will make the server
accessible for all users.</p>
<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
<code>AbortController</code> is similar to calling <code>.close()</code> on the server:</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>();
server.<span class="hljs-title function_">listen</span>({
<span class="hljs-attr">host</span>: <span class="hljs-string">'localhost'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
<span class="hljs-attr">signal</span>: controller.<span class="hljs-property">signal</span>,
});
<span class="hljs-comment">// Later, when you want to close the server.</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<h5><code>server.listen(path[, backlog][, callback])</code><span><a class="mark" href="#all_net_serverlistenpath-backlog-callback" id="all_net_serverlistenpath-backlog-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_server_listen_path_backlog_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Path the server should listen to. See
<a href="#all_net_identifying-paths-for-ipc-connections">Identifying paths for IPC connections</a>.</li>
<li><code>backlog</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Common parameter of <a href="#all_net_serverlisten"><code>server.listen()</code></a> functions.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>.</li>
<li>Returns: <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<p>Start an <a href="#all_net_ipc-support">IPC</a> server listening for connections on the given <code>path</code>.</p>
<h5><code>server.listen([port[, host[, backlog]]][, callback])</code><span><a class="mark" href="#all_net_serverlistenport-host-backlog-callback" id="all_net_serverlistenport-host-backlog-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_server_listen_port_host_backlog_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>backlog</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Common parameter of <a href="#all_net_serverlisten"><code>server.listen()</code></a> functions.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>.</li>
<li>Returns: <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<p>Start a TCP server listening for connections on the given <code>port</code> and <code>host</code>.</p>
<p>If <code>port</code> is omitted or is 0, the operating system will assign an arbitrary
unused port, which can be retrieved by using <code>server.address().port</code>
after the <a href="#all_net_event-listening"><code>'listening'</code></a> event has been emitted.</p>
<p>If <code>host</code> is omitted, the server will accept connections on the
<a href="https://en.wikipedia.org/wiki/IPv6_address#Unspecified_address">unspecified IPv6 address</a> (<code>::</code>) when IPv6 is available, or the
<a href="https://en.wikipedia.org/wiki/0.0.0.0">unspecified IPv4 address</a> (<code>0.0.0.0</code>) otherwise.</p>
<p>In most operating systems, listening to the <a href="https://en.wikipedia.org/wiki/IPv6_address#Unspecified_address">unspecified IPv6 address</a> (<code>::</code>)
may cause the <code>net.Server</code> to also listen on the <a href="https://en.wikipedia.org/wiki/0.0.0.0">unspecified IPv4 address</a>
(<code>0.0.0.0</code>).</p>
<h4><code>server.listening</code><span><a class="mark" href="#all_net_serverlistening" id="all_net_serverlistening">#</a></span><a aria-hidden="true" class="legacy" id="net_server_listening"></a></h4>
<div class="api_metadata">
<span>Added in: v5.7.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether or not the server is listening for connections.</li>
</ul>
<h4><code>server.maxConnections</code><span><a class="mark" href="#all_net_servermaxconnections" id="all_net_servermaxconnections">#</a></span><a aria-hidden="true" class="legacy" id="net_server_maxconnections"></a></h4>
<div class="api_metadata">
<span>Added in: v0.2.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>Set this property to reject connections when the server's connection count gets
high.</p>
<p>It is not recommended to use this option once a socket has been sent to a child
with <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>.</p>
<h4><code>server.ref()</code><span><a class="mark" href="#all_net_serverref" id="all_net_serverref">#</a></span><a aria-hidden="true" class="legacy" id="net_server_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref</code>ed server will
<em>not</em> let the program exit if it's the only server left (the default behavior).
If the server is <code>ref</code>ed calling <code>ref()</code> again will have no effect.</p>
<h4><code>server.unref()</code><span><a class="mark" href="#all_net_serverunref" id="all_net_serverunref">#</a></span><a aria-hidden="true" class="legacy" id="net_server_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<p>Calling <code>unref()</code> on a server will allow the program to exit if this is the only
active server in the event system. If the server is already <code>unref</code>ed calling
<code>unref()</code> again will have no effect.</p>
</section><section><h3>Class: <code>net.Socket</code><span><a class="mark" href="#all_net_class-netsocket" id="all_net_class-netsocket">#</a></span><a aria-hidden="true" class="legacy" id="net_class_net_socket"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>This class is an abstraction of a TCP socket or a streaming <a href="#all_net_ipc-support">IPC</a> endpoint
(uses named pipes on Windows, and Unix domain sockets otherwise). It is also
an <a href="#all_events_class-eventemitter"><code>EventEmitter</code></a>.</p>
<p>A <code>net.Socket</code> can be created by the user and used directly to interact with
a server. For example, it is returned by <a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a>,
so the user can use it to talk to the server.</p>
<p>It can also be created by Node.js and passed to the user when a connection
is received. For example, it is passed to the listeners of a
<a href="#all_net_event-connection"><code>'connection'</code></a> event emitted on a <a href="#all_net_class-netserver"><code>net.Server</code></a>, so the user can use
it to interact with the client.</p>
<h4><code>new net.Socket([options])</code><span><a class="mark" href="#all_net_new-netsocketoptions" id="all_net_new-netsocketoptions">#</a></span><a aria-hidden="true" class="legacy" id="net_new_net_socket_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>v15.14.0</td>
<td><p>AbortSignal support was added.</p></td></tr>
<tr><td>v12.10.0</td>
<td><p>Added <code>onread</code> option.</p></td></tr>
<tr><td>v0.3.4</td>
<td><p><span>Added in: v0.3.4</span></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> Available options are:
<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 socket will
automatically end the writable side when the readable side ends. See
<a href="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer()</code></a> and the <a href="#all_net_event-end"><code>'end'</code></a> event for details. <strong>Default:</strong>
<code>false</code>.</li>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If specified, wrap around an existing socket with
the given file descriptor, otherwise a new socket will be created.</li>
<li><code>onread</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> If specified, incoming data is stored in a single <code>buffer</code>
and passed to the supplied <code>callback</code> when data arrives on the socket.
This will cause the streaming functionality to not provide any data.
The socket will emit events like <code>'error'</code>, <code>'end'</code>, and <code>'close'</code>
as usual. Methods like <code>pause()</code> and <code>resume()</code> will also behave as
expected.
<ul>
<li><code>buffer</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Either a reusable chunk of memory to
use for storing incoming data or a function that returns such.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> This function is called for every chunk of incoming
data. Two arguments are passed to it: the number of bytes written to
<code>buffer</code> and a reference to <code>buffer</code>. Return <code>false</code> from this function to
implicitly <code>pause()</code> the socket. This function will be executed in the
global context.</li>
</ul>
</li>
<li><code>readable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Allow reads on the socket when an <code>fd</code> is passed,
otherwise ignored. <strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> An Abort signal that may be used to destroy the
socket.</li>
<li><code>writable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Allow writes on the socket when an <code>fd</code> is passed,
otherwise ignored. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
</ul>
<p>Creates a new socket object.</p>
<p>The newly created socket can be either a TCP socket or a streaming <a href="#all_net_ipc-support">IPC</a>
endpoint, depending on what it <a href="#all_net_socketconnect"><code>connect()</code></a> to.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_net_event-close_1" id="all_net_event-close_1">#</a></span><a aria-hidden="true" class="legacy" id="net_event_close_1"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>hadError</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the socket had a transmission error.</li>
</ul>
<p>Emitted once the socket is fully closed. The argument <code>hadError</code> is a boolean
which says if the socket was closed due to a transmission error.</p>
<h4>Event: <code>'connect'</code><span><a class="mark" href="#all_net_event-connect" id="all_net_event-connect">#</a></span><a aria-hidden="true" class="legacy" id="net_event_connect"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<p>Emitted when a socket connection is successfully established.
See <a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a>.</p>
<h4>Event: <code>'connectionAttempt'</code><span><a class="mark" href="#all_net_event-connectionattempt" id="all_net_event-connectionattempt">#</a></span><a aria-hidden="true" class="legacy" id="net_event_connectionattempt"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<ul>
<li><code>ip</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The IP which the socket is attempting to connect to.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The port which the socket is attempting to connect to.</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The family of the IP. It can be <code>6</code> for IPv6 or <code>4</code> for IPv4.</li>
</ul>
<p>Emitted when a new connection attempt is started. This may be emitted multiple times
if the family autoselection algorithm is enabled in <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.</p>
<h4>Event: <code>'connectionAttemptFailed'</code><span><a class="mark" href="#all_net_event-connectionattemptfailed" id="all_net_event-connectionattemptfailed">#</a></span><a aria-hidden="true" class="legacy" id="net_event_connectionattemptfailed"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<ul>
<li><code>ip</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The IP which the socket attempted to connect to.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The port which the socket attempted to connect to.</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The family of the IP. It can be <code>6</code> for IPv6 or <code>4</code> for IPv4.</li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The error associated with the failure.</li>
</ul>
<p>Emitted when a connection attempt failed. This may be emitted multiple times
if the family autoselection algorithm is enabled in <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.</p>
<h4>Event: <code>'connectionAttemptTimeout'</code><span><a class="mark" href="#all_net_event-connectionattempttimeout" id="all_net_event-connectionattempttimeout">#</a></span><a aria-hidden="true" class="legacy" id="net_event_connectionattempttimeout"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<ul>
<li><code>ip</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The IP which the socket attempted to connect to.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The port which the socket attempted to connect to.</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The family of the IP. It can be <code>6</code> for IPv6 or <code>4</code> for IPv4.</li>
</ul>
<p>Emitted when a connection attempt timed out. This is only emitted (and may be
emitted multiple times) if the family autoselection algorithm is enabled
in <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.</p>
<h4>Event: <code>'data'</code><span><a class="mark" href="#all_net_event-data" id="all_net_event-data">#</a></span><a aria-hidden="true" class="legacy" id="net_event_data"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#all_buffer_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></li>
</ul>
<p>Emitted when data is received. The argument <code>data</code> will be a <code>Buffer</code> or
<code>String</code>. Encoding of data is set by <a href="#all_net_socketsetencodingencoding"><code>socket.setEncoding()</code></a>.</p>
<p>The data will be lost if there is no listener when a <code>Socket</code>
emits a <code>'data'</code> event.</p>
<h4>Event: <code>'drain'</code><span><a class="mark" href="#all_net_event-drain" id="all_net_event-drain">#</a></span><a aria-hidden="true" class="legacy" id="net_event_drain"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<p>Emitted when the write buffer becomes empty. Can be used to throttle uploads.</p>
<p>See also: the return values of <code>socket.write()</code>.</p>
<h4>Event: <code>'end'</code><span><a class="mark" href="#all_net_event-end" id="all_net_event-end">#</a></span><a aria-hidden="true" class="legacy" id="net_event_end"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<p>Emitted when the other end of the socket signals the end of transmission, thus
ending the readable side of the socket.</p>
<p>By default (<code>allowHalfOpen</code> is <code>false</code>) the socket will send an end of
transmission packet back and destroy its file descriptor once it has written out
its pending write queue. However, if <code>allowHalfOpen</code> is set to <code>true</code>, the
socket will not automatically <a href="#all_net_socketenddata-encoding-callback"><code>end()</code></a> its writable side,
allowing the user to write arbitrary amounts of data. The user must call
<a href="#all_net_socketenddata-encoding-callback"><code>end()</code></a> explicitly to close the connection (i.e. sending a
FIN packet back).</p>
<h4>Event: <code>'error'</code><span><a class="mark" href="#all_net_event-error_1" id="all_net_event-error_1">#</a></span><a aria-hidden="true" class="legacy" id="net_event_error_1"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</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>Emitted when an error occurs. The <code>'close'</code> event will be called directly
following this event.</p>
<h4>Event: <code>'lookup'</code><span><a class="mark" href="#all_net_event-lookup" id="all_net_event-lookup">#</a></span><a aria-hidden="true" class="legacy" id="net_event_lookup"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.10.0</td>
<td><p>The <code>host</code> parameter is supported now.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p><span>Added in: v0.11.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Emitted after resolving the host name but before connecting.
Not applicable to Unix sockets.</p>
<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 href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The error object. See <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The IP address.</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The address type. See <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The host name.</li>
</ul>
<h4>Event: <code>'ready'</code><span><a class="mark" href="#all_net_event-ready" id="all_net_event-ready">#</a></span><a aria-hidden="true" class="legacy" id="net_event_ready"></a></h4>
<div class="api_metadata">
<span>Added in: v9.11.0</span>
</div>
<p>Emitted when a socket is ready to be used.</p>
<p>Triggered immediately after <code>'connect'</code>.</p>
<h4>Event: <code>'timeout'</code><span><a class="mark" href="#all_net_event-timeout" id="all_net_event-timeout">#</a></span><a aria-hidden="true" class="legacy" id="net_event_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<p>Emitted if the socket times out from inactivity. This is only to notify that
the socket has been idle. The user must manually close the connection.</p>
<p>See also: <a href="#all_net_socketsettimeouttimeout-callback"><code>socket.setTimeout()</code></a>.</p>
<h4><code>socket.address()</code><span><a class="mark" href="#all_net_socketaddress" id="all_net_socketaddress">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_address"></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.4.0</td>
<td><p>The <code>family</code> property now returns a string instead of a number.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>family</code> property now returns a number instead of a string.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns the bound <code>address</code>, the address <code>family</code> name and <code>port</code> of the
socket as reported by the operating system:
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code></p>
<h4><code>socket.autoSelectFamilyAttemptedAddresses</code><span><a class="mark" href="#all_net_socketautoselectfamilyattemptedaddresses" id="all_net_socketautoselectfamilyattemptedaddresses">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_autoselectfamilyattemptedaddresses"></a></h4>
<div class="api_metadata">
<span>Added in: v19.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>This property is only present if the family autoselection algorithm is enabled in
<a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a> and it is an array of the addresses that have been attempted.</p>
<p>Each address is a string in the form of <code>$IP:$PORT</code>. If the connection was successful,
then the last address is the one that the socket is currently connected to.</p>
<h4><code>socket.bufferSize</code><span><a class="mark" href="#all_net_socketbuffersize" id="all_net_socketbuffersize">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_buffersize"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.8</span><span>Deprecated since: v14.6.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_stream_writablewritablelength"><code>writable.writableLength</code></a> instead.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>This property shows the number of characters buffered for writing. The buffer
may contain strings whose length after encoding is not yet known. So this number
is only an approximation of the number of bytes in the buffer.</p>
<p><code>net.Socket</code> has the property that <code>socket.write()</code> always works. This is to
help users get up and running quickly. The computer cannot always keep up
with the amount of data that is written to a socket. The network connection
simply might be too slow. Node.js will internally queue up the data written to a
socket and send it out over the wire when it is possible.</p>
<p>The consequence of this internal buffering is that memory may grow.
Users who experience large or growing <code>bufferSize</code> should attempt to
"throttle" the data flows in their program with
<a href="#all_net_socketpause"><code>socket.pause()</code></a> and <a href="#all_net_socketresume"><code>socket.resume()</code></a>.</p>
<h4><code>socket.bytesRead</code><span><a class="mark" href="#all_net_socketbytesread" id="all_net_socketbytesread">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_bytesread"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.3</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>The amount of received bytes.</p>
<h4><code>socket.bytesWritten</code><span><a class="mark" href="#all_net_socketbyteswritten" id="all_net_socketbyteswritten">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_byteswritten"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.3</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>The amount of bytes sent.</p>
<h4><code>socket.connect()</code><span><a class="mark" href="#all_net_socketconnect" id="all_net_socketconnect">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_connect"></a></h4>
<p>Initiate a connection on a given socket.</p>
<p>Possible signatures:</p>
<ul>
<li><a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a></li>
<li><a href="#all_net_socketconnectpath-connectlistener"><code>socket.connect(path[, connectListener])</code></a>
for <a href="#all_net_ipc-support">IPC</a> connections.</li>
<li><a href="#all_net_socketconnectport-host-connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>
for TCP connections.</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>This function is asynchronous. When the connection is established, the
<a href="#all_net_event-connect"><code>'connect'</code></a> event will be emitted. If there is a problem connecting,
instead of a <a href="#all_net_event-connect"><code>'connect'</code></a> event, an <a href="#all_net_event-error_1"><code>'error'</code></a> event will be emitted with
the error passed to the <a href="#all_net_event-error_1"><code>'error'</code></a> listener.
The last parameter <code>connectListener</code>, if supplied, will be added as a listener
for the <a href="#all_net_event-connect"><code>'connect'</code></a> event <strong>once</strong>.</p>
<p>This function should only be used for reconnecting a socket after
<code>'close'</code> has been emitted or otherwise it may lead to undefined
behavior.</p>
<h5><code>socket.connect(options[, connectListener])</code><span><a class="mark" href="#all_net_socketconnectoptions-connectlistener" id="all_net_socketconnectoptions-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_connect_options_connectlistener"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The default value for the autoSelectFamily option is now true. The <code>--enable-network-family-autoselection</code> CLI flag has been renamed to <code>--network-family-autoselection</code>. The old name is now an alias but it is discouraged.</p></td></tr>
<tr><td>v19.4.0</td>
<td><p>The default value for autoSelectFamily option can be changed at runtime using <code>setDefaultAutoSelectFamily</code> or via the command line option <code>--enable-network-family-autoselection</code>.</p></td></tr>
<tr><td>v19.3.0, v18.13.0</td>
<td><p>Added the <code>autoSelectFamily</code> option.</p></td></tr>
<tr><td>v17.7.0, v16.15.0</td>
<td><p>The <code>noDelay</code>, <code>keepAlive</code>, and <code>keepAliveInitialDelay</code> options are supported now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>hints</code> option defaults to <code>0</code> in all cases now. Previously, in the absence of the <code>family</code> option it would default to <code>dns.ADDRCONFIG | dns.V4MAPPED</code>.</p></td></tr>
<tr><td>v5.11.0</td>
<td><p>The <code>hints</code> option is supported now.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></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></li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of <a href="#all_net_socketconnect"><code>socket.connect()</code></a>
methods. Will be added as a listener for the <a href="#all_net_event-connect"><code>'connect'</code></a> event once.</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>Initiate a connection on a given socket. Normally this method is not needed,
the socket should be created and opened with <a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a>. Use
this only when implementing a custom Socket.</p>
<p>For TCP connections, available <code>options</code> are:</p>
<ul>
<li><code>autoSelectFamily</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a>: If set to <code>true</code>, it enables a family
autodetection algorithm that loosely implements section 5 of <a href="https://www.rfc-editor.org/rfc/rfc8305.txt">RFC 8305</a>. The
<code>all</code> option passed to lookup is set to <code>true</code> and the sockets attempts to
connect to all obtained IPv6 and IPv4 addresses, in sequence, until a
connection is established. The first returned AAAA address is tried first,
then the first returned A address, then the second returned AAAA address and
so on. Each connection attempt (but the last one) is given the amount of time
specified by the <code>autoSelectFamilyAttemptTimeout</code> option before timing out and
trying the next address. Ignored if the <code>family</code> option is not <code>0</code> or if
<code>localAddress</code> is set. Connection errors are not emitted if at least one
connection succeeds. If all connections attempts fails, a single
<code>AggregateError</code> with all failed attempts is emitted. <strong>Default:</strong>
<a href="#all_net_netgetdefaultautoselectfamily"><code>net.getDefaultAutoSelectFamily()</code></a>.</li>
<li><code>autoSelectFamilyAttemptTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a>: The amount of time in milliseconds
to wait for a connection attempt to finish before trying the next address when
using the <code>autoSelectFamily</code> option. If set to a positive integer less than
<code>10</code>, then the value <code>10</code> will be used instead. <strong>Default:</strong>
<a href="#all_net_netgetdefaultautoselectfamilyattempttimeout"><code>net.getDefaultAutoSelectFamilyAttemptTimeout()</code></a>.</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a>: Version of IP stack. Must be <code>4</code>, <code>6</code>, or <code>0</code>. The value
<code>0</code> indicates that both IPv4 and IPv6 addresses are allowed. <strong>Default:</strong> <code>0</code>.</li>
<li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optional <a href="#all_dns_supported-getaddrinfo-flags"><code>dns.lookup()</code> hints</a>.</li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host the socket should connect to. <strong>Default:</strong> <code>'localhost'</code>.</li>
<li><code>keepAlive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, it enables keep-alive functionality on
the socket immediately after the connection is established, similarly on what
is done in <a href="#all_net_socketsetkeepaliveenable-initialdelay"><code>socket.setKeepAlive()</code></a>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>keepAliveInitialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If set to a positive number, it sets the
initial delay before the first keepalive probe is sent on an idle socket.
<strong>Default:</strong> <code>0</code>.</li>
<li><code>localAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Local address the socket should connect from.</li>
<li><code>localPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Local port the socket should connect from.</li>
<li><code>lookup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Custom lookup function. <strong>Default:</strong> <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</li>
<li><code>noDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, it disables the use of Nagle's algorithm
immediately after the socket is established. <strong>Default:</strong> <code>false</code>.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Required. Port the socket should connect to.</li>
</ul>
<p>For <a href="#all_net_ipc-support">IPC</a> connections, available <code>options</code> are:</p>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Required. Path the client should connect to.
See <a href="#all_net_identifying-paths-for-ipc-connections">Identifying paths for IPC connections</a>. If provided, the TCP-specific
options above are ignored.</li>
</ul>
<h5><code>socket.connect(path[, connectListener])</code><span><a class="mark" href="#all_net_socketconnectpath-connectlistener" id="all_net_socketconnectpath-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_connect_path_connectlistener"></a></h5>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Path the client should connect to. See
<a href="#all_net_identifying-paths-for-ipc-connections">Identifying paths for IPC connections</a>.</li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of <a href="#all_net_socketconnect"><code>socket.connect()</code></a>
methods. Will be added as a listener for the <a href="#all_net_event-connect"><code>'connect'</code></a> event once.</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>Initiate an <a href="#all_net_ipc-support">IPC</a> connection on the given socket.</p>
<p>Alias to
<a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a>
called with <code>{ path: path }</code> as <code>options</code>.</p>
<h5><code>socket.connect(port[, host][, connectListener])</code><span><a class="mark" href="#all_net_socketconnectport-host-connectlistener" id="all_net_socketconnectport-host-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_connect_port_host_connectlistener"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port the client should connect to.</li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host the client should connect to.</li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of <a href="#all_net_socketconnect"><code>socket.connect()</code></a>
methods. Will be added as a listener for the <a href="#all_net_event-connect"><code>'connect'</code></a> event once.</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>Initiate a TCP connection on the given socket.</p>
<p>Alias to
<a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a>
called with <code>{port: port, host: host}</code> as <code>options</code>.</p>
<h4><code>socket.connecting</code><span><a class="mark" href="#all_net_socketconnecting" id="all_net_socketconnecting">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_connecting"></a></h4>
<div class="api_metadata">
<span>Added in: v6.1.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>If <code>true</code>,
<a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a> was
called and has not yet finished. It will stay <code>true</code> until the socket becomes
connected, then it is set to <code>false</code> and the <code>'connect'</code> event is emitted. Note
that the
<a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a>
callback is a listener for the <code>'connect'</code> event.</p>
<h4><code>socket.destroy([error])</code><span><a class="mark" href="#all_net_socketdestroyerror" id="all_net_socketdestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_destroy_error"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
</ul>
<p>Ensures that no more I/O activity happens on this socket.
Destroys the stream and closes the connection.</p>
<p>See <a href="#all_stream_writabledestroyerror"><code>writable.destroy()</code></a> for further details.</p>
<h4><code>socket.destroyed</code><span><a class="mark" href="#all_net_socketdestroyed" id="all_net_socketdestroyed">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_destroyed"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates if the connection is destroyed or not. Once a
connection is destroyed no further data can be transferred using it.</li>
</ul>
<p>See <a href="#all_stream_writabledestroyed"><code>writable.destroyed</code></a> for further details.</p>
<h4><code>socket.destroySoon()</code><span><a class="mark" href="#all_net_socketdestroysoon" id="all_net_socketdestroysoon">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_destroysoon"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<p>Destroys the socket after all data is written. If the <code>'finish'</code> event was
already emitted the socket is destroyed immediately. If the socket is still
writable it implicitly calls <code>socket.end()</code>.</p>
<h4><code>socket.end([data[, encoding]][, callback])</code><span><a class="mark" href="#all_net_socketenddata-encoding-callback" id="all_net_socketenddata-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_end_data_encoding_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></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> Only used when data is <code>string</code>. <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> Optional callback for when the socket is finished.</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>Half-closes the socket. i.e., it sends a FIN packet. It is possible the
server will still send some data.</p>
<p>See <a href="#all_stream_writableendchunk-encoding-callback"><code>writable.end()</code></a> for further details.</p>
<h4><code>socket.localAddress</code><span><a class="mark" href="#all_net_socketlocaladdress" id="all_net_socketlocaladdress">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_localaddress"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.6</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The string representation of the local IP address the remote client is
connecting on. For example, in a server listening on <code>'0.0.0.0'</code>, if a client
connects on <code>'192.168.1.1'</code>, the value of <code>socket.localAddress</code> would be
<code>'192.168.1.1'</code>.</p>
<h4><code>socket.localPort</code><span><a class="mark" href="#all_net_socketlocalport" id="all_net_socketlocalport">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_localport"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.6</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>The numeric representation of the local port. For example, <code>80</code> or <code>21</code>.</p>
<h4><code>socket.localFamily</code><span><a class="mark" href="#all_net_socketlocalfamily" id="all_net_socketlocalfamily">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_localfamily"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The string representation of the local IP family. <code>'IPv4'</code> or <code>'IPv6'</code>.</p>
<h4><code>socket.pause()</code><span><a class="mark" href="#all_net_socketpause" id="all_net_socketpause">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_pause"></a></h4>
<ul>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>Pauses the reading of data. That is, <a href="#all_net_event-data"><code>'data'</code></a> events will not be emitted.
Useful to throttle back an upload.</p>
<h4><code>socket.pending</code><span><a class="mark" href="#all_net_socketpending" id="all_net_socketpending">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_pending"></a></h4>
<div class="api_metadata">
<span>Added in: v11.2.0, v10.16.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 is <code>true</code> if the socket is not connected yet, either because <code>.connect()</code>
has not yet been called or because it is still in the process of connecting
(see <a href="#all_net_socketconnecting"><code>socket.connecting</code></a>).</p>
<h4><code>socket.ref()</code><span><a class="mark" href="#all_net_socketref" id="all_net_socketref">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref</code>ed socket will
<em>not</em> let the program exit if it's the only socket left (the default behavior).
If the socket is <code>ref</code>ed calling <code>ref</code> again will have no effect.</p>
<h4><code>socket.remoteAddress</code><span><a class="mark" href="#all_net_socketremoteaddress" id="all_net_socketremoteaddress">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_remoteaddress"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.10</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The string representation of the remote IP address. For example,
<code>'74.125.127.100'</code> or <code>'2001:4860:a005::68'</code>. Value may be <code>undefined</code> if
the socket is destroyed (for example, if the client disconnected).</p>
<h4><code>socket.remoteFamily</code><span><a class="mark" href="#all_net_socketremotefamily" id="all_net_socketremotefamily">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_remotefamily"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The string representation of the remote IP family. <code>'IPv4'</code> or <code>'IPv6'</code>. Value may be <code>undefined</code> if
the socket is destroyed (for example, if the client disconnected).</p>
<h4><code>socket.remotePort</code><span><a class="mark" href="#all_net_socketremoteport" id="all_net_socketremoteport">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_remoteport"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.10</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>The numeric representation of the remote port. For example, <code>80</code> or <code>21</code>. Value may be <code>undefined</code> if
the socket is destroyed (for example, if the client disconnected).</p>
<h4><code>socket.resetAndDestroy()</code><span><a class="mark" href="#all_net_socketresetanddestroy" id="all_net_socketresetanddestroy">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_resetanddestroy"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<ul>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
</ul>
<p>Close the TCP connection by sending an RST packet and destroy the stream.
If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected.
Otherwise, it will call <code>socket.destroy</code> with an <code>ERR_SOCKET_CLOSED</code> Error.
If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an <code>ERR_INVALID_HANDLE_TYPE</code> Error.</p>
<h4><code>socket.resume()</code><span><a class="mark" href="#all_net_socketresume" id="all_net_socketresume">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_resume"></a></h4>
<ul>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>Resumes reading after a call to <a href="#all_net_socketpause"><code>socket.pause()</code></a>.</p>
<h4><code>socket.setEncoding([encoding])</code><span><a class="mark" href="#all_net_socketsetencodingencoding" id="all_net_socketsetencodingencoding">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_setencoding_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</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></li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>Set the encoding for the socket as a <a href="#all_stream_class-streamreadable">Readable Stream</a>. See
<a href="#all_stream_readablesetencodingencoding"><code>readable.setEncoding()</code></a> for more information.</p>
<h4><code>socket.setKeepAlive([enable][, initialDelay])</code><span><a class="mark" href="#all_net_socketsetkeepaliveenable-initialdelay" id="all_net_socketsetkeepaliveenable-initialdelay">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_setkeepalive_enable_initialdelay"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>New defaults for <code>TCP_KEEPCNT</code> and <code>TCP_KEEPINTVL</code> socket options were added.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>enable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>initialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>0</code></li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>Enable/disable keep-alive functionality, and optionally set the initial
delay before the first keepalive probe is sent on an idle socket.</p>
<p>Set <code>initialDelay</code> (in milliseconds) to set the delay between the last
data packet received and the first keepalive probe. Setting <code>0</code> for
<code>initialDelay</code> will leave the value unchanged from the default
(or previous) setting.</p>
<p>Enabling the keep-alive functionality will set the following socket options:</p>
<ul>
<li><code>SO_KEEPALIVE=1</code></li>
<li><code>TCP_KEEPIDLE=initialDelay</code></li>
<li><code>TCP_KEEPCNT=10</code></li>
<li><code>TCP_KEEPINTVL=1</code></li>
</ul>
<h4><code>socket.setNoDelay([noDelay])</code><span><a class="mark" href="#all_net_socketsetnodelaynodelay" id="all_net_socketsetnodelaynodelay">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_setnodelay_nodelay"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>noDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</code></li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>Enable/disable the use of Nagle's algorithm.</p>
<p>When a TCP connection is created, it will have Nagle's algorithm enabled.</p>
<p>Nagle's algorithm delays data before it is sent via the network. It attempts
to optimize throughput at the expense of latency.</p>
<p>Passing <code>true</code> for <code>noDelay</code> or not passing an argument will disable Nagle's
algorithm for the socket. Passing <code>false</code> for <code>noDelay</code> will enable Nagle's
algorithm.</p>
<h4><code>socket.setTimeout(timeout[, callback])</code><span><a class="mark" href="#all_net_socketsettimeouttimeout-callback" id="all_net_socketsettimeouttimeout-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_settimeout_timeout_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>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>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>Sets the socket to timeout after <code>timeout</code> milliseconds of inactivity on
the socket. By default <code>net.Socket</code> do not have a timeout.</p>
<p>When an idle timeout is triggered the socket will receive a <a href="#all_net_event-timeout"><code>'timeout'</code></a>
event but the connection will not be severed. The user must manually call
<a href="#all_net_socketenddata-encoding-callback"><code>socket.end()</code></a> or <a href="#all_net_socketdestroyerror"><code>socket.destroy()</code></a> to end the connection.</p>
<pre><code class="language-js">socket.<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">3000</span>);
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'timeout'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'socket timeout'</span>);
socket.<span class="hljs-title function_">end</span>();
});</code> <button class="copy-button">copy</button></pre>
<p>If <code>timeout</code> is 0, then the existing idle timeout is disabled.</p>
<p>The optional <code>callback</code> parameter will be added as a one-time listener for the
<a href="#all_net_event-timeout"><code>'timeout'</code></a> event.</p>
<h4><code>socket.timeout</code><span><a class="mark" href="#all_net_sockettimeout" id="all_net_sockettimeout">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>The socket timeout in milliseconds as set by <a href="#all_net_socketsettimeouttimeout-callback"><code>socket.setTimeout()</code></a>.
It is <code>undefined</code> if a timeout has not been set.</p>
<h4><code>socket.unref()</code><span><a class="mark" href="#all_net_socketunref" id="all_net_socketunref">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
<p>Calling <code>unref()</code> on a socket will allow the program to exit if this is the only
active socket in the event system. If the socket is already <code>unref</code>ed calling
<code>unref()</code> again will have no effect.</p>
<h4><code>socket.write(data[, encoding][, callback])</code><span><a class="mark" href="#all_net_socketwritedata-encoding-callback" id="all_net_socketwritedata-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_write_data_encoding_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></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> Only used when data is <code>string</code>. <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></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>Sends data on the socket. The second parameter specifies the encoding in the
case of a string. It defaults to UTF8 encoding.</p>
<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
buffer. Returns <code>false</code> if all or part of the data was queued in user memory.
<a href="#all_net_event-drain"><code>'drain'</code></a> will be emitted when the buffer is again free.</p>
<p>The optional <code>callback</code> parameter will be executed when the data is finally
written out, which may not be immediately.</p>
<p>See <code>Writable</code> stream <a href="#all_stream_writablewritechunk-encoding-callback"><code>write()</code></a> method for more
information.</p>
<h4><code>socket.readyState</code><span><a class="mark" href="#all_net_socketreadystate" id="all_net_socketreadystate">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_readystate"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>This property represents the state of the connection as a string.</p>
<ul>
<li>If the stream is connecting <code>socket.readyState</code> is <code>opening</code>.</li>
<li>If the stream is readable and writable, it is <code>open</code>.</li>
<li>If the stream is readable and not writable, it is <code>readOnly</code>.</li>
<li>If the stream is not readable and writable, it is <code>writeOnly</code>.</li>
</ul>
</section><section><h3><code>net.connect()</code><span><a class="mark" href="#all_net_netconnect" id="all_net_netconnect">#</a></span><a aria-hidden="true" class="legacy" id="net_net_connect"></a></h3>
<p>Aliases to
<a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a>.</p>
<p>Possible signatures:</p>
<ul>
<li><a href="#all_net_netconnectoptions-connectlistener"><code>net.connect(options[, connectListener])</code></a></li>
<li><a href="#all_net_netconnectpath-connectlistener"><code>net.connect(path[, connectListener])</code></a> for <a href="#all_net_ipc-support">IPC</a>
connections.</li>
<li><a href="#all_net_netconnectport-host-connectlistener"><code>net.connect(port[, host][, connectListener])</code></a>
for TCP connections.</li>
</ul>
<h4><code>net.connect(options[, connectListener])</code><span><a class="mark" href="#all_net_netconnectoptions-connectlistener" id="all_net_netconnectoptions-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_connect_options_connectlistener"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.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></li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
</ul>
<p>Alias to
<a href="#all_net_netcreateconnectionoptions-connectlistener"><code>net.createConnection(options[, connectListener])</code></a>.</p>
<h4><code>net.connect(path[, connectListener])</code><span><a class="mark" href="#all_net_netconnectpath-connectlistener" id="all_net_netconnectpath-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_connect_path_connectlistener"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
</ul>
<p>Alias to
<a href="#all_net_netcreateconnectionpath-connectlistener"><code>net.createConnection(path[, connectListener])</code></a>.</p>
<h4><code>net.connect(port[, host][, connectListener])</code><span><a class="mark" href="#all_net_netconnectport-host-connectlistener" id="all_net_netconnectport-host-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_connect_port_host_connectlistener"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
</ul>
<p>Alias to
<a href="#all_net_netcreateconnectionport-host-connectlistener"><code>net.createConnection(port[, host][, connectListener])</code></a>.</p>
</section><section><h3><code>net.createConnection()</code><span><a class="mark" href="#all_net_netcreateconnection" id="all_net_netcreateconnection">#</a></span><a aria-hidden="true" class="legacy" id="net_net_createconnection"></a></h3>
<p>A factory function, which creates a new <a href="#all_net_class-netsocket"><code>net.Socket</code></a>,
immediately initiates connection with <a href="#all_net_socketconnect"><code>socket.connect()</code></a>,
then returns the <code>net.Socket</code> that starts the connection.</p>
<p>When the connection is established, a <a href="#all_net_event-connect"><code>'connect'</code></a> event will be emitted
on the returned socket. The last parameter <code>connectListener</code>, if supplied,
will be added as a listener for the <a href="#all_net_event-connect"><code>'connect'</code></a> event <strong>once</strong>.</p>
<p>Possible signatures:</p>
<ul>
<li><a href="#all_net_netcreateconnectionoptions-connectlistener"><code>net.createConnection(options[, connectListener])</code></a></li>
<li><a href="#all_net_netcreateconnectionpath-connectlistener"><code>net.createConnection(path[, connectListener])</code></a>
for <a href="#all_net_ipc-support">IPC</a> connections.</li>
<li><a href="#all_net_netcreateconnectionport-host-connectlistener"><code>net.createConnection(port[, host][, connectListener])</code></a>
for TCP connections.</li>
</ul>
<p>The <a href="#all_net_netconnect"><code>net.connect()</code></a> function is an alias to this function.</p>
<h4><code>net.createConnection(options[, connectListener])</code><span><a class="mark" href="#all_net_netcreateconnectionoptions-connectlistener" id="all_net_netcreateconnectionoptions-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_createconnection_options_connectlistener"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</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> Required. Will be passed to both the
<a href="#all_net_new-netsocketoptions"><code>new net.Socket([options])</code></a> call and the
<a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a>
method.</li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of the
<a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a> functions. If supplied, will be added as
a listener for the <a href="#all_net_event-connect"><code>'connect'</code></a> event on the returned socket once.</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The newly created socket used to start the connection.</li>
</ul>
<p>For available options, see
<a href="#all_net_new-netsocketoptions"><code>new net.Socket([options])</code></a>
and <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a>.</p>
<p>Additional options:</p>
<ul>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If set, will be used to call
<a href="#all_net_socketsettimeouttimeout-callback"><code>socket.setTimeout(timeout)</code></a> after the socket is created, but before
it starts the connection.</li>
</ul>
<p>Following is an example of a client of the echo server described
in the <a href="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer()</code></a> section:</p>
<pre class="with-59-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> net <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">const</span> client = net.<span class="hljs-title function_">createConnection</span>({ <span class="hljs-attr">port</span>: <span class="hljs-number">8124</span> }, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// 'connect' listener.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'connected to server!'</span>);
client.<span class="hljs-title function_">write</span>(<span class="hljs-string">'world!\r\n'</span>);
});
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>());
client.<span class="hljs-title function_">end</span>();
});
client.<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">'disconnected from server'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> client = net.<span class="hljs-title function_">createConnection</span>({ <span class="hljs-attr">port</span>: <span class="hljs-number">8124</span> }, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// 'connect' listener.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'connected to server!'</span>);
client.<span class="hljs-title function_">write</span>(<span class="hljs-string">'world!\r\n'</span>);
});
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>());
client.<span class="hljs-title function_">end</span>();
});
client.<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">'disconnected from server'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>To connect on the socket <code>/tmp/echo.sock</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> client = net.<span class="hljs-title function_">createConnection</span>({ <span class="hljs-attr">path</span>: <span class="hljs-string">'/tmp/echo.sock'</span> });</code> <button class="copy-button">copy</button></pre>
<p>Following is an example of a client using the <code>port</code> and <code>onread</code>
option. In this case, the <code>onread</code> option will be only used to call
<code>new net.Socket([options])</code> and the <code>port</code> option will be used to
call <code>socket.connect(options[, connectListener])</code>.</p>
<pre class="with-37-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> net <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
net.<span class="hljs-title function_">createConnection</span>({
<span class="hljs-attr">port</span>: <span class="hljs-number">8124</span>,
<span class="hljs-attr">onread</span>: {
<span class="hljs-comment">// Reuses a 4KiB Buffer for every read from the socket.</span>
<span class="hljs-attr">buffer</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">4</span> * <span class="hljs-number">1024</span>),
<span class="hljs-attr">callback</span>: <span class="hljs-keyword">function</span>(<span class="hljs-params">nread, buf</span>) {
<span class="hljs-comment">// Received data is available in `buf` from 0 to `nread`.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, nread));
},
},
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
net.<span class="hljs-title function_">createConnection</span>({
<span class="hljs-attr">port</span>: <span class="hljs-number">8124</span>,
<span class="hljs-attr">onread</span>: {
<span class="hljs-comment">// Reuses a 4KiB Buffer for every read from the socket.</span>
<span class="hljs-attr">buffer</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">4</span> * <span class="hljs-number">1024</span>),
<span class="hljs-attr">callback</span>: <span class="hljs-keyword">function</span>(<span class="hljs-params">nread, buf</span>) {
<span class="hljs-comment">// Received data is available in `buf` from 0 to `nread`.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, nread));
},
},
});</code><button class="copy-button">copy</button></pre>
<h4><code>net.createConnection(path[, connectListener])</code><span><a class="mark" href="#all_net_netcreateconnectionpath-connectlistener" id="all_net_netcreateconnectionpath-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_createconnection_path_connectlistener"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Path the socket should connect to. Will be passed to
<a href="#all_net_socketconnectpath-connectlistener"><code>socket.connect(path[, connectListener])</code></a>.
See <a href="#all_net_identifying-paths-for-ipc-connections">Identifying paths for IPC connections</a>.</li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of the
<a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a> functions, an "once" listener for the
<code>'connect'</code> event on the initiating socket. Will be passed to
<a href="#all_net_socketconnectpath-connectlistener"><code>socket.connect(path[, connectListener])</code></a>.</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The newly created socket used to start the connection.</li>
</ul>
<p>Initiates an <a href="#all_net_ipc-support">IPC</a> connection.</p>
<p>This function creates a new <a href="#all_net_class-netsocket"><code>net.Socket</code></a> with all options set to default,
immediately initiates connection with
<a href="#all_net_socketconnectpath-connectlistener"><code>socket.connect(path[, connectListener])</code></a>,
then returns the <code>net.Socket</code> that starts the connection.</p>
<h4><code>net.createConnection(port[, host][, connectListener])</code><span><a class="mark" href="#all_net_netcreateconnectionport-host-connectlistener" id="all_net_netcreateconnectionport-host-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_createconnection_port_host_connectlistener"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port the socket should connect to. Will be passed to
<a href="#all_net_socketconnectport-host-connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>.</li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host the socket should connect to. Will be passed to
<a href="#all_net_socketconnectport-host-connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>.
<strong>Default:</strong> <code>'localhost'</code>.</li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of the
<a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a> functions, an "once" listener for the
<code>'connect'</code> event on the initiating socket. Will be passed to
<a href="#all_net_socketconnectport-host-connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>.</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type"><net.Socket></a> The newly created socket used to start the connection.</li>
</ul>
<p>Initiates a TCP connection.</p>
<p>This function creates a new <a href="#all_net_class-netsocket"><code>net.Socket</code></a> with all options set to default,
immediately initiates connection with
<a href="#all_net_socketconnectport-host-connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>,
then returns the <code>net.Socket</code> that starts the connection.</p>
</section><section><h3><code>net.createServer([options][, connectionListener])</code><span><a class="mark" href="#all_net_netcreateserveroptions-connectionlistener" id="all_net_netcreateserveroptions-connectionlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_createserver_options_connectionlistener"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>The <code>highWaterMark</code> option is supported now.</p></td></tr>
<tr><td>v17.7.0, v16.15.0</td>
<td><p>The <code>noDelay</code>, <code>keepAlive</code>, and <code>keepAliveInitialDelay</code> options are supported now.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p>
<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 socket will
automatically end the writable side when the readable side ends.
<strong>Default:</strong> <code>false</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> Optionally overrides all <a href="#all_net_class-netsocket"><code>net.Socket</code></a>s'
<code>readableHighWaterMark</code> and <code>writableHighWaterMark</code>.
<strong>Default:</strong> See <a href="#all_stream_streamgetdefaulthighwatermarkobjectmode"><code>stream.getDefaultHighWaterMark()</code></a>.</li>
<li><code>keepAlive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, it enables keep-alive functionality
on the socket immediately after a new incoming connection is received,
similarly on what is done in <a href="#all_net_socketsetkeepaliveenable-initialdelay"><code>socket.setKeepAlive()</code></a>. <strong>Default:</strong>
<code>false</code>.</li>
<li><code>keepAliveInitialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If set to a positive number, it sets the
initial delay before the first keepalive probe is sent on an idle socket.
<strong>Default:</strong> <code>0</code>.</li>
<li><code>noDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, it disables the use of Nagle's
algorithm immediately after a new incoming connection is received.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>pauseOnConnect</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether the socket should be
paused on incoming connections. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>
<p><code>connectionListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Automatically set as a listener for the
<a href="#all_net_event-connection"><code>'connection'</code></a> event.</p>
</li>
<li>
<p>Returns: <a href="#all_net_class-netserver" class="type"><net.Server></a></p>
</li>
</ul>
<p>Creates a new TCP or <a href="#all_net_ipc-support">IPC</a> server.</p>
<p>If <code>allowHalfOpen</code> is set to <code>true</code>, when the other end of the socket
signals the end of transmission, the server will only send back the end of
transmission when <a href="#all_net_socketenddata-encoding-callback"><code>socket.end()</code></a> is explicitly called. For example, in the
context of TCP, when a FIN packed is received, a FIN packed is sent
back only when <a href="#all_net_socketenddata-encoding-callback"><code>socket.end()</code></a> is explicitly called. Until then the
connection is half-closed (non-readable but still writable). See <a href="#all_net_event-end"><code>'end'</code></a>
event and <a href="https://tools.ietf.org/html/rfc1122">RFC 1122</a> (section 4.2.2.13) for more information.</p>
<p>If <code>pauseOnConnect</code> is set to <code>true</code>, then the socket associated with each
incoming connection will be paused, and no data will be read from its handle.
This allows connections to be passed between processes without any data being
read by the original process. To begin reading data from a paused socket, call
<a href="#all_net_socketresume"><code>socket.resume()</code></a>.</p>
<p>The server can be a TCP server or an <a href="#all_net_ipc-support">IPC</a> server, depending on what it
<a href="#all_net_serverlisten"><code>listen()</code></a> to.</p>
<p>Here is an example of a TCP echo server which listens for connections
on port 8124:</p>
<pre class="with-40-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> net <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">c</span>) =></span> {
<span class="hljs-comment">// 'connection' listener.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'client connected'</span>);
c.<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">'client disconnected'</span>);
});
c.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello\r\n'</span>);
c.<span class="hljs-title function_">pipe</span>(c);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">throw</span> err;
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8124</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server bound'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">c</span>) =></span> {
<span class="hljs-comment">// 'connection' listener.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'client connected'</span>);
c.<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">'client disconnected'</span>);
});
c.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello\r\n'</span>);
c.<span class="hljs-title function_">pipe</span>(c);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">throw</span> err;
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8124</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server bound'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Test this by using <code>telnet</code>:</p>
<pre><code class="language-bash">telnet localhost 8124</code> <button class="copy-button">copy</button></pre>
<p>To listen on the socket <code>/tmp/echo.sock</code>:</p>
<pre><code class="language-js">server.<span class="hljs-title function_">listen</span>(<span class="hljs-string">'/tmp/echo.sock'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server bound'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Use <code>nc</code> to connect to a Unix domain socket server:</p>
<pre><code class="language-bash">nc -U /tmp/echo.sock</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>net.getDefaultAutoSelectFamily()</code><span><a class="mark" href="#all_net_netgetdefaultautoselectfamily" id="all_net_netgetdefaultautoselectfamily">#</a></span><a aria-hidden="true" class="legacy" id="net_net_getdefaultautoselectfamily"></a></h3>
<div class="api_metadata">
<span>Added in: v19.4.0</span>
</div>
<p>Gets the current default value of the <code>autoSelectFamily</code> option of <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.
The initial default value is <code>true</code>, unless the command line option
<code>--no-network-family-autoselection</code> is provided.</p>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> The current default value of the <code>autoSelectFamily</code> option.</li>
</ul>
</section><section><h3><code>net.setDefaultAutoSelectFamily(value)</code><span><a class="mark" href="#all_net_netsetdefaultautoselectfamilyvalue" id="all_net_netsetdefaultautoselectfamilyvalue">#</a></span><a aria-hidden="true" class="legacy" id="net_net_setdefaultautoselectfamily_value"></a></h3>
<div class="api_metadata">
<span>Added in: v19.4.0</span>
</div>
<p>Sets the default value of the <code>autoSelectFamily</code> option of <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.</p>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> The new default value.
The initial default value is <code>true</code>, unless the command line option
<code>--no-network-family-autoselection</code> is provided.</li>
</ul>
</section><section><h3><code>net.getDefaultAutoSelectFamilyAttemptTimeout()</code><span><a class="mark" href="#all_net_netgetdefaultautoselectfamilyattempttimeout" id="all_net_netgetdefaultautoselectfamilyattempttimeout">#</a></span><a aria-hidden="true" class="legacy" id="net_net_getdefaultautoselectfamilyattempttimeout"></a></h3>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p>Gets the current default value of the <code>autoSelectFamilyAttemptTimeout</code> option of <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.
The initial default value is <code>250</code> or the value specified via the command line
option <code>--network-family-autoselection-attempt-timeout</code>.</p>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The current default value of the <code>autoSelectFamilyAttemptTimeout</code> option.</li>
</ul>
</section><section><h3><code>net.setDefaultAutoSelectFamilyAttemptTimeout(value)</code><span><a class="mark" href="#all_net_netsetdefaultautoselectfamilyattempttimeoutvalue" id="all_net_netsetdefaultautoselectfamilyattempttimeoutvalue">#</a></span><a aria-hidden="true" class="legacy" id="net_net_setdefaultautoselectfamilyattempttimeout_value"></a></h3>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p>Sets the default value of the <code>autoSelectFamilyAttemptTimeout</code> option of <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.</p>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The new default value, which must be a positive number. If the number is less than <code>10</code>,
the value <code>10</code> is used instead. The initial default value is <code>250</code> or the value specified via the command line
option <code>--network-family-autoselection-attempt-timeout</code>.</li>
</ul>
</section><section><h3><code>net.isIP(input)</code><span><a class="mark" href="#all_net_netisipinput" id="all_net_netisipinput">#</a></span><a aria-hidden="true" class="legacy" id="net_net_isip_input"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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 <code>6</code> if <code>input</code> is an IPv6 address. Returns <code>4</code> if <code>input</code> is an IPv4
address in <a href="https://en.wikipedia.org/wiki/Dot-decimal_notation">dot-decimal notation</a> with no leading zeroes. Otherwise, returns
<code>0</code>.</p>
<pre><code class="language-js">net.<span class="hljs-title function_">isIP</span>(<span class="hljs-string">'::1'</span>); <span class="hljs-comment">// returns 6</span>
net.<span class="hljs-title function_">isIP</span>(<span class="hljs-string">'127.0.0.1'</span>); <span class="hljs-comment">// returns 4</span>
net.<span class="hljs-title function_">isIP</span>(<span class="hljs-string">'127.000.000.001'</span>); <span class="hljs-comment">// returns 0</span>
net.<span class="hljs-title function_">isIP</span>(<span class="hljs-string">'127.0.0.1/24'</span>); <span class="hljs-comment">// returns 0</span>
net.<span class="hljs-title function_">isIP</span>(<span class="hljs-string">'fhqwhgads'</span>); <span class="hljs-comment">// returns 0</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>net.isIPv4(input)</code><span><a class="mark" href="#all_net_netisipv4input" id="all_net_netisipv4input">#</a></span><a aria-hidden="true" class="legacy" id="net_net_isipv4_input"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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 <code>true</code> if <code>input</code> is an IPv4 address in <a href="https://en.wikipedia.org/wiki/Dot-decimal_notation">dot-decimal notation</a> with no
leading zeroes. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">net.<span class="hljs-title function_">isIPv4</span>(<span class="hljs-string">'127.0.0.1'</span>); <span class="hljs-comment">// returns true</span>
net.<span class="hljs-title function_">isIPv4</span>(<span class="hljs-string">'127.000.000.001'</span>); <span class="hljs-comment">// returns false</span>
net.<span class="hljs-title function_">isIPv4</span>(<span class="hljs-string">'127.0.0.1/24'</span>); <span class="hljs-comment">// returns false</span>
net.<span class="hljs-title function_">isIPv4</span>(<span class="hljs-string">'fhqwhgads'</span>); <span class="hljs-comment">// returns false</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>net.isIPv6(input)</code><span><a class="mark" href="#all_net_netisipv6input" id="all_net_netisipv6input">#</a></span><a aria-hidden="true" class="legacy" id="net_net_isipv6_input"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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 <code>true</code> if <code>input</code> is an IPv6 address. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">net.<span class="hljs-title function_">isIPv6</span>(<span class="hljs-string">'::1'</span>); <span class="hljs-comment">// returns true</span>
net.<span class="hljs-title function_">isIPv6</span>(<span class="hljs-string">'fhqwhgads'</span>); <span class="hljs-comment">// returns false</span></code> <button class="copy-button">copy</button></pre></section>
</section>
<section><h2>OS<span><a class="mark" href="#all_os_os" id="all_os_os">#</a></span><a aria-hidden="true" class="legacy" id="os_os"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/os.js">lib/os.js</a></p>
<p>The <code>node:os</code> module provides operating system-related utility methods and
properties. It can be accessed using:</p>
<pre class="with-30-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> os <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> os = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3><code>os.EOL</code><span><a class="mark" href="#all_os_oseol" id="all_os_oseol">#</a></span><a aria-hidden="true" class="legacy" id="os_os_eol"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.8</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The operating system-specific end-of-line marker.</p>
<ul>
<li><code>\n</code> on POSIX</li>
<li><code>\r\n</code> on Windows</li>
</ul>
</section><section><h3><code>os.availableParallelism()</code><span><a class="mark" href="#all_os_osavailableparallelism" id="all_os_osavailableparallelism">#</a></span><a aria-hidden="true" class="legacy" id="os_os_availableparallelism"></a></h3>
<div class="api_metadata">
<span>Added in: v19.4.0, v18.14.0</span>
</div>
<ul>
<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 an estimate of the default amount of parallelism a program should use.
Always returns a value greater than zero.</p>
<p>This function is a small wrapper about libuv's <a href="https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism"><code>uv_available_parallelism()</code></a>.</p>
</section><section><h3><code>os.arch()</code><span><a class="mark" href="#all_os_osarch" id="all_os_osarch">#</a></span><a aria-hidden="true" class="legacy" id="os_os_arch"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the operating system CPU architecture for which the Node.js binary was
compiled. Possible values are <code>'arm'</code>, <code>'arm64'</code>, <code>'ia32'</code>, <code>'loong64'</code>,
<code>'mips'</code>, <code>'mipsel'</code>, <code>'ppc'</code>, <code>'ppc64'</code>, <code>'riscv64'</code>, <code>'s390'</code>, <code>'s390x'</code>,
and <code>'x64'</code>.</p>
<p>The return value is equivalent to <a href="#all_process_processarch"><code>process.arch</code></a>.</p>
</section><section><h3><code>os.constants</code><span><a class="mark" href="#all_os_osconstants" id="all_os_osconstants">#</a></span><a aria-hidden="true" class="legacy" id="os_os_constants"></a></h3>
<div class="api_metadata">
<span>Added in: v6.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Contains commonly used operating system-specific constants for error codes,
process signals, and so on. The specific constants defined are described in
<a href="#all_os_os-constants">OS constants</a>.</p>
</section><section><h3><code>os.cpus()</code><span><a class="mark" href="#all_os_oscpus" id="all_os_oscpus">#</a></span><a aria-hidden="true" class="legacy" id="os_os_cpus"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li>
</ul>
<p>Returns an array of objects containing information about each logical CPU core.
The array will be empty if no CPU information is available, such as if the
<code>/proc</code> file system is unavailable.</p>
<p>The properties included on each object include:</p>
<ul>
<li><code>model</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>speed</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> (in MHz)</li>
<li><code>times</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>user</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds the CPU has spent in user mode.</li>
<li><code>nice</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds the CPU has spent in nice mode.</li>
<li><code>sys</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds the CPU has spent in sys mode.</li>
<li><code>idle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds the CPU has spent in idle mode.</li>
<li><code>irq</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds the CPU has spent in irq mode.</li>
</ul>
</li>
</ul>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js">[
{
<span class="hljs-attr">model</span>: <span class="hljs-string">'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz'</span>,
<span class="hljs-attr">speed</span>: <span class="hljs-number">2926</span>,
<span class="hljs-attr">times</span>: {
<span class="hljs-attr">user</span>: <span class="hljs-number">252020</span>,
<span class="hljs-attr">nice</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">sys</span>: <span class="hljs-number">30340</span>,
<span class="hljs-attr">idle</span>: <span class="hljs-number">1070356870</span>,
<span class="hljs-attr">irq</span>: <span class="hljs-number">0</span>,
},
},
{
<span class="hljs-attr">model</span>: <span class="hljs-string">'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz'</span>,
<span class="hljs-attr">speed</span>: <span class="hljs-number">2926</span>,
<span class="hljs-attr">times</span>: {
<span class="hljs-attr">user</span>: <span class="hljs-number">306960</span>,
<span class="hljs-attr">nice</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">sys</span>: <span class="hljs-number">26980</span>,
<span class="hljs-attr">idle</span>: <span class="hljs-number">1071569080</span>,
<span class="hljs-attr">irq</span>: <span class="hljs-number">0</span>,
},
},
{
<span class="hljs-attr">model</span>: <span class="hljs-string">'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz'</span>,
<span class="hljs-attr">speed</span>: <span class="hljs-number">2926</span>,
<span class="hljs-attr">times</span>: {
<span class="hljs-attr">user</span>: <span class="hljs-number">248450</span>,
<span class="hljs-attr">nice</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">sys</span>: <span class="hljs-number">21750</span>,
<span class="hljs-attr">idle</span>: <span class="hljs-number">1070919370</span>,
<span class="hljs-attr">irq</span>: <span class="hljs-number">0</span>,
},
},
{
<span class="hljs-attr">model</span>: <span class="hljs-string">'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz'</span>,
<span class="hljs-attr">speed</span>: <span class="hljs-number">2926</span>,
<span class="hljs-attr">times</span>: {
<span class="hljs-attr">user</span>: <span class="hljs-number">256880</span>,
<span class="hljs-attr">nice</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">sys</span>: <span class="hljs-number">19430</span>,
<span class="hljs-attr">idle</span>: <span class="hljs-number">1070905480</span>,
<span class="hljs-attr">irq</span>: <span class="hljs-number">20</span>,
},
},
]</code> <button class="copy-button">copy</button></pre>
<p><code>nice</code> values are POSIX-only. On Windows, the <code>nice</code> values of all processors
are always 0.</p>
<p><code>os.cpus().length</code> should not be used to calculate the amount of parallelism
available to an application. Use
<a href="#all_os_osavailableparallelism"><code>os.availableParallelism()</code></a> for this purpose.</p>
</section><section><h3><code>os.devNull</code><span><a class="mark" href="#all_os_osdevnull" id="all_os_osdevnull">#</a></span><a aria-hidden="true" class="legacy" id="os_os_devnull"></a></h3>
<div class="api_metadata">
<span>Added in: v16.3.0, v14.18.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The platform-specific file path of the null device.</p>
<ul>
<li><code>\\.\nul</code> on Windows</li>
<li><code>/dev/null</code> on POSIX</li>
</ul>
</section><section><h3><code>os.endianness()</code><span><a class="mark" href="#all_os_osendianness" id="all_os_osendianness">#</a></span><a aria-hidden="true" class="legacy" id="os_os_endianness"></a></h3>
<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/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns a string identifying the endianness of the CPU for which the Node.js
binary was compiled.</p>
<p>Possible values are <code>'BE'</code> for big endian and <code>'LE'</code> for little endian.</p>
</section><section><h3><code>os.freemem()</code><span><a class="mark" href="#all_os_osfreemem" id="all_os_osfreemem">#</a></span><a aria-hidden="true" class="legacy" id="os_os_freemem"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div>
<ul>
<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 amount of free system memory in bytes as an integer.</p>
</section><section><h3><code>os.getPriority([pid])</code><span><a class="mark" href="#all_os_osgetprioritypid" id="all_os_osgetprioritypid">#</a></span><a aria-hidden="true" class="legacy" id="os_os_getpriority_pid"></a></h3>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li><code>pid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The process ID to retrieve scheduling priority for.
<strong>Default:</strong> <code>0</code>.</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 scheduling priority for the process specified by <code>pid</code>. If <code>pid</code> is
not provided or is <code>0</code>, the priority of the current process is returned.</p>
</section><section><h3><code>os.homedir()</code><span><a class="mark" href="#all_os_oshomedir" id="all_os_oshomedir">#</a></span><a aria-hidden="true" class="legacy" id="os_os_homedir"></a></h3>
<div class="api_metadata">
<span>Added in: v2.3.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the string path of the current user's home directory.</p>
<p>On POSIX, it uses the <code>$HOME</code> environment variable if defined. Otherwise it
uses the <a href="https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID">effective UID</a> to look up the user's home directory.</p>
<p>On Windows, it uses the <code>USERPROFILE</code> environment variable if defined.
Otherwise it uses the path to the profile directory of the current user.</p>
</section><section><h3><code>os.hostname()</code><span><a class="mark" href="#all_os_oshostname" id="all_os_oshostname">#</a></span><a aria-hidden="true" class="legacy" id="os_os_hostname"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the host name of the operating system as a string.</p>
</section><section><h3><code>os.loadavg()</code><span><a class="mark" href="#all_os_osloadavg" id="all_os_osloadavg">#</a></span><a aria-hidden="true" class="legacy" id="os_os_loadavg"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number[]></a></li>
</ul>
<p>Returns an array containing the 1, 5, and 15 minute load averages.</p>
<p>The load average is a measure of system activity calculated by the operating
system and expressed as a fractional number.</p>
<p>The load average is a Unix-specific concept. On Windows, the return value is
always <code>[0, 0, 0]</code>.</p>
</section><section><h3><code>os.machine()</code><span><a class="mark" href="#all_os_osmachine" id="all_os_osmachine">#</a></span><a aria-hidden="true" class="legacy" id="os_os_machine"></a></h3>
<div class="api_metadata">
<span>Added in: v18.9.0, v16.18.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the machine type as a string, such as <code>arm</code>, <code>arm64</code>, <code>aarch64</code>,
<code>mips</code>, <code>mips64</code>, <code>ppc64</code>, <code>ppc64le</code>, <code>s390</code>, <code>s390x</code>, <code>i386</code>, <code>i686</code>, <code>x86_64</code>.</p>
<p>On POSIX systems, the machine type is determined by calling
<a href="https://linux.die.net/man/3/uname"><code>uname(3)</code></a>. On Windows, <code>RtlGetVersion()</code> is used, and if it is not
available, <code>GetVersionExW()</code> will be used. See
<a href="https://en.wikipedia.org/wiki/Uname#Examples">https://en.wikipedia.org/wiki/Uname#Examples</a> for more information.</p>
</section><section><h3><code>os.networkInterfaces()</code><span><a class="mark" href="#all_os_osnetworkinterfaces" id="all_os_osnetworkinterfaces">#</a></span><a aria-hidden="true" class="legacy" id="os_os_networkinterfaces"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.4.0</td>
<td><p>The <code>family</code> property now returns a string instead of a number.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>family</code> property now returns a number instead of a string.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns an object containing network interfaces that have been assigned a
network address.</p>
<p>Each key on the returned object identifies a network interface. The associated
value is an array of objects that each describe an assigned network address.</p>
<p>The properties available on the assigned network address object include:</p>
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The assigned IPv4 or IPv6 address</li>
<li><code>netmask</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The IPv4 or IPv6 network mask</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>IPv4</code> or <code>IPv6</code></li>
<li><code>mac</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The MAC address of the network interface</li>
<li><code>internal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the network interface is a loopback or
similar interface that is not remotely accessible; otherwise <code>false</code></li>
<li><code>scopeid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The numeric IPv6 scope ID (only specified when <code>family</code>
is <code>IPv6</code>)</li>
<li><code>cidr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The assigned IPv4 or IPv6 address with the routing prefix
in CIDR notation. If the <code>netmask</code> is invalid, this property is set
to <code>null</code>.</li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
<span class="hljs-attr">lo</span>: [
{
<span class="hljs-attr">address</span>: <span class="hljs-string">'127.0.0.1'</span>,
<span class="hljs-attr">netmask</span>: <span class="hljs-string">'255.0.0.0'</span>,
<span class="hljs-attr">family</span>: <span class="hljs-string">'IPv4'</span>,
<span class="hljs-attr">mac</span>: <span class="hljs-string">'00:00:00:00:00:00'</span>,
<span class="hljs-attr">internal</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">cidr</span>: <span class="hljs-string">'127.0.0.1/8'</span>
},
{
<span class="hljs-attr">address</span>: <span class="hljs-string">'::1'</span>,
<span class="hljs-attr">netmask</span>: <span class="hljs-string">'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'</span>,
<span class="hljs-attr">family</span>: <span class="hljs-string">'IPv6'</span>,
<span class="hljs-attr">mac</span>: <span class="hljs-string">'00:00:00:00:00:00'</span>,
<span class="hljs-attr">scopeid</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">internal</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">cidr</span>: <span class="hljs-string">'::1/128'</span>
}
],
<span class="hljs-attr">eth0</span>: [
{
<span class="hljs-attr">address</span>: <span class="hljs-string">'192.168.1.108'</span>,
<span class="hljs-attr">netmask</span>: <span class="hljs-string">'255.255.255.0'</span>,
<span class="hljs-attr">family</span>: <span class="hljs-string">'IPv4'</span>,
<span class="hljs-attr">mac</span>: <span class="hljs-string">'01:02:03:0a:0b:0c'</span>,
<span class="hljs-attr">internal</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">cidr</span>: <span class="hljs-string">'192.168.1.108/24'</span>
},
{
<span class="hljs-attr">address</span>: <span class="hljs-string">'fe80::a00:27ff:fe4e:66a1'</span>,
<span class="hljs-attr">netmask</span>: <span class="hljs-string">'ffff:ffff:ffff:ffff::'</span>,
<span class="hljs-attr">family</span>: <span class="hljs-string">'IPv6'</span>,
<span class="hljs-attr">mac</span>: <span class="hljs-string">'01:02:03:0a:0b:0c'</span>,
<span class="hljs-attr">scopeid</span>: <span class="hljs-number">1</span>,
<span class="hljs-attr">internal</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">cidr</span>: <span class="hljs-string">'fe80::a00:27ff:fe4e:66a1/64'</span>
}
]
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>os.platform()</code><span><a class="mark" href="#all_os_osplatform" id="all_os_osplatform">#</a></span><a aria-hidden="true" class="legacy" id="os_os_platform"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns a string identifying the operating system platform for which
the Node.js binary was compiled. The value is set at compile time.
Possible values are <code>'aix'</code>, <code>'darwin'</code>, <code>'freebsd'</code>,<code>'linux'</code>,
<code>'openbsd'</code>, <code>'sunos'</code>, and <code>'win32'</code>.</p>
<p>The return value is equivalent to <a href="#all_process_processplatform"><code>process.platform</code></a>.</p>
<p>The value <code>'android'</code> may also be returned if Node.js is built on the Android
operating system. <a href="https://github.com/nodejs/node/blob/HEAD/BUILDING.md#android">Android support is experimental</a>.</p>
</section><section><h3><code>os.release()</code><span><a class="mark" href="#all_os_osrelease" id="all_os_osrelease">#</a></span><a aria-hidden="true" class="legacy" id="os_os_release"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the operating system as a string.</p>
<p>On POSIX systems, the operating system release is determined by calling
<a href="https://linux.die.net/man/3/uname"><code>uname(3)</code></a>. On Windows, <code>GetVersionExW()</code> is used. See
<a href="https://en.wikipedia.org/wiki/Uname#Examples">https://en.wikipedia.org/wiki/Uname#Examples</a> for more information.</p>
</section><section><h3><code>os.setPriority([pid, ]priority)</code><span><a class="mark" href="#all_os_ossetprioritypid-priority" id="all_os_ossetprioritypid-priority">#</a></span><a aria-hidden="true" class="legacy" id="os_os_setpriority_pid_priority"></a></h3>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li><code>pid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The process ID to set scheduling priority for.
<strong>Default:</strong> <code>0</code>.</li>
<li><code>priority</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The scheduling priority to assign to the process.</li>
</ul>
<p>Attempts to set the scheduling priority for the process specified by <code>pid</code>. If
<code>pid</code> is not provided or is <code>0</code>, the process ID of the current process is used.</p>
<p>The <code>priority</code> input must be an integer between <code>-20</code> (high priority) and <code>19</code>
(low priority). Due to differences between Unix priority levels and Windows
priority classes, <code>priority</code> is mapped to one of six priority constants in
<code>os.constants.priority</code>. When retrieving a process priority level, this range
mapping may cause the return value to be slightly different on Windows. To avoid
confusion, set <code>priority</code> to one of the priority constants.</p>
<p>On Windows, setting priority to <code>PRIORITY_HIGHEST</code> requires elevated user
privileges. Otherwise the set priority will be silently reduced to
<code>PRIORITY_HIGH</code>.</p>
</section><section><h3><code>os.tmpdir()</code><span><a class="mark" href="#all_os_ostmpdir" id="all_os_ostmpdir">#</a></span><a aria-hidden="true" class="legacy" id="os_os_tmpdir"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v2.0.0</td>
<td><p>This function is now cross-platform consistent and no longer returns a path with a trailing slash on any platform.</p></td></tr>
<tr><td>v0.9.9</td>
<td><p><span>Added in: v0.9.9</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the operating system's default directory for temporary files as a
string.</p>
<p>On Windows, the result can be overridden by <code>TEMP</code> and <code>TMP</code> environment variables, and
<code>TEMP</code> takes precedence over <code>TMP</code>. If neither is set, it defaults to <code>%SystemRoot%\temp</code>
or <code>%windir%\temp</code>.</p>
<p>On non-Windows platforms, <code>TMPDIR</code>, <code>TMP</code> and <code>TEMP</code> environment variables will be checked
to override the result of this method, in the described order. If none of them is set, it
defaults to <code>/tmp</code>.</p>
<p>Some operating system distributions would either configure <code>TMPDIR</code> (non-Windows) or
<code>TEMP</code> and <code>TMP</code> (Windows) by default without additional configurations by the system
administrators. The result of <code>os.tmpdir()</code> typically reflects the system preference
unless it's explicitly overridden by the users.</p>
</section><section><h3><code>os.totalmem()</code><span><a class="mark" href="#all_os_ostotalmem" id="all_os_ostotalmem">#</a></span><a aria-hidden="true" class="legacy" id="os_os_totalmem"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div>
<ul>
<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 total amount of system memory in bytes as an integer.</p>
</section><section><h3><code>os.type()</code><span><a class="mark" href="#all_os_ostype" id="all_os_ostype">#</a></span><a aria-hidden="true" class="legacy" id="os_os_type"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the operating system name as returned by <a href="https://linux.die.net/man/3/uname"><code>uname(3)</code></a>. For example, it
returns <code>'Linux'</code> on Linux, <code>'Darwin'</code> on macOS, and <code>'Windows_NT'</code> on Windows.</p>
<p>See <a href="https://en.wikipedia.org/wiki/Uname#Examples">https://en.wikipedia.org/wiki/Uname#Examples</a> for additional information
about the output of running <a href="https://linux.die.net/man/3/uname"><code>uname(3)</code></a> on various operating systems.</p>
</section><section><h3><code>os.uptime()</code><span><a class="mark" href="#all_os_osuptime" id="all_os_osuptime">#</a></span><a aria-hidden="true" class="legacy" id="os_os_uptime"></a></h3>
<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 result of this function no longer contains a fraction component on Windows.</p></td></tr>
<tr><td>v0.3.3</td>
<td><p><span>Added in: v0.3.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<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 system uptime in number of seconds.</p>
</section><section><h3><code>os.userInfo([options])</code><span><a class="mark" href="#all_os_osuserinfooptions" id="all_os_osuserinfooptions">#</a></span><a aria-hidden="true" class="legacy" id="os_os_userinfo_options"></a></h3>
<div class="api_metadata">
<span>Added in: v6.0.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>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Character encoding used to interpret resulting strings.
If <code>encoding</code> is set to <code>'buffer'</code>, the <code>username</code>, <code>shell</code>, and <code>homedir</code>
values will be <code>Buffer</code> instances. <strong>Default:</strong> <code>'utf8'</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns information about the currently effective user. On POSIX platforms,
this is typically a subset of the password file. The returned object includes
the <code>username</code>, <code>uid</code>, <code>gid</code>, <code>shell</code>, and <code>homedir</code>. On Windows, the <code>uid</code> and
<code>gid</code> fields are <code>-1</code>, and <code>shell</code> is <code>null</code>.</p>
<p>The value of <code>homedir</code> returned by <code>os.userInfo()</code> is provided by the operating
system. This differs from the result of <code>os.homedir()</code>, which queries
environment variables for the home directory before falling back to the
operating system response.</p>
<p>Throws a <a href="#all_errors_class-systemerror"><code>SystemError</code></a> if a user has no <code>username</code> or <code>homedir</code>.</p>
</section><section><h3><code>os.version()</code><span><a class="mark" href="#all_os_osversion" id="all_os_osversion">#</a></span><a aria-hidden="true" class="legacy" id="os_os_version"></a></h3>
<div class="api_metadata">
<span>Added in: v13.11.0, v12.17.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns a string identifying the kernel version.</p>
<p>On POSIX systems, the operating system release is determined by calling
<a href="https://linux.die.net/man/3/uname"><code>uname(3)</code></a>. On Windows, <code>RtlGetVersion()</code> is used, and if it is not
available, <code>GetVersionExW()</code> will be used. See
<a href="https://en.wikipedia.org/wiki/Uname#Examples">https://en.wikipedia.org/wiki/Uname#Examples</a> for more information.</p>
</section><section><h3>OS constants<span><a class="mark" href="#all_os_os-constants" id="all_os_os-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_os_constants_1"></a></h3>
<p>The following constants are exported by <code>os.constants</code>.</p>
<p>Not all constants will be available on every operating system.</p>
<h4>Signal constants<span><a class="mark" href="#all_os_signal-constants" id="all_os_signal-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_signal_constants"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.11.0</td>
<td><p>Added support for <code>SIGINFO</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The following signal constants are exported by <code>os.constants.signals</code>.</p>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>SIGHUP</code></td>
<td>Sent to indicate when a controlling terminal is closed or a parent
process exits.</td>
</tr>
<tr>
<td><code>SIGINT</code></td>
<td>Sent to indicate when a user wishes to interrupt a process
(<kbd>Ctrl</kbd>+<kbd>C</kbd>).</td>
</tr>
<tr>
<td><code>SIGQUIT</code></td>
<td>Sent to indicate when a user wishes to terminate a process and perform a
core dump.</td>
</tr>
<tr>
<td><code>SIGILL</code></td>
<td>Sent to a process to notify that it has attempted to perform an illegal,
malformed, unknown, or privileged instruction.</td>
</tr>
<tr>
<td><code>SIGTRAP</code></td>
<td>Sent to a process when an exception has occurred.</td>
</tr>
<tr>
<td><code>SIGABRT</code></td>
<td>Sent to a process to request that it abort.</td>
</tr>
<tr>
<td><code>SIGIOT</code></td>
<td>Synonym for <code>SIGABRT</code></td>
</tr>
<tr>
<td><code>SIGBUS</code></td>
<td>Sent to a process to notify that it has caused a bus error.</td>
</tr>
<tr>
<td><code>SIGFPE</code></td>
<td>Sent to a process to notify that it has performed an illegal arithmetic
operation.</td>
</tr>
<tr>
<td><code>SIGKILL</code></td>
<td>Sent to a process to terminate it immediately.</td>
</tr>
<tr>
<td><code>SIGUSR1</code> <code>SIGUSR2</code></td>
<td>Sent to a process to identify user-defined conditions.</td>
</tr>
<tr>
<td><code>SIGSEGV</code></td>
<td>Sent to a process to notify of a segmentation fault.</td>
</tr>
<tr>
<td><code>SIGPIPE</code></td>
<td>Sent to a process when it has attempted to write to a disconnected
pipe.</td>
</tr>
<tr>
<td><code>SIGALRM</code></td>
<td>Sent to a process when a system timer elapses.</td>
</tr>
<tr>
<td><code>SIGTERM</code></td>
<td>Sent to a process to request termination.</td>
</tr>
<tr>
<td><code>SIGCHLD</code></td>
<td>Sent to a process when a child process terminates.</td>
</tr>
<tr>
<td><code>SIGSTKFLT</code></td>
<td>Sent to a process to indicate a stack fault on a coprocessor.</td>
</tr>
<tr>
<td><code>SIGCONT</code></td>
<td>Sent to instruct the operating system to continue a paused process.</td>
</tr>
<tr>
<td><code>SIGSTOP</code></td>
<td>Sent to instruct the operating system to halt a process.</td>
</tr>
<tr>
<td><code>SIGTSTP</code></td>
<td>Sent to a process to request it to stop.</td>
</tr>
<tr>
<td><code>SIGBREAK</code></td>
<td>Sent to indicate when a user wishes to interrupt a process.</td>
</tr>
<tr>
<td><code>SIGTTIN</code></td>
<td>Sent to a process when it reads from the TTY while in the
background.</td>
</tr>
<tr>
<td><code>SIGTTOU</code></td>
<td>Sent to a process when it writes to the TTY while in the
background.</td>
</tr>
<tr>
<td><code>SIGURG</code></td>
<td>Sent to a process when a socket has urgent data to read.</td>
</tr>
<tr>
<td><code>SIGXCPU</code></td>
<td>Sent to a process when it has exceeded its limit on CPU usage.</td>
</tr>
<tr>
<td><code>SIGXFSZ</code></td>
<td>Sent to a process when it grows a file larger than the maximum
allowed.</td>
</tr>
<tr>
<td><code>SIGVTALRM</code></td>
<td>Sent to a process when a virtual timer has elapsed.</td>
</tr>
<tr>
<td><code>SIGPROF</code></td>
<td>Sent to a process when a system timer has elapsed.</td>
</tr>
<tr>
<td><code>SIGWINCH</code></td>
<td>Sent to a process when the controlling terminal has changed its
size.</td>
</tr>
<tr>
<td><code>SIGIO</code></td>
<td>Sent to a process when I/O is available.</td>
</tr>
<tr>
<td><code>SIGPOLL</code></td>
<td>Synonym for <code>SIGIO</code></td>
</tr>
<tr>
<td><code>SIGLOST</code></td>
<td>Sent to a process when a file lock has been lost.</td>
</tr>
<tr>
<td><code>SIGPWR</code></td>
<td>Sent to a process to notify of a power failure.</td>
</tr>
<tr>
<td><code>SIGINFO</code></td>
<td>Synonym for <code>SIGPWR</code></td>
</tr>
<tr>
<td><code>SIGSYS</code></td>
<td>Sent to a process to notify of a bad argument.</td>
</tr>
<tr>
<td><code>SIGUNUSED</code></td>
<td>Synonym for <code>SIGSYS</code></td>
</tr>
</tbody></table>
<h4>Error constants<span><a class="mark" href="#all_os_error-constants" id="all_os_error-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_error_constants"></a></h4>
<p>The following error constants are exported by <code>os.constants.errno</code>.</p>
<h5>POSIX error constants<span><a class="mark" href="#all_os_posix-error-constants" id="all_os_posix-error-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_posix_error_constants"></a></h5>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>E2BIG</code></td>
<td>Indicates that the list of arguments is longer than expected.</td>
</tr>
<tr>
<td><code>EACCES</code></td>
<td>Indicates that the operation did not have sufficient permissions.</td>
</tr>
<tr>
<td><code>EADDRINUSE</code></td>
<td>Indicates that the network address is already in use.</td>
</tr>
<tr>
<td><code>EADDRNOTAVAIL</code></td>
<td>Indicates that the network address is currently unavailable for
use.</td>
</tr>
<tr>
<td><code>EAFNOSUPPORT</code></td>
<td>Indicates that the network address family is not supported.</td>
</tr>
<tr>
<td><code>EAGAIN</code></td>
<td>Indicates that there is no data available and to try the
operation again later.</td>
</tr>
<tr>
<td><code>EALREADY</code></td>
<td>Indicates that the socket already has a pending connection in
progress.</td>
</tr>
<tr>
<td><code>EBADF</code></td>
<td>Indicates that a file descriptor is not valid.</td>
</tr>
<tr>
<td><code>EBADMSG</code></td>
<td>Indicates an invalid data message.</td>
</tr>
<tr>
<td><code>EBUSY</code></td>
<td>Indicates that a device or resource is busy.</td>
</tr>
<tr>
<td><code>ECANCELED</code></td>
<td>Indicates that an operation was canceled.</td>
</tr>
<tr>
<td><code>ECHILD</code></td>
<td>Indicates that there are no child processes.</td>
</tr>
<tr>
<td><code>ECONNABORTED</code></td>
<td>Indicates that the network connection has been aborted.</td>
</tr>
<tr>
<td><code>ECONNREFUSED</code></td>
<td>Indicates that the network connection has been refused.</td>
</tr>
<tr>
<td><code>ECONNRESET</code></td>
<td>Indicates that the network connection has been reset.</td>
</tr>
<tr>
<td><code>EDEADLK</code></td>
<td>Indicates that a resource deadlock has been avoided.</td>
</tr>
<tr>
<td><code>EDESTADDRREQ</code></td>
<td>Indicates that a destination address is required.</td>
</tr>
<tr>
<td><code>EDOM</code></td>
<td>Indicates that an argument is out of the domain of the function.</td>
</tr>
<tr>
<td><code>EDQUOT</code></td>
<td>Indicates that the disk quota has been exceeded.</td>
</tr>
<tr>
<td><code>EEXIST</code></td>
<td>Indicates that the file already exists.</td>
</tr>
<tr>
<td><code>EFAULT</code></td>
<td>Indicates an invalid pointer address.</td>
</tr>
<tr>
<td><code>EFBIG</code></td>
<td>Indicates that the file is too large.</td>
</tr>
<tr>
<td><code>EHOSTUNREACH</code></td>
<td>Indicates that the host is unreachable.</td>
</tr>
<tr>
<td><code>EIDRM</code></td>
<td>Indicates that the identifier has been removed.</td>
</tr>
<tr>
<td><code>EILSEQ</code></td>
<td>Indicates an illegal byte sequence.</td>
</tr>
<tr>
<td><code>EINPROGRESS</code></td>
<td>Indicates that an operation is already in progress.</td>
</tr>
<tr>
<td><code>EINTR</code></td>
<td>Indicates that a function call was interrupted.</td>
</tr>
<tr>
<td><code>EINVAL</code></td>
<td>Indicates that an invalid argument was provided.</td>
</tr>
<tr>
<td><code>EIO</code></td>
<td>Indicates an otherwise unspecified I/O error.</td>
</tr>
<tr>
<td><code>EISCONN</code></td>
<td>Indicates that the socket is connected.</td>
</tr>
<tr>
<td><code>EISDIR</code></td>
<td>Indicates that the path is a directory.</td>
</tr>
<tr>
<td><code>ELOOP</code></td>
<td>Indicates too many levels of symbolic links in a path.</td>
</tr>
<tr>
<td><code>EMFILE</code></td>
<td>Indicates that there are too many open files.</td>
</tr>
<tr>
<td><code>EMLINK</code></td>
<td>Indicates that there are too many hard links to a file.</td>
</tr>
<tr>
<td><code>EMSGSIZE</code></td>
<td>Indicates that the provided message is too long.</td>
</tr>
<tr>
<td><code>EMULTIHOP</code></td>
<td>Indicates that a multihop was attempted.</td>
</tr>
<tr>
<td><code>ENAMETOOLONG</code></td>
<td>Indicates that the filename is too long.</td>
</tr>
<tr>
<td><code>ENETDOWN</code></td>
<td>Indicates that the network is down.</td>
</tr>
<tr>
<td><code>ENETRESET</code></td>
<td>Indicates that the connection has been aborted by the network.</td>
</tr>
<tr>
<td><code>ENETUNREACH</code></td>
<td>Indicates that the network is unreachable.</td>
</tr>
<tr>
<td><code>ENFILE</code></td>
<td>Indicates too many open files in the system.</td>
</tr>
<tr>
<td><code>ENOBUFS</code></td>
<td>Indicates that no buffer space is available.</td>
</tr>
<tr>
<td><code>ENODATA</code></td>
<td>Indicates that no message is available on the stream head read
queue.</td>
</tr>
<tr>
<td><code>ENODEV</code></td>
<td>Indicates that there is no such device.</td>
</tr>
<tr>
<td><code>ENOENT</code></td>
<td>Indicates that there is no such file or directory.</td>
</tr>
<tr>
<td><code>ENOEXEC</code></td>
<td>Indicates an exec format error.</td>
</tr>
<tr>
<td><code>ENOLCK</code></td>
<td>Indicates that there are no locks available.</td>
</tr>
<tr>
<td><code>ENOLINK</code></td>
<td>Indications that a link has been severed.</td>
</tr>
<tr>
<td><code>ENOMEM</code></td>
<td>Indicates that there is not enough space.</td>
</tr>
<tr>
<td><code>ENOMSG</code></td>
<td>Indicates that there is no message of the desired type.</td>
</tr>
<tr>
<td><code>ENOPROTOOPT</code></td>
<td>Indicates that a given protocol is not available.</td>
</tr>
<tr>
<td><code>ENOSPC</code></td>
<td>Indicates that there is no space available on the device.</td>
</tr>
<tr>
<td><code>ENOSR</code></td>
<td>Indicates that there are no stream resources available.</td>
</tr>
<tr>
<td><code>ENOSTR</code></td>
<td>Indicates that a given resource is not a stream.</td>
</tr>
<tr>
<td><code>ENOSYS</code></td>
<td>Indicates that a function has not been implemented.</td>
</tr>
<tr>
<td><code>ENOTCONN</code></td>
<td>Indicates that the socket is not connected.</td>
</tr>
<tr>
<td><code>ENOTDIR</code></td>
<td>Indicates that the path is not a directory.</td>
</tr>
<tr>
<td><code>ENOTEMPTY</code></td>
<td>Indicates that the directory is not empty.</td>
</tr>
<tr>
<td><code>ENOTSOCK</code></td>
<td>Indicates that the given item is not a socket.</td>
</tr>
<tr>
<td><code>ENOTSUP</code></td>
<td>Indicates that a given operation is not supported.</td>
</tr>
<tr>
<td><code>ENOTTY</code></td>
<td>Indicates an inappropriate I/O control operation.</td>
</tr>
<tr>
<td><code>ENXIO</code></td>
<td>Indicates no such device or address.</td>
</tr>
<tr>
<td><code>EOPNOTSUPP</code></td>
<td>Indicates that an operation is not supported on the socket. Although
<code>ENOTSUP</code> and <code>EOPNOTSUPP</code> have the same value
on Linux, according to POSIX.1 these error values should be distinct.)</td>
</tr>
<tr>
<td><code>EOVERFLOW</code></td>
<td>Indicates that a value is too large to be stored in a given data
type.</td>
</tr>
<tr>
<td><code>EPERM</code></td>
<td>Indicates that the operation is not permitted.</td>
</tr>
<tr>
<td><code>EPIPE</code></td>
<td>Indicates a broken pipe.</td>
</tr>
<tr>
<td><code>EPROTO</code></td>
<td>Indicates a protocol error.</td>
</tr>
<tr>
<td><code>EPROTONOSUPPORT</code></td>
<td>Indicates that a protocol is not supported.</td>
</tr>
<tr>
<td><code>EPROTOTYPE</code></td>
<td>Indicates the wrong type of protocol for a socket.</td>
</tr>
<tr>
<td><code>ERANGE</code></td>
<td>Indicates that the results are too large.</td>
</tr>
<tr>
<td><code>EROFS</code></td>
<td>Indicates that the file system is read only.</td>
</tr>
<tr>
<td><code>ESPIPE</code></td>
<td>Indicates an invalid seek operation.</td>
</tr>
<tr>
<td><code>ESRCH</code></td>
<td>Indicates that there is no such process.</td>
</tr>
<tr>
<td><code>ESTALE</code></td>
<td>Indicates that the file handle is stale.</td>
</tr>
<tr>
<td><code>ETIME</code></td>
<td>Indicates an expired timer.</td>
</tr>
<tr>
<td><code>ETIMEDOUT</code></td>
<td>Indicates that the connection timed out.</td>
</tr>
<tr>
<td><code>ETXTBSY</code></td>
<td>Indicates that a text file is busy.</td>
</tr>
<tr>
<td><code>EWOULDBLOCK</code></td>
<td>Indicates that the operation would block.</td>
</tr>
<tr>
<td><code>EXDEV</code></td>
<td>Indicates an improper link.</td>
</tr>
</tbody></table>
<h5>Windows-specific error constants<span><a class="mark" href="#all_os_windows-specific-error-constants" id="all_os_windows-specific-error-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_windows_specific_error_constants"></a></h5>
<p>The following error codes are specific to the Windows operating system.</p>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>WSAEINTR</code></td>
<td>Indicates an interrupted function call.</td>
</tr>
<tr>
<td><code>WSAEBADF</code></td>
<td>Indicates an invalid file handle.</td>
</tr>
<tr>
<td><code>WSAEACCES</code></td>
<td>Indicates insufficient permissions to complete the operation.</td>
</tr>
<tr>
<td><code>WSAEFAULT</code></td>
<td>Indicates an invalid pointer address.</td>
</tr>
<tr>
<td><code>WSAEINVAL</code></td>
<td>Indicates that an invalid argument was passed.</td>
</tr>
<tr>
<td><code>WSAEMFILE</code></td>
<td>Indicates that there are too many open files.</td>
</tr>
<tr>
<td><code>WSAEWOULDBLOCK</code></td>
<td>Indicates that a resource is temporarily unavailable.</td>
</tr>
<tr>
<td><code>WSAEINPROGRESS</code></td>
<td>Indicates that an operation is currently in progress.</td>
</tr>
<tr>
<td><code>WSAEALREADY</code></td>
<td>Indicates that an operation is already in progress.</td>
</tr>
<tr>
<td><code>WSAENOTSOCK</code></td>
<td>Indicates that the resource is not a socket.</td>
</tr>
<tr>
<td><code>WSAEDESTADDRREQ</code></td>
<td>Indicates that a destination address is required.</td>
</tr>
<tr>
<td><code>WSAEMSGSIZE</code></td>
<td>Indicates that the message size is too long.</td>
</tr>
<tr>
<td><code>WSAEPROTOTYPE</code></td>
<td>Indicates the wrong protocol type for the socket.</td>
</tr>
<tr>
<td><code>WSAENOPROTOOPT</code></td>
<td>Indicates a bad protocol option.</td>
</tr>
<tr>
<td><code>WSAEPROTONOSUPPORT</code></td>
<td>Indicates that the protocol is not supported.</td>
</tr>
<tr>
<td><code>WSAESOCKTNOSUPPORT</code></td>
<td>Indicates that the socket type is not supported.</td>
</tr>
<tr>
<td><code>WSAEOPNOTSUPP</code></td>
<td>Indicates that the operation is not supported.</td>
</tr>
<tr>
<td><code>WSAEPFNOSUPPORT</code></td>
<td>Indicates that the protocol family is not supported.</td>
</tr>
<tr>
<td><code>WSAEAFNOSUPPORT</code></td>
<td>Indicates that the address family is not supported.</td>
</tr>
<tr>
<td><code>WSAEADDRINUSE</code></td>
<td>Indicates that the network address is already in use.</td>
</tr>
<tr>
<td><code>WSAEADDRNOTAVAIL</code></td>
<td>Indicates that the network address is not available.</td>
</tr>
<tr>
<td><code>WSAENETDOWN</code></td>
<td>Indicates that the network is down.</td>
</tr>
<tr>
<td><code>WSAENETUNREACH</code></td>
<td>Indicates that the network is unreachable.</td>
</tr>
<tr>
<td><code>WSAENETRESET</code></td>
<td>Indicates that the network connection has been reset.</td>
</tr>
<tr>
<td><code>WSAECONNABORTED</code></td>
<td>Indicates that the connection has been aborted.</td>
</tr>
<tr>
<td><code>WSAECONNRESET</code></td>
<td>Indicates that the connection has been reset by the peer.</td>
</tr>
<tr>
<td><code>WSAENOBUFS</code></td>
<td>Indicates that there is no buffer space available.</td>
</tr>
<tr>
<td><code>WSAEISCONN</code></td>
<td>Indicates that the socket is already connected.</td>
</tr>
<tr>
<td><code>WSAENOTCONN</code></td>
<td>Indicates that the socket is not connected.</td>
</tr>
<tr>
<td><code>WSAESHUTDOWN</code></td>
<td>Indicates that data cannot be sent after the socket has been
shutdown.</td>
</tr>
<tr>
<td><code>WSAETOOMANYREFS</code></td>
<td>Indicates that there are too many references.</td>
</tr>
<tr>
<td><code>WSAETIMEDOUT</code></td>
<td>Indicates that the connection has timed out.</td>
</tr>
<tr>
<td><code>WSAECONNREFUSED</code></td>
<td>Indicates that the connection has been refused.</td>
</tr>
<tr>
<td><code>WSAELOOP</code></td>
<td>Indicates that a name cannot be translated.</td>
</tr>
<tr>
<td><code>WSAENAMETOOLONG</code></td>
<td>Indicates that a name was too long.</td>
</tr>
<tr>
<td><code>WSAEHOSTDOWN</code></td>
<td>Indicates that a network host is down.</td>
</tr>
<tr>
<td><code>WSAEHOSTUNREACH</code></td>
<td>Indicates that there is no route to a network host.</td>
</tr>
<tr>
<td><code>WSAENOTEMPTY</code></td>
<td>Indicates that the directory is not empty.</td>
</tr>
<tr>
<td><code>WSAEPROCLIM</code></td>
<td>Indicates that there are too many processes.</td>
</tr>
<tr>
<td><code>WSAEUSERS</code></td>
<td>Indicates that the user quota has been exceeded.</td>
</tr>
<tr>
<td><code>WSAEDQUOT</code></td>
<td>Indicates that the disk quota has been exceeded.</td>
</tr>
<tr>
<td><code>WSAESTALE</code></td>
<td>Indicates a stale file handle reference.</td>
</tr>
<tr>
<td><code>WSAEREMOTE</code></td>
<td>Indicates that the item is remote.</td>
</tr>
<tr>
<td><code>WSASYSNOTREADY</code></td>
<td>Indicates that the network subsystem is not ready.</td>
</tr>
<tr>
<td><code>WSAVERNOTSUPPORTED</code></td>
<td>Indicates that the <code>winsock.dll</code> version is out of
range.</td>
</tr>
<tr>
<td><code>WSANOTINITIALISED</code></td>
<td>Indicates that successful WSAStartup has not yet been performed.</td>
</tr>
<tr>
<td><code>WSAEDISCON</code></td>
<td>Indicates that a graceful shutdown is in progress.</td>
</tr>
<tr>
<td><code>WSAENOMORE</code></td>
<td>Indicates that there are no more results.</td>
</tr>
<tr>
<td><code>WSAECANCELLED</code></td>
<td>Indicates that an operation has been canceled.</td>
</tr>
<tr>
<td><code>WSAEINVALIDPROCTABLE</code></td>
<td>Indicates that the procedure call table is invalid.</td>
</tr>
<tr>
<td><code>WSAEINVALIDPROVIDER</code></td>
<td>Indicates an invalid service provider.</td>
</tr>
<tr>
<td><code>WSAEPROVIDERFAILEDINIT</code></td>
<td>Indicates that the service provider failed to initialized.</td>
</tr>
<tr>
<td><code>WSASYSCALLFAILURE</code></td>
<td>Indicates a system call failure.</td>
</tr>
<tr>
<td><code>WSASERVICE_NOT_FOUND</code></td>
<td>Indicates that a service was not found.</td>
</tr>
<tr>
<td><code>WSATYPE_NOT_FOUND</code></td>
<td>Indicates that a class type was not found.</td>
</tr>
<tr>
<td><code>WSA_E_NO_MORE</code></td>
<td>Indicates that there are no more results.</td>
</tr>
<tr>
<td><code>WSA_E_CANCELLED</code></td>
<td>Indicates that the call was canceled.</td>
</tr>
<tr>
<td><code>WSAEREFUSED</code></td>
<td>Indicates that a database query was refused.</td>
</tr>
</tbody></table>
<h4>dlopen constants<span><a class="mark" href="#all_os_dlopen-constants" id="all_os_dlopen-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_dlopen_constants"></a></h4>
<p>If available on the operating system, the following constants
are exported in <code>os.constants.dlopen</code>. See <a href="http://man7.org/linux/man-pages/man3/dlopen.3.html"><code>dlopen(3)</code></a> for detailed
information.</p>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>RTLD_LAZY</code></td>
<td>Perform lazy binding. Node.js sets this flag by default.</td>
</tr>
<tr>
<td><code>RTLD_NOW</code></td>
<td>Resolve all undefined symbols in the library before dlopen(3)
returns.</td>
</tr>
<tr>
<td><code>RTLD_GLOBAL</code></td>
<td>Symbols defined by the library will be made available for symbol
resolution of subsequently loaded libraries.</td>
</tr>
<tr>
<td><code>RTLD_LOCAL</code></td>
<td>The converse of <code>RTLD_GLOBAL</code>. This is the default behavior
if neither flag is specified.</td>
</tr>
<tr>
<td><code>RTLD_DEEPBIND</code></td>
<td>Make a self-contained library use its own symbols in preference to
symbols from previously loaded libraries.</td>
</tr>
</tbody></table>
<h4>Priority constants<span><a class="mark" href="#all_os_priority-constants" id="all_os_priority-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_priority_constants"></a></h4>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<p>The following process scheduling constants are exported by
<code>os.constants.priority</code>.</p>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>PRIORITY_LOW</code></td>
<td>The lowest process scheduling priority. This corresponds to
<code>IDLE_PRIORITY_CLASS</code> on Windows, and a nice value of
<code>19</code> on all other platforms.</td>
</tr>
<tr>
<td><code>PRIORITY_BELOW_NORMAL</code></td>
<td>The process scheduling priority above <code>PRIORITY_LOW</code> and
below <code>PRIORITY_NORMAL</code>. This corresponds to
<code>BELOW_NORMAL_PRIORITY_CLASS</code> on Windows, and a nice value of
<code>10</code> on all other platforms.</td>
</tr>
<tr>
<td><code>PRIORITY_NORMAL</code></td>
<td>The default process scheduling priority. This corresponds to
<code>NORMAL_PRIORITY_CLASS</code> on Windows, and a nice value of
<code>0</code> on all other platforms.</td>
</tr>
<tr>
<td><code>PRIORITY_ABOVE_NORMAL</code></td>
<td>The process scheduling priority above <code>PRIORITY_NORMAL</code> and
below <code>PRIORITY_HIGH</code>. This corresponds to
<code>ABOVE_NORMAL_PRIORITY_CLASS</code> on Windows, and a nice value of
<code>-7</code> on all other platforms.</td>
</tr>
<tr>
<td><code>PRIORITY_HIGH</code></td>
<td>The process scheduling priority above <code>PRIORITY_ABOVE_NORMAL</code>
and below <code>PRIORITY_HIGHEST</code>. This corresponds to
<code>HIGH_PRIORITY_CLASS</code> on Windows, and a nice value of
<code>-14</code> on all other platforms.</td>
</tr>
<tr>
<td><code>PRIORITY_HIGHEST</code></td>
<td>The highest process scheduling priority. This corresponds to
<code>REALTIME_PRIORITY_CLASS</code> on Windows, and a nice value of
<code>-20</code> on all other platforms.</td>
</tr>
</tbody></table>
<h4>libuv constants<span><a class="mark" href="#all_os_libuv-constants" id="all_os_libuv-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_libuv_constants"></a></h4>
<table>
<tbody><tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>UV_UDP_REUSEADDR</code></td>
<td></td>
</tr>
</tbody></table></section>
</section>
<section><h2>Path<span><a class="mark" href="#all_path_path" id="all_path_path">#</a></span><a aria-hidden="true" class="legacy" id="path_path"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/path.js">lib/path.js</a></p>
<p>The <code>node:path</code> module provides utilities for working with file and directory
paths. It can be accessed using:</p>
<pre class="with-34-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> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;</code><button class="copy-button">copy</button></pre>
<section><h3>Windows vs. POSIX<span><a class="mark" href="#all_path_windows-vs-posix" id="all_path_windows-vs-posix">#</a></span><a aria-hidden="true" class="legacy" id="path_windows_vs_posix"></a></h3>
<p>The default operation of the <code>node:path</code> module varies based on the operating
system on which a Node.js application is running. Specifically, when running on
a Windows operating system, the <code>node:path</code> module will assume that
Windows-style paths are being used.</p>
<p>So using <code>path.basename()</code> might yield different results on POSIX and Windows:</p>
<p>On POSIX:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'C:\\temp\\myfile.html'</span>);
<span class="hljs-comment">// Returns: 'C:\\temp\\myfile.html'</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'C:\\temp\\myfile.html'</span>);
<span class="hljs-comment">// Returns: 'myfile.html'</span></code> <button class="copy-button">copy</button></pre>
<p>To achieve consistent results when working with Windows file paths on any
operating system, use <a href="#all_path_pathwin32"><code>path.win32</code></a>:</p>
<p>On POSIX and Windows:</p>
<pre><code class="language-js">path.<span class="hljs-property">win32</span>.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'C:\\temp\\myfile.html'</span>);
<span class="hljs-comment">// Returns: 'myfile.html'</span></code> <button class="copy-button">copy</button></pre>
<p>To achieve consistent results when working with POSIX file paths on any
operating system, use <a href="#all_path_pathposix"><code>path.posix</code></a>:</p>
<p>On POSIX and Windows:</p>
<pre><code class="language-js">path.<span class="hljs-property">posix</span>.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'/tmp/myfile.html'</span>);
<span class="hljs-comment">// Returns: 'myfile.html'</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows Node.js follows the concept of per-drive working directory.
This behavior can be observed when using a drive path without a backslash. For
example, <code>path.resolve('C:\\')</code> can potentially return a different result than
<code>path.resolve('C:')</code>. For more information, see
<a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths">this MSDN page</a>.</p>
</section><section><h3><code>path.basename(path[, suffix])</code><span><a class="mark" href="#all_path_pathbasenamepath-suffix" id="all_path_pathbasenamepath-suffix">#</a></span><a aria-hidden="true" class="legacy" id="path_path_basename_path_suffix"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>Passing a non-string as the <code>path</code> argument will throw now.</p></td></tr>
<tr><td>v0.1.25</td>
<td><p><span>Added in: v0.1.25</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>suffix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> An optional suffix to remove</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>path.basename()</code> method returns the last portion of a <code>path</code>, similar to
the Unix <code>basename</code> command. Trailing <a href="#all_path_pathsep">directory separators</a> are
ignored.</p>
<pre><code class="language-js">path.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'/foo/bar/baz/asdf/quux.html'</span>);
<span class="hljs-comment">// Returns: 'quux.html'</span>
path.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'/foo/bar/baz/asdf/quux.html'</span>, <span class="hljs-string">'.html'</span>);
<span class="hljs-comment">// Returns: 'quux'</span></code> <button class="copy-button">copy</button></pre>
<p>Although Windows usually treats file names, including file extensions, in a
case-insensitive manner, this function does not. For example, <code>C:\\foo.html</code> and
<code>C:\\foo.HTML</code> refer to the same file, but <code>basename</code> treats the extension as a
case-sensitive string:</p>
<pre><code class="language-js">path.<span class="hljs-property">win32</span>.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'C:\\foo.html'</span>, <span class="hljs-string">'.html'</span>);
<span class="hljs-comment">// Returns: 'foo'</span>
path.<span class="hljs-property">win32</span>.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'C:\\foo.HTML'</span>, <span class="hljs-string">'.html'</span>);
<span class="hljs-comment">// Returns: 'foo.HTML'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string or if <code>suffix</code> is given
and is not a string.</p>
</section><section><h3><code>path.delimiter</code><span><a class="mark" href="#all_path_pathdelimiter" id="all_path_pathdelimiter">#</a></span><a aria-hidden="true" class="legacy" id="path_path_delimiter"></a></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Provides the platform-specific path delimiter:</p>
<ul>
<li><code>;</code> for Windows</li>
<li><code>:</code> for POSIX</li>
</ul>
<p>For example, on POSIX:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-property">env</span>.<span class="hljs-property">PATH</span>);
<span class="hljs-comment">// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'</span>
process.<span class="hljs-property">env</span>.<span class="hljs-property">PATH</span>.<span class="hljs-title function_">split</span>(path.<span class="hljs-property">delimiter</span>);
<span class="hljs-comment">// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-property">env</span>.<span class="hljs-property">PATH</span>);
<span class="hljs-comment">// Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'</span>
process.<span class="hljs-property">env</span>.<span class="hljs-property">PATH</span>.<span class="hljs-title function_">split</span>(path.<span class="hljs-property">delimiter</span>);
<span class="hljs-comment">// Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>path.dirname(path)</code><span><a class="mark" href="#all_path_pathdirnamepath" id="all_path_pathdirnamepath">#</a></span><a aria-hidden="true" class="legacy" id="path_path_dirname_path"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>Passing a non-string as the <code>path</code> argument will throw now.</p></td></tr>
<tr><td>v0.1.16</td>
<td><p><span>Added in: v0.1.16</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>path.dirname()</code> method returns the directory name of a <code>path</code>, similar to
the Unix <code>dirname</code> command. Trailing directory separators are ignored, see
<a href="#all_path_pathsep"><code>path.sep</code></a>.</p>
<pre><code class="language-js">path.<span class="hljs-title function_">dirname</span>(<span class="hljs-string">'/foo/bar/baz/asdf/quux'</span>);
<span class="hljs-comment">// Returns: '/foo/bar/baz/asdf'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
</section><section><h3><code>path.extname(path)</code><span><a class="mark" href="#all_path_pathextnamepath" id="all_path_pathextnamepath">#</a></span><a aria-hidden="true" class="legacy" id="path_path_extname_path"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>Passing a non-string as the <code>path</code> argument will throw now.</p></td></tr>
<tr><td>v0.1.25</td>
<td><p><span>Added in: v0.1.25</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>path.extname()</code> method returns the extension of the <code>path</code>, from the last
occurrence of the <code>.</code> (period) character to end of string in the last portion of
the <code>path</code>. If there is no <code>.</code> in the last portion of the <code>path</code>, or if
there are no <code>.</code> characters other than the first character of
the basename of <code>path</code> (see <code>path.basename()</code>) , an empty string is returned.</p>
<pre><code class="language-js">path.<span class="hljs-title function_">extname</span>(<span class="hljs-string">'index.html'</span>);
<span class="hljs-comment">// Returns: '.html'</span>
path.<span class="hljs-title function_">extname</span>(<span class="hljs-string">'index.coffee.md'</span>);
<span class="hljs-comment">// Returns: '.md'</span>
path.<span class="hljs-title function_">extname</span>(<span class="hljs-string">'index.'</span>);
<span class="hljs-comment">// Returns: '.'</span>
path.<span class="hljs-title function_">extname</span>(<span class="hljs-string">'index'</span>);
<span class="hljs-comment">// Returns: ''</span>
path.<span class="hljs-title function_">extname</span>(<span class="hljs-string">'.index'</span>);
<span class="hljs-comment">// Returns: ''</span>
path.<span class="hljs-title function_">extname</span>(<span class="hljs-string">'.index.md'</span>);
<span class="hljs-comment">// Returns: '.md'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
</section><section><h3><code>path.format(pathObject)</code><span><a class="mark" href="#all_path_pathformatpathobject" id="all_path_pathformatpathobject">#</a></span><a aria-hidden="true" class="legacy" id="path_path_format_pathobject"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>The dot will be added if it is not specified in <code>ext</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>pathObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Any JavaScript object having the following properties:
<ul>
<li><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>root</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>base</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>ext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>path.format()</code> method returns a path string from an object. This is the
opposite of <a href="#all_path_pathparsepath"><code>path.parse()</code></a>.</p>
<p>When providing properties to the <code>pathObject</code> remember that there are
combinations where one property has priority over another:</p>
<ul>
<li><code>pathObject.root</code> is ignored if <code>pathObject.dir</code> is provided</li>
<li><code>pathObject.ext</code> and <code>pathObject.name</code> are ignored if <code>pathObject.base</code> exists</li>
</ul>
<p>For example, on POSIX:</p>
<pre><code class="language-js"><span class="hljs-comment">// If `dir`, `root` and `base` are provided,</span>
<span class="hljs-comment">// `${dir}${path.sep}${base}`</span>
<span class="hljs-comment">// will be returned. `root` is ignored.</span>
path.<span class="hljs-title function_">format</span>({
<span class="hljs-attr">root</span>: <span class="hljs-string">'/ignored'</span>,
<span class="hljs-attr">dir</span>: <span class="hljs-string">'/home/user/dir'</span>,
<span class="hljs-attr">base</span>: <span class="hljs-string">'file.txt'</span>,
});
<span class="hljs-comment">// Returns: '/home/user/dir/file.txt'</span>
<span class="hljs-comment">// `root` will be used if `dir` is not specified.</span>
<span class="hljs-comment">// If only `root` is provided or `dir` is equal to `root` then the</span>
<span class="hljs-comment">// platform separator will not be included. `ext` will be ignored.</span>
path.<span class="hljs-title function_">format</span>({
<span class="hljs-attr">root</span>: <span class="hljs-string">'/'</span>,
<span class="hljs-attr">base</span>: <span class="hljs-string">'file.txt'</span>,
<span class="hljs-attr">ext</span>: <span class="hljs-string">'ignored'</span>,
});
<span class="hljs-comment">// Returns: '/file.txt'</span>
<span class="hljs-comment">// `name` + `ext` will be used if `base` is not specified.</span>
path.<span class="hljs-title function_">format</span>({
<span class="hljs-attr">root</span>: <span class="hljs-string">'/'</span>,
<span class="hljs-attr">name</span>: <span class="hljs-string">'file'</span>,
<span class="hljs-attr">ext</span>: <span class="hljs-string">'.txt'</span>,
});
<span class="hljs-comment">// Returns: '/file.txt'</span>
<span class="hljs-comment">// The dot will be added if it is not specified in `ext`.</span>
path.<span class="hljs-title function_">format</span>({
<span class="hljs-attr">root</span>: <span class="hljs-string">'/'</span>,
<span class="hljs-attr">name</span>: <span class="hljs-string">'file'</span>,
<span class="hljs-attr">ext</span>: <span class="hljs-string">'txt'</span>,
});
<span class="hljs-comment">// Returns: '/file.txt'</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">format</span>({
<span class="hljs-attr">dir</span>: <span class="hljs-string">'C:\\path\\dir'</span>,
<span class="hljs-attr">base</span>: <span class="hljs-string">'file.txt'</span>,
});
<span class="hljs-comment">// Returns: 'C:\\path\\dir\\file.txt'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>path.matchesGlob(path, pattern)</code><span><a class="mark" href="#all_path_pathmatchesglobpath-pattern" id="all_path_pathmatchesglobpath-pattern">#</a></span><a aria-hidden="true" class="legacy" id="path_path_matchesglob_path_pattern"></a></h3>
<div class="api_metadata">
<span>Added in: v20.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The path to glob-match against.</li>
<li><code>pattern</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The glob to check the path against.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not the <code>path</code> matched the <code>pattern</code>.</li>
</ul>
<p>The <code>path.matchesGlob()</code> method determines if <code>path</code> matches the <code>pattern</code>.</p>
<p>For example:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">matchesGlob</span>(<span class="hljs-string">'/foo/bar'</span>, <span class="hljs-string">'/foo/*'</span>); <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">matchesGlob</span>(<span class="hljs-string">'/foo/bar*'</span>, <span class="hljs-string">'foo/bird'</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> or <code>pattern</code> are not strings.</p>
</section><section><h3><code>path.isAbsolute(path)</code><span><a class="mark" href="#all_path_pathisabsolutepath" id="all_path_pathisabsolutepath">#</a></span><a aria-hidden="true" class="legacy" id="path_path_isabsolute_path"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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>The <code>path.isAbsolute()</code> method determines if <code>path</code> is an absolute path.</p>
<p>If the given <code>path</code> is a zero-length string, <code>false</code> will be returned.</p>
<p>For example, on POSIX:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'/foo/bar'</span>); <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'/baz/..'</span>); <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'qux/'</span>); <span class="hljs-comment">// false</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'.'</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'//server'</span>); <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'\\\\server'</span>); <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'C:/foo/..'</span>); <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'C:\\foo\\..'</span>); <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'bar\\baz'</span>); <span class="hljs-comment">// false</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'bar/baz'</span>); <span class="hljs-comment">// false</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'.'</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
</section><section><h3><code>path.join([...paths])</code><span><a class="mark" href="#all_path_pathjoinpaths" id="all_path_pathjoinpaths">#</a></span><a aria-hidden="true" class="legacy" id="path_path_join_paths"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><code>...paths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A sequence of path segments</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>path.join()</code> method joins all given <code>path</code> segments together using the
platform-specific separator as a delimiter, then normalizes the resulting path.</p>
<p>Zero-length <code>path</code> segments are ignored. If the joined path string is a
zero-length string then <code>'.'</code> will be returned, representing the current
working directory.</p>
<pre><code class="language-js">path.<span class="hljs-title function_">join</span>(<span class="hljs-string">'/foo'</span>, <span class="hljs-string">'bar'</span>, <span class="hljs-string">'baz/asdf'</span>, <span class="hljs-string">'quux'</span>, <span class="hljs-string">'..'</span>);
<span class="hljs-comment">// Returns: '/foo/bar/baz/asdf'</span>
path.<span class="hljs-title function_">join</span>(<span class="hljs-string">'foo'</span>, {}, <span class="hljs-string">'bar'</span>);
<span class="hljs-comment">// Throws 'TypeError: Path must be a string. Received {}'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if any of the path segments is not a string.</p>
</section><section><h3><code>path.normalize(path)</code><span><a class="mark" href="#all_path_pathnormalizepath" id="all_path_pathnormalizepath">#</a></span><a aria-hidden="true" class="legacy" id="path_path_normalize_path"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.23</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>path.normalize()</code> method normalizes the given <code>path</code>, resolving <code>'..'</code> and
<code>'.'</code> segments.</p>
<p>When multiple, sequential path segment separation characters are found (e.g.
<code>/</code> on POSIX and either <code>\</code> or <code>/</code> on Windows), they are replaced by a single
instance of the platform-specific path segment separator (<code>/</code> on POSIX and
<code>\</code> on Windows). Trailing separators are preserved.</p>
<p>If the <code>path</code> is a zero-length string, <code>'.'</code> is returned, representing the
current working directory.</p>
<p>On POSIX, the types of normalization applied by this function do not strictly
adhere to the POSIX specification. For example, this function will replace two
leading forward slashes with a single slash as if it was a regular absolute
path, whereas a few POSIX systems assign special meaning to paths beginning with
exactly two forward slashes. Similarly, other substitutions performed by this
function, such as removing <code>..</code> segments, may change how the underlying system
resolves the path.</p>
<p>For example, on POSIX:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">normalize</span>(<span class="hljs-string">'/foo/bar//baz/asdf/quux/..'</span>);
<span class="hljs-comment">// Returns: '/foo/bar/baz/asdf'</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">normalize</span>(<span class="hljs-string">'C:\\temp\\\\foo\\bar\\..\\'</span>);
<span class="hljs-comment">// Returns: 'C:\\temp\\foo\\'</span></code> <button class="copy-button">copy</button></pre>
<p>Since Windows recognizes multiple path separators, both separators will be
replaced by instances of the Windows preferred separator (<code>\</code>):</p>
<pre><code class="language-js">path.<span class="hljs-property">win32</span>.<span class="hljs-title function_">normalize</span>(<span class="hljs-string">'C:////temp\\\\/\\/\\/foo/bar'</span>);
<span class="hljs-comment">// Returns: 'C:\\temp\\foo\\bar'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
</section><section><h3><code>path.parse(path)</code><span><a class="mark" href="#all_path_pathparsepath" id="all_path_pathparsepath">#</a></span><a aria-hidden="true" class="legacy" id="path_path_parse_path"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>path.parse()</code> method returns an object whose properties represent
significant elements of the <code>path</code>. Trailing directory separators are ignored,
see <a href="#all_path_pathsep"><code>path.sep</code></a>.</p>
<p>The returned object will have the following properties:</p>
<ul>
<li><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>root</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>base</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>ext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>For example, on POSIX:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">parse</span>(<span class="hljs-string">'/home/user/dir/file.txt'</span>);
<span class="hljs-comment">// Returns:</span>
<span class="hljs-comment">// { root: '/',</span>
<span class="hljs-comment">// dir: '/home/user/dir',</span>
<span class="hljs-comment">// base: 'file.txt',</span>
<span class="hljs-comment">// ext: '.txt',</span>
<span class="hljs-comment">// name: 'file' }</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-text">┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
│ root │ │ name │ ext │
" / home/user/dir / file .txt "
└──────┴──────────────┴──────┴─────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)</code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">parse</span>(<span class="hljs-string">'C:\\path\\dir\\file.txt'</span>);
<span class="hljs-comment">// Returns:</span>
<span class="hljs-comment">// { root: 'C:\\',</span>
<span class="hljs-comment">// dir: 'C:\\path\\dir',</span>
<span class="hljs-comment">// base: 'file.txt',</span>
<span class="hljs-comment">// ext: '.txt',</span>
<span class="hljs-comment">// name: 'file' }</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-text">┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
│ root │ │ name │ ext │
" C:\ path\dir \ file .txt "
└──────┴──────────────┴──────┴─────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)</code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
</section><section><h3><code>path.posix</code><span><a class="mark" href="#all_path_pathposix" id="all_path_pathposix">#</a></span><a aria-hidden="true" class="legacy" id="path_path_posix"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.3.0</td>
<td><p>Exposed as <code>require('path/posix')</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><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>path.posix</code> property provides access to POSIX specific implementations
of the <code>path</code> methods.</p>
<p>The API is accessible via <code>require('node:path').posix</code> or <code>require('node:path/posix')</code>.</p>
</section><section><h3><code>path.relative(from, to)</code><span><a class="mark" href="#all_path_pathrelativefrom-to" id="all_path_pathrelativefrom-to">#</a></span><a aria-hidden="true" class="legacy" id="path_path_relative_from_to"></a></h3>
<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>On Windows, the leading slashes for UNC paths are now included in the return value.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>from</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>to</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>path.relative()</code> method returns the relative path from <code>from</code> to <code>to</code> based
on the current working directory. If <code>from</code> and <code>to</code> each resolve to the same
path (after calling <code>path.resolve()</code> on each), a zero-length string is returned.</p>
<p>If a zero-length string is passed as <code>from</code> or <code>to</code>, the current working
directory will be used instead of the zero-length strings.</p>
<p>For example, on POSIX:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">relative</span>(<span class="hljs-string">'/data/orandea/test/aaa'</span>, <span class="hljs-string">'/data/orandea/impl/bbb'</span>);
<span class="hljs-comment">// Returns: '../../impl/bbb'</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">relative</span>(<span class="hljs-string">'C:\\orandea\\test\\aaa'</span>, <span class="hljs-string">'C:\\orandea\\impl\\bbb'</span>);
<span class="hljs-comment">// Returns: '..\\..\\impl\\bbb'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if either <code>from</code> or <code>to</code> is not a string.</p>
</section><section><h3><code>path.resolve([...paths])</code><span><a class="mark" href="#all_path_pathresolvepaths" id="all_path_pathresolvepaths">#</a></span><a aria-hidden="true" class="legacy" id="path_path_resolve_paths"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<ul>
<li><code>...paths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A sequence of paths or path segments</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>path.resolve()</code> method resolves a sequence of paths or path segments into
an absolute path.</p>
<p>The given sequence of paths is processed from right to left, with each
subsequent <code>path</code> prepended until an absolute path is constructed.
For instance, given the sequence of path segments: <code>/foo</code>, <code>/bar</code>, <code>baz</code>,
calling <code>path.resolve('/foo', '/bar', 'baz')</code> would return <code>/bar/baz</code>
because <code>'baz'</code> is not an absolute path but <code>'/bar' + '/' + 'baz'</code> is.</p>
<p>If, after processing all given <code>path</code> segments, an absolute path has not yet
been generated, the current working directory is used.</p>
<p>The resulting path is normalized and trailing slashes are removed unless the
path is resolved to the root directory.</p>
<p>Zero-length <code>path</code> segments are ignored.</p>
<p>If no <code>path</code> segments are passed, <code>path.resolve()</code> will return the absolute path
of the current working directory.</p>
<pre><code class="language-js">path.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'/foo/bar'</span>, <span class="hljs-string">'./baz'</span>);
<span class="hljs-comment">// Returns: '/foo/bar/baz'</span>
path.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'/foo/bar'</span>, <span class="hljs-string">'/tmp/file/'</span>);
<span class="hljs-comment">// Returns: '/tmp/file'</span>
path.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'wwwroot'</span>, <span class="hljs-string">'static_files/png/'</span>, <span class="hljs-string">'../gif/image.gif'</span>);
<span class="hljs-comment">// If the current working directory is /home/myself/node,</span>
<span class="hljs-comment">// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if any of the arguments is not a string.</p>
</section><section><h3><code>path.sep</code><span><a class="mark" href="#all_path_pathsep" id="all_path_pathsep">#</a></span><a aria-hidden="true" class="legacy" id="path_path_sep"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.9</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Provides the platform-specific path segment separator:</p>
<ul>
<li><code>\</code> on Windows</li>
<li><code>/</code> on POSIX</li>
</ul>
<p>For example, on POSIX:</p>
<pre><code class="language-js"><span class="hljs-string">'foo/bar/baz'</span>.<span class="hljs-title function_">split</span>(path.<span class="hljs-property">sep</span>);
<span class="hljs-comment">// Returns: ['foo', 'bar', 'baz']</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js"><span class="hljs-string">'foo\\bar\\baz'</span>.<span class="hljs-title function_">split</span>(path.<span class="hljs-property">sep</span>);
<span class="hljs-comment">// Returns: ['foo', 'bar', 'baz']</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows, both the forward slash (<code>/</code>) and backward slash (<code>\</code>) are accepted
as path segment separators; however, the <code>path</code> methods only add backward
slashes (<code>\</code>).</p>
</section><section><h3><code>path.toNamespacedPath(path)</code><span><a class="mark" href="#all_path_pathtonamespacedpathpath" id="all_path_pathtonamespacedpathpath">#</a></span><a aria-hidden="true" class="legacy" id="path_path_tonamespacedpath_path"></a></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>On Windows systems only, returns an equivalent <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#namespaces">namespace-prefixed path</a> for
the given <code>path</code>. If <code>path</code> is not a string, <code>path</code> will be returned without
modifications.</p>
<p>This method is meaningful only on Windows systems. On POSIX systems, the
method is non-operational and always returns <code>path</code> without modifications.</p>
</section><section><h3><code>path.win32</code><span><a class="mark" href="#all_path_pathwin32" id="all_path_pathwin32">#</a></span><a aria-hidden="true" class="legacy" id="path_path_win32"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.3.0</td>
<td><p>Exposed as <code>require('path/win32')</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><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>path.win32</code> property provides access to Windows-specific implementations
of the <code>path</code> methods.</p>
<p>The API is accessible via <code>require('node:path').win32</code> or <code>require('node:path/win32')</code>.</p></section>
</section>
<section><h2>Performance measurement APIs<span><a class="mark" href="#all_perf_hooks_performance-measurement-apis" id="all_perf_hooks_performance-measurement-apis">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_measurement_apis"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/perf_hooks.js">lib/perf_hooks.js</a></p>
<p>This module provides an implementation of a subset of the W3C
<a href="https://w3c.github.io/perf-timing-primer/">Web Performance APIs</a> as well as additional APIs for
Node.js-specific performance measurements.</p>
<p>Node.js supports the following <a href="https://w3c.github.io/perf-timing-primer/">Web Performance APIs</a>:</p>
<ul>
<li><a href="https://www.w3.org/TR/hr-time-2">High Resolution Time</a></li>
<li><a href="https://w3c.github.io/performance-timeline/">Performance Timeline</a></li>
<li><a href="https://www.w3.org/TR/user-timing/">User Timing</a></li>
<li><a href="https://www.w3.org/TR/resource-timing-2/">Resource Timing</a></li>
</ul>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">PerformanceObserver</span>, performance } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(items.<span class="hljs-title function_">getEntries</span>()[<span class="hljs-number">0</span>].<span class="hljs-property">duration</span>);
performance.<span class="hljs-title function_">clearMarks</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">type</span>: <span class="hljs-string">'measure'</span> });
performance.<span class="hljs-title function_">measure</span>(<span class="hljs-string">'Start to Now'</span>);
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'A'</span>);
<span class="hljs-title function_">doSomeLongRunningProcess</span>(<span class="hljs-function">() =></span> {
performance.<span class="hljs-title function_">measure</span>(<span class="hljs-string">'A to Now'</span>, <span class="hljs-string">'A'</span>);
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'B'</span>);
performance.<span class="hljs-title function_">measure</span>(<span class="hljs-string">'A to B'</span>, <span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>);
});</code> <button class="copy-button">copy</button></pre>
<section><h3><code>perf_hooks.performance</code><span><a class="mark" href="#all_perf_hooks_perf_hooksperformance" id="all_perf_hooks_perf_hooksperformance">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_perf_hooks_performance"></a></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>An object that can be used to collect performance metrics from the current
Node.js instance. It is similar to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/performance"><code>window.performance</code></a> in browsers.</p>
<h4><code>performance.clearMarks([name])</code><span><a class="mark" href="#all_perf_hooks_performanceclearmarksname" id="all_perf_hooks_performanceclearmarksname">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_clearmarks_name"></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.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>If <code>name</code> is not provided, removes all <code>PerformanceMark</code> objects from the
Performance Timeline. If <code>name</code> is provided, removes only the named mark.</p>
<h4><code>performance.clearMeasures([name])</code><span><a class="mark" href="#all_perf_hooks_performanceclearmeasuresname" id="all_perf_hooks_performanceclearmeasuresname">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_clearmeasures_name"></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.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>If <code>name</code> is not provided, removes all <code>PerformanceMeasure</code> objects from the
Performance Timeline. If <code>name</code> is provided, removes only the named measure.</p>
<h4><code>performance.clearResourceTimings([name])</code><span><a class="mark" href="#all_perf_hooks_performanceclearresourcetimingsname" id="all_perf_hooks_performanceclearresourcetimingsname">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_clearresourcetimings_name"></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.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>If <code>name</code> is not provided, removes all <code>PerformanceResourceTiming</code> objects from
the Resource Timeline. If <code>name</code> is provided, removes only the named resource.</p>
<h4><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code><span><a class="mark" href="#all_perf_hooks_performanceeventlooputilizationutilization1-utilization2" id="all_perf_hooks_performanceeventlooputilizationutilization1-utilization2">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_eventlooputilization_utilization1_utilization2"></a></h4>
<div class="api_metadata">
<span>Added in: v14.10.0, v12.19.0</span>
</div>
<ul>
<li><code>utilization1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The result of a previous call to
<code>eventLoopUtilization()</code>.</li>
<li><code>utilization2</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The result of a previous call to
<code>eventLoopUtilization()</code> prior to <code>utilization1</code>.</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>idle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>active</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>utilization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</li>
</ul>
<p>The <code>eventLoopUtilization()</code> method returns an object that contains the
cumulative duration of time the event loop has been both idle and active as a
high resolution milliseconds timer. The <code>utilization</code> value is the calculated
Event Loop Utilization (ELU).</p>
<p>If bootstrapping has not yet finished on the main thread the properties have
the value of <code>0</code>. The ELU is immediately available on <a href="#all_worker_threads_worker-threads">Worker threads</a> since
bootstrap happens within the event loop.</p>
<p>Both <code>utilization1</code> and <code>utilization2</code> are optional parameters.</p>
<p>If <code>utilization1</code> is passed, then the delta between the current call's <code>active</code>
and <code>idle</code> times, as well as the corresponding <code>utilization</code> value are
calculated and returned (similar to <a href="#all_process_processhrtimetime"><code>process.hrtime()</code></a>).</p>
<p>If <code>utilization1</code> and <code>utilization2</code> are both passed, then the delta is
calculated between the two arguments. This is a convenience option because,
unlike <a href="#all_process_processhrtimetime"><code>process.hrtime()</code></a>, calculating the ELU is more complex than a
single subtraction.</p>
<p>ELU is similar to CPU utilization, except that it only measures event loop
statistics and not CPU usage. It represents the percentage of time the event
loop has spent outside the event loop's event provider (e.g. <code>epoll_wait</code>).
No other CPU idle time is taken into consideration. The following is an example
of how a mostly idle process will have a high ELU.</p>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> { eventLoopUtilization } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>).<span class="hljs-property">performance</span>;
<span class="hljs-keyword">const</span> { spawnSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> elu = <span class="hljs-title function_">eventLoopUtilization</span>();
<span class="hljs-title function_">spawnSync</span>(<span class="hljs-string">'sleep'</span>, [<span class="hljs-string">'5'</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">eventLoopUtilization</span>(elu).<span class="hljs-property">utilization</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Although the CPU is mostly idle while running this script, the value of
<code>utilization</code> is <code>1</code>. This is because the call to
<a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync()</code></a> blocks the event loop from proceeding.</p>
<p>Passing in a user-defined object instead of the result of a previous call to
<code>eventLoopUtilization()</code> will lead to undefined behavior. The return values
are not guaranteed to reflect any correct state of the event loop.</p>
<h4><code>performance.getEntries()</code><span><a class="mark" href="#all_perf_hooks_performancegetentries" id="all_perf_hooks_performancegetentries">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_getentries"></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.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry[]></a></li>
</ul>
<p>Returns a list of <code>PerformanceEntry</code> objects in chronological order with
respect to <code>performanceEntry.startTime</code>. If you are only interested in
performance entries of certain types or that have certain names, see
<code>performance.getEntriesByType()</code> and <code>performance.getEntriesByName()</code>.</p>
<h4><code>performance.getEntriesByName(name[, type])</code><span><a class="mark" href="#all_perf_hooks_performancegetentriesbynamename-type" id="all_perf_hooks_performancegetentriesbynamename-type">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_getentriesbyname_name_type"></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.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry[]></a></li>
</ul>
<p>Returns a list of <code>PerformanceEntry</code> objects in chronological order
with respect to <code>performanceEntry.startTime</code> whose <code>performanceEntry.name</code> is
equal to <code>name</code>, and optionally, whose <code>performanceEntry.entryType</code> is equal to
<code>type</code>.</p>
<h4><code>performance.getEntriesByType(type)</code><span><a class="mark" href="#all_perf_hooks_performancegetentriesbytypetype" id="all_perf_hooks_performancegetentriesbytypetype">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_getentriesbytype_type"></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.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry[]></a></li>
</ul>
<p>Returns a list of <code>PerformanceEntry</code> objects in chronological order
with respect to <code>performanceEntry.startTime</code> whose <code>performanceEntry.entryType</code>
is equal to <code>type</code>.</p>
<h4><code>performance.mark(name[, options])</code><span><a class="mark" href="#all_perf_hooks_performancemarkname-options" id="all_perf_hooks_performancemarkname-options">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_mark_name_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.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver. The name argument is no longer optional.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Updated to conform to the User Timing Level 3 specification.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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>detail</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Additional optional detail to include with the mark.</li>
<li><code>startTime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> An optional timestamp to be used as the mark time.
<strong>Default</strong>: <code>performance.now()</code>.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>PerformanceMark</code> entry in the Performance Timeline. A
<code>PerformanceMark</code> is a subclass of <code>PerformanceEntry</code> whose
<code>performanceEntry.entryType</code> is always <code>'mark'</code>, and whose
<code>performanceEntry.duration</code> is always <code>0</code>. Performance marks are used
to mark specific significant moments in the Performance Timeline.</p>
<p>The created <code>PerformanceMark</code> entry is put in the global Performance Timeline
and can be queried with <code>performance.getEntries</code>,
<code>performance.getEntriesByName</code>, and <code>performance.getEntriesByType</code>. When the
observation is performed, the entries should be cleared from the global
Performance Timeline manually with <code>performance.clearMarks</code>.</p>
<h4><code>performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode)</code><span><a class="mark" href="#all_perf_hooks_performancemarkresourcetimingtiminginfo-requestedurl-initiatortype-global-cachemode" id="all_perf_hooks_performancemarkresourcetimingtiminginfo-requestedurl-initiatortype-global-cachemode">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_markresourcetiming_timinginfo_requestedurl_initiatortype_global_cachemode"></a></h4>
<div class="api_metadata">
<span>Added in: v18.2.0, v16.17.0</span>
</div>
<ul>
<li><code>timingInfo</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="https://fetch.spec.whatwg.org/#fetch-timing-info">Fetch Timing Info</a></li>
<li><code>requestedUrl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The resource url</li>
<li><code>initiatorType</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The initiator name, e.g: 'fetch'</li>
<li><code>global</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>cacheMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The cache mode must be an empty string ('') or 'local'</li>
</ul>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>Creates a new <code>PerformanceResourceTiming</code> entry in the Resource Timeline. A
<code>PerformanceResourceTiming</code> is a subclass of <code>PerformanceEntry</code> whose
<code>performanceEntry.entryType</code> is always <code>'resource'</code>. Performance resources
are used to mark moments in the Resource Timeline.</p>
<p>The created <code>PerformanceMark</code> entry is put in the global Resource Timeline
and can be queried with <code>performance.getEntries</code>,
<code>performance.getEntriesByName</code>, and <code>performance.getEntriesByType</code>. When the
observation is performed, the entries should be cleared from the global
Performance Timeline manually with <code>performance.clearResourceTimings</code>.</p>
<h4><code>performance.measure(name[, startMarkOrOptions[, endMark]])</code><span><a class="mark" href="#all_perf_hooks_performancemeasurename-startmarkoroptions-endmark" id="all_perf_hooks_performancemeasurename-startmarkoroptions-endmark">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_measure_name_startmarkoroptions_endmark"></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.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Updated to conform to the User Timing Level 3 specification.</p></td></tr>
<tr><td>v13.13.0, v12.16.3</td>
<td><p>Make <code>startMark</code> and <code>endMark</code> parameters optional.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>startMarkOrOptions</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/Reference/Global_Objects/Object" class="type"><Object></a> Optional.
<ul>
<li><code>detail</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Additional optional detail to include with the measure.</li>
<li><code>duration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Duration between start and end times.</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Timestamp to be used as the end time, or a string
identifying a previously recorded mark.</li>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Timestamp to be used as the start time, or a string
identifying a previously recorded mark.</li>
</ul>
</li>
<li><code>endMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optional. Must be omitted if <code>startMarkOrOptions</code> is an
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>.</li>
</ul>
<p>Creates a new <code>PerformanceMeasure</code> entry in the Performance Timeline. A
<code>PerformanceMeasure</code> is a subclass of <code>PerformanceEntry</code> whose
<code>performanceEntry.entryType</code> is always <code>'measure'</code>, and whose
<code>performanceEntry.duration</code> measures the number of milliseconds elapsed since
<code>startMark</code> and <code>endMark</code>.</p>
<p>The <code>startMark</code> argument may identify any <em>existing</em> <code>PerformanceMark</code> in the
Performance Timeline, or <em>may</em> identify any of the timestamp properties
provided by the <code>PerformanceNodeTiming</code> class. If the named <code>startMark</code> does
not exist, an error is thrown.</p>
<p>The optional <code>endMark</code> argument must identify any <em>existing</em> <code>PerformanceMark</code>
in the Performance Timeline or any of the timestamp properties provided by the
<code>PerformanceNodeTiming</code> class. <code>endMark</code> will be <code>performance.now()</code>
if no parameter is passed, otherwise if the named <code>endMark</code> does not exist, an
error will be thrown.</p>
<p>The created <code>PerformanceMeasure</code> entry is put in the global Performance Timeline
and can be queried with <code>performance.getEntries</code>,
<code>performance.getEntriesByName</code>, and <code>performance.getEntriesByType</code>. When the
observation is performed, the entries should be cleared from the global
Performance Timeline manually with <code>performance.clearMeasures</code>.</p>
<h4><code>performance.nodeTiming</code><span><a class="mark" href="#all_perf_hooks_performancenodetiming" id="all_perf_hooks_performancenodetiming">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_nodetiming"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><a href="#all_perf_hooks_class-performancenodetiming" class="type"><PerformanceNodeTiming></a></li>
</ul>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>An instance of the <code>PerformanceNodeTiming</code> class that provides performance
metrics for specific Node.js operational milestones.</p>
<h4><code>performance.now()</code><span><a class="mark" href="#all_perf_hooks_performancenow" id="all_perf_hooks_performancenow">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_now"></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.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Returns the current high resolution millisecond timestamp, where 0 represents
the start of the current <code>node</code> process.</p>
<h4><code>performance.setResourceTimingBufferSize(maxSize)</code><span><a class="mark" href="#all_perf_hooks_performancesetresourcetimingbuffersizemaxsize" id="all_perf_hooks_performancesetresourcetimingbuffersizemaxsize">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_setresourcetimingbuffersize_maxsize"></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.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v18.8.0</td>
<td><p><span>Added in: v18.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Sets the global performance resource timing buffer size to the specified number
of "resource" type performance entry objects.</p>
<p>By default the max buffer size is set to 250.</p>
<h4><code>performance.timeOrigin</code><span><a class="mark" href="#all_perf_hooks_performancetimeorigin" id="all_perf_hooks_performancetimeorigin">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_timeorigin"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.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>The <a href="https://w3c.github.io/hr-time/#dom-performance-timeorigin"><code>timeOrigin</code></a> specifies the high resolution millisecond timestamp at
which the current <code>node</code> process began, measured in Unix time.</p>
<h4><code>performance.timerify(fn[, options])</code><span><a class="mark" href="#all_perf_hooks_performancetimerifyfn-options" id="all_perf_hooks_performancetimerifyfn-options">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_timerify_fn_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>v16.0.0</td>
<td><p>Added the histogram option.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Re-implemented to use pure-JavaScript and the ability to time async functions.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fn</code> <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>histogram</code> <a href="#all_perf_hooks_class-recordablehistogram-extends-histogram" class="type"><RecordableHistogram></a> A histogram object created using
<code>perf_hooks.createHistogram()</code> that will record runtime durations in
nanoseconds.</li>
</ul>
</li>
</ul>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>Wraps a function within a new function that measures the running time of the
wrapped function. A <code>PerformanceObserver</code> must be subscribed to the <code>'function'</code>
event type in order for the timing details to be accessed.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
performance,
<span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">someFunction</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'hello world'</span>);
}
<span class="hljs-keyword">const</span> wrapped = performance.<span class="hljs-title function_">timerify</span>(someFunction);
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">list</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(list.<span class="hljs-title function_">getEntries</span>()[<span class="hljs-number">0</span>].<span class="hljs-property">duration</span>);
performance.<span class="hljs-title function_">clearMarks</span>();
performance.<span class="hljs-title function_">clearMeasures</span>();
obs.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'function'</span>] });
<span class="hljs-comment">// A performance timeline entry will be created</span>
<span class="hljs-title function_">wrapped</span>();</code> <button class="copy-button">copy</button></pre>
<p>If the wrapped function returns a promise, a finally handler will be attached
to the promise and the duration will be reported once the finally handler is
invoked.</p>
<h4><code>performance.toJSON()</code><span><a class="mark" href="#all_perf_hooks_performancetojson" id="all_perf_hooks_performancetojson">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_tojson"></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.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v16.1.0</td>
<td><p><span>Added in: v16.1.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An object which is JSON representation of the <code>performance</code> object. It
is similar to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON"><code>window.performance.toJSON</code></a> in browsers.</p>
<h5>Event: <code>'resourcetimingbufferfull'</code><span><a class="mark" href="#all_perf_hooks_event-resourcetimingbufferfull" id="all_perf_hooks_event-resourcetimingbufferfull">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_event_resourcetimingbufferfull"></a></h5>
<div class="api_metadata">
<span>Added in: v18.8.0</span>
</div>
<p>The <code>'resourcetimingbufferfull'</code> event is fired when the global performance
resource timing buffer is full. Adjust resource timing buffer size with
<code>performance.setResourceTimingBufferSize()</code> or clear the buffer with
<code>performance.clearResourceTimings()</code> in the event listener to allow
more entries to be added to the performance timeline buffer.</p>
</section><section><h3>Class: <code>PerformanceEntry</code><span><a class="mark" href="#all_perf_hooks_class-performanceentry" id="all_perf_hooks_class-performanceentry">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performanceentry"></a></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>The constructor of this class is not exposed to users directly.</p>
<h4><code>performanceEntry.duration</code><span><a class="mark" href="#all_perf_hooks_performanceentryduration" id="all_perf_hooks_performanceentryduration">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceentry_duration"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceEntry</code> object as the receiver.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</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>The total number of milliseconds elapsed for this entry. This value will not
be meaningful for all Performance Entry types.</p>
<h4><code>performanceEntry.entryType</code><span><a class="mark" href="#all_perf_hooks_performanceentryentrytype" id="all_perf_hooks_performanceentryentrytype">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceentry_entrytype"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceEntry</code> object as the receiver.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The type of the performance entry. It may be one of:</p>
<ul>
<li><code>'dns'</code> (Node.js only)</li>
<li><code>'function'</code> (Node.js only)</li>
<li><code>'gc'</code> (Node.js only)</li>
<li><code>'http2'</code> (Node.js only)</li>
<li><code>'http'</code> (Node.js only)</li>
<li><code>'mark'</code> (available on the Web)</li>
<li><code>'measure'</code> (available on the Web)</li>
<li><code>'net'</code> (Node.js only)</li>
<li><code>'node'</code> (Node.js only)</li>
<li><code>'resource'</code> (available on the Web)</li>
</ul>
<h4><code>performanceEntry.name</code><span><a class="mark" href="#all_perf_hooks_performanceentryname" id="all_perf_hooks_performanceentryname">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceentry_name"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceEntry</code> object as the receiver.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The name of the performance entry.</p>
<h4><code>performanceEntry.startTime</code><span><a class="mark" href="#all_perf_hooks_performanceentrystarttime" id="all_perf_hooks_performanceentrystarttime">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceentry_starttime"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceEntry</code> object as the receiver.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</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>The high resolution millisecond timestamp marking the starting time of the
Performance Entry.</p>
</section><section><h3>Class: <code>PerformanceMark</code><span><a class="mark" href="#all_perf_hooks_class-performancemark" id="all_perf_hooks_class-performancemark">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performancemark"></a></h3>
<div class="api_metadata">
<span>Added in: v18.2.0, v16.17.0</span>
</div>
<ul>
<li>Extends: <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry></a></li>
</ul>
<p>Exposes marks created via the <code>Performance.mark()</code> method.</p>
<h4><code>performanceMark.detail</code><span><a class="mark" href="#all_perf_hooks_performancemarkdetail" id="all_perf_hooks_performancemarkdetail">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancemark_detail"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceMark</code> object as the receiver.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p><span>Added in: v16.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Additional detail specified when creating with <code>Performance.mark()</code> method.</p>
</section><section><h3>Class: <code>PerformanceMeasure</code><span><a class="mark" href="#all_perf_hooks_class-performancemeasure" id="all_perf_hooks_class-performancemeasure">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performancemeasure"></a></h3>
<div class="api_metadata">
<span>Added in: v18.2.0, v16.17.0</span>
</div>
<ul>
<li>Extends: <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry></a></li>
</ul>
<p>Exposes measures created via the <code>Performance.measure()</code> method.</p>
<p>The constructor of this class is not exposed to users directly.</p>
<h4><code>performanceMeasure.detail</code><span><a class="mark" href="#all_perf_hooks_performancemeasuredetail" id="all_perf_hooks_performancemeasuredetail">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancemeasure_detail"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceMeasure</code> object as the receiver.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p><span>Added in: v16.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Additional detail specified when creating with <code>Performance.measure()</code> method.</p>
</section><section><h3>Class: <code>PerformanceNodeEntry</code><span><a class="mark" href="#all_perf_hooks_class-performancenodeentry" id="all_perf_hooks_class-performancenodeentry">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performancenodeentry"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<ul>
<li>Extends: <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry></a></li>
</ul>
<p><em>This class is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>Provides detailed Node.js timing data.</p>
<p>The constructor of this class is not exposed to users directly.</p>
<h4><code>performanceNodeEntry.detail</code><span><a class="mark" href="#all_perf_hooks_performancenodeentrydetail" id="all_perf_hooks_performancenodeentrydetail">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodeentry_detail"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceNodeEntry</code> object as the receiver.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p><span>Added in: v16.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Additional detail specific to the <code>entryType</code>.</p>
<h4><code>performanceNodeEntry.flags</code><span><a class="mark" href="#all_perf_hooks_performancenodeentryflags" id="all_perf_hooks_performancenodeentryflags">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodeentry_flags"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecated. Now moved to the detail property when entryType is 'gc'.</p></td></tr>
<tr><td>v13.9.0, v12.17.0</td>
<td><p><span>Added in: v13.9.0, v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <code>performanceNodeEntry.detail</code> instead.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>When <code>performanceEntry.entryType</code> is equal to <code>'gc'</code>, the <code>performance.flags</code>
property contains additional information about garbage collection operation.
The value may be one of:</p>
<ul>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE</code></li>
</ul>
<h4><code>performanceNodeEntry.kind</code><span><a class="mark" href="#all_perf_hooks_performancenodeentrykind" id="all_perf_hooks_performancenodeentrykind">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodeentry_kind"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecated. Now moved to the detail property when entryType is 'gc'.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <code>performanceNodeEntry.detail</code> instead.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>When <code>performanceEntry.entryType</code> is equal to <code>'gc'</code>, the <code>performance.kind</code>
property identifies the type of garbage collection operation that occurred.
The value may be one of:</p>
<ul>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB</code></li>
</ul>
<h4>Garbage Collection ('gc') Details<span><a class="mark" href="#all_perf_hooks_garbage-collection-gc-details" id="all_perf_hooks_garbage-collection-gc-details">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_garbage_collection_gc_details"></a></h4>
<p>When <code>performanceEntry.type</code> is equal to <code>'gc'</code>, the
<code>performanceNodeEntry.detail</code> property will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> with two properties:</p>
<ul>
<li><code>kind</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> One of:
<ul>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB</code></li>
</ul>
</li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> One of:
<ul>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE</code></li>
</ul>
</li>
</ul>
<h4>HTTP ('http') Details<span><a class="mark" href="#all_perf_hooks_http-http-details" id="all_perf_hooks_http-http-details">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_http_http_details"></a></h4>
<p>When <code>performanceEntry.type</code> is equal to <code>'http'</code>, the
<code>performanceNodeEntry.detail</code> property will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> containing
additional information.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>HttpClient</code>, the <code>detail</code>
will contain the following properties: <code>req</code>, <code>res</code>. And the <code>req</code> property
will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> containing <code>method</code>, <code>url</code>, <code>headers</code>, the <code>res</code> property
will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> containing <code>statusCode</code>, <code>statusMessage</code>, <code>headers</code>.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>HttpRequest</code>, the <code>detail</code>
will contain the following properties: <code>req</code>, <code>res</code>. And the <code>req</code> property
will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> containing <code>method</code>, <code>url</code>, <code>headers</code>, the <code>res</code> property
will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> containing <code>statusCode</code>, <code>statusMessage</code>, <code>headers</code>.</p>
<p>This could add additional memory overhead and should only be used for
diagnostic purposes, not left turned on in production by default.</p>
<h4>HTTP/2 ('http2') Details<span><a class="mark" href="#all_perf_hooks_http2-http2-details" id="all_perf_hooks_http2-http2-details">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_http_2_http2_details"></a></h4>
<p>When <code>performanceEntry.type</code> is equal to <code>'http2'</code>, the
<code>performanceNodeEntry.detail</code> property will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> containing
additional performance information.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>Http2Stream</code>, the <code>detail</code>
will contain the following properties:</p>
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of <code>DATA</code> frame bytes received for this
<code>Http2Stream</code>.</li>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of <code>DATA</code> frame bytes sent for this
<code>Http2Stream</code>.</li>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The identifier of the associated <code>Http2Stream</code></li>
<li><code>timeToFirstByte</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds elapsed between the
<code>PerformanceEntry</code> <code>startTime</code> and the reception of the first <code>DATA</code> frame.</li>
<li><code>timeToFirstByteSent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds elapsed between
the <code>PerformanceEntry</code> <code>startTime</code> and sending of the first <code>DATA</code> frame.</li>
<li><code>timeToFirstHeader</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds elapsed between the
<code>PerformanceEntry</code> <code>startTime</code> and the reception of the first header.</li>
</ul>
<p>If <code>performanceEntry.name</code> is equal to <code>Http2Session</code>, the <code>detail</code> will
contain the following properties:</p>
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes received for this <code>Http2Session</code>.</li>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes sent for this <code>Http2Session</code>.</li>
<li><code>framesReceived</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of HTTP/2 frames received by the
<code>Http2Session</code>.</li>
<li><code>framesSent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of HTTP/2 frames sent by the <code>Http2Session</code>.</li>
<li><code>maxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum number of streams concurrently
open during the lifetime of the <code>Http2Session</code>.</li>
<li><code>pingRTT</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds elapsed since the transmission
of a <code>PING</code> frame and the reception of its acknowledgment. Only present if
a <code>PING</code> frame has been sent on the <code>Http2Session</code>.</li>
<li><code>streamAverageDuration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The average duration (in milliseconds) for
all <code>Http2Stream</code> instances.</li>
<li><code>streamCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of <code>Http2Stream</code> instances processed by
the <code>Http2Session</code>.</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>'server'</code> or <code>'client'</code> to identify the type of
<code>Http2Session</code>.</li>
</ul>
<h4>Timerify ('function') Details<span><a class="mark" href="#all_perf_hooks_timerify-function-details" id="all_perf_hooks_timerify-function-details">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_timerify_function_details"></a></h4>
<p>When <code>performanceEntry.type</code> is equal to <code>'function'</code>, the
<code>performanceNodeEntry.detail</code> property will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> listing
the input arguments to the timed function.</p>
<h4>Net ('net') Details<span><a class="mark" href="#all_perf_hooks_net-net-details" id="all_perf_hooks_net-net-details">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_net_net_details"></a></h4>
<p>When <code>performanceEntry.type</code> is equal to <code>'net'</code>, the
<code>performanceNodeEntry.detail</code> property will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> containing
additional information.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>connect</code>, the <code>detail</code>
will contain the following properties: <code>host</code>, <code>port</code>.</p>
<h4>DNS ('dns') Details<span><a class="mark" href="#all_perf_hooks_dns-dns-details" id="all_perf_hooks_dns-dns-details">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_dns_dns_details"></a></h4>
<p>When <code>performanceEntry.type</code> is equal to <code>'dns'</code>, the
<code>performanceNodeEntry.detail</code> property will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> containing
additional information.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>lookup</code>, the <code>detail</code>
will contain the following properties: <code>hostname</code>, <code>family</code>, <code>hints</code>, <code>verbatim</code>,
<code>addresses</code>.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>lookupService</code>, the <code>detail</code> will
contain the following properties: <code>host</code>, <code>port</code>, <code>hostname</code>, <code>service</code>.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>queryxxx</code> or <code>getHostByAddr</code>, the <code>detail</code> will
contain the following properties: <code>host</code>, <code>ttl</code>, <code>result</code>. The value of <code>result</code> is
same as the result of <code>queryxxx</code> or <code>getHostByAddr</code>.</p>
</section><section><h3>Class: <code>PerformanceNodeTiming</code><span><a class="mark" href="#all_perf_hooks_class-performancenodetiming" id="all_perf_hooks_class-performancenodetiming">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performancenodetiming"></a></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li>Extends: <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry></a></li>
</ul>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>Provides timing details for Node.js itself. The constructor of this class
is not exposed to users.</p>
<h4><code>performanceNodeTiming.bootstrapComplete</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingbootstrapcomplete" id="all_perf_hooks_performancenodetimingbootstrapcomplete">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_bootstrapcomplete"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.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>The high resolution millisecond timestamp at which the Node.js process
completed bootstrapping. If bootstrapping has not yet finished, the property
has the value of -1.</p>
<h4><code>performanceNodeTiming.environment</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingenvironment" id="all_perf_hooks_performancenodetimingenvironment">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_environment"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.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>The high resolution millisecond timestamp at which the Node.js environment was
initialized.</p>
<h4><code>performanceNodeTiming.idleTime</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingidletime" id="all_perf_hooks_performancenodetimingidletime">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_idletime"></a></h4>
<div class="api_metadata">
<span>Added in: v14.10.0, v12.19.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>The high resolution millisecond timestamp of the amount of time the event loop
has been idle within the event loop's event provider (e.g. <code>epoll_wait</code>). This
does not take CPU usage into consideration. If the event loop has not yet
started (e.g., in the first tick of the main script), the property has the
value of 0.</p>
<h4><code>performanceNodeTiming.loopExit</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingloopexit" id="all_perf_hooks_performancenodetimingloopexit">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_loopexit"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.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>The high resolution millisecond timestamp at which the Node.js event loop
exited. If the event loop has not yet exited, the property has the value of -1.
It can only have a value of not -1 in a handler of the <a href="#all_process_event-exit"><code>'exit'</code></a> event.</p>
<h4><code>performanceNodeTiming.loopStart</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingloopstart" id="all_perf_hooks_performancenodetimingloopstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_loopstart"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.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>The high resolution millisecond timestamp at which the Node.js event loop
started. If the event loop has not yet started (e.g., in the first tick of the
main script), the property has the value of -1.</p>
<h4><code>performanceNodeTiming.nodeStart</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingnodestart" id="all_perf_hooks_performancenodetimingnodestart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_nodestart"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.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>The high resolution millisecond timestamp at which the Node.js process was
initialized.</p>
<h4><code>performanceNodeTiming.uvMetricsInfo</code><span><a class="mark" href="#all_perf_hooks_performancenodetiminguvmetricsinfo" id="all_perf_hooks_performancenodetiminguvmetricsinfo">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_uvmetricsinfo"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>loopCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of event loop iterations.</li>
<li><code>events</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of events that have been processed by the event handler.</li>
<li><code>eventsWaiting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of events that were waiting to be processed when the event provider was called.</li>
</ul>
</li>
</ul>
<p>This is a wrapper to the <code>uv_metrics_info</code> function.
It returns the current set of event loop metrics.</p>
<p>It is recommended to use this property inside a function whose execution was
scheduled using <code>setImmediate</code> to avoid collecting metrics before finishing all
operations scheduled during the current loop iteration.</p>
<pre class="with-51-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> { performance } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(performance.<span class="hljs-property">nodeTiming</span>.<span class="hljs-property">uvMetricsInfo</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { performance } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:perf_hooks'</span>;
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(performance.<span class="hljs-property">nodeTiming</span>.<span class="hljs-property">uvMetricsInfo</span>);
});</code><button class="copy-button">copy</button></pre>
<h4><code>performanceNodeTiming.v8Start</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingv8start" id="all_perf_hooks_performancenodetimingv8start">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_v8start"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.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>The high resolution millisecond timestamp at which the V8 platform was
initialized.</p>
</section><section><h3>Class: <code>PerformanceResourceTiming</code><span><a class="mark" href="#all_perf_hooks_class-performanceresourcetiming" id="all_perf_hooks_class-performanceresourcetiming">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performanceresourcetiming"></a></h3>
<div class="api_metadata">
<span>Added in: v18.2.0, v16.17.0</span>
</div>
<ul>
<li>Extends: <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry></a></li>
</ul>
<p>Provides detailed network timing data regarding the loading of an application's
resources.</p>
<p>The constructor of this class is not exposed to users directly.</p>
<h4><code>performanceResourceTiming.workerStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingworkerstart" id="all_perf_hooks_performanceresourcetimingworkerstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_workerstart"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>The high resolution millisecond timestamp at immediately before dispatching
the <code>fetch</code> request. If the resource is not intercepted by a worker the property
will always return 0.</p>
<h4><code>performanceResourceTiming.redirectStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingredirectstart" id="all_perf_hooks_performanceresourcetimingredirectstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_redirectstart"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>The high resolution millisecond timestamp that represents the start time
of the fetch which initiates the redirect.</p>
<h4><code>performanceResourceTiming.redirectEnd</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingredirectend" id="all_perf_hooks_performanceresourcetimingredirectend">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_redirectend"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>The high resolution millisecond timestamp that will be created immediately after
receiving the last byte of the response of the last redirect.</p>
<h4><code>performanceResourceTiming.fetchStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingfetchstart" id="all_perf_hooks_performanceresourcetimingfetchstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_fetchstart"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>The high resolution millisecond timestamp immediately before the Node.js starts
to fetch the resource.</p>
<h4><code>performanceResourceTiming.domainLookupStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingdomainlookupstart" id="all_perf_hooks_performanceresourcetimingdomainlookupstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_domainlookupstart"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>The high resolution millisecond timestamp immediately before the Node.js starts
the domain name lookup for the resource.</p>
<h4><code>performanceResourceTiming.domainLookupEnd</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingdomainlookupend" id="all_perf_hooks_performanceresourcetimingdomainlookupend">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_domainlookupend"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>The high resolution millisecond timestamp representing the time immediately
after the Node.js finished the domain name lookup for the resource.</p>
<h4><code>performanceResourceTiming.connectStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingconnectstart" id="all_perf_hooks_performanceresourcetimingconnectstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_connectstart"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>The high resolution millisecond timestamp representing the time immediately
before Node.js starts to establish the connection to the server to retrieve
the resource.</p>
<h4><code>performanceResourceTiming.connectEnd</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingconnectend" id="all_perf_hooks_performanceresourcetimingconnectend">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_connectend"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>The high resolution millisecond timestamp representing the time immediately
after Node.js finishes establishing the connection to the server to retrieve
the resource.</p>
<h4><code>performanceResourceTiming.secureConnectionStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingsecureconnectionstart" id="all_perf_hooks_performanceresourcetimingsecureconnectionstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_secureconnectionstart"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>The high resolution millisecond timestamp representing the time immediately
before Node.js starts the handshake process to secure the current connection.</p>
<h4><code>performanceResourceTiming.requestStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingrequeststart" id="all_perf_hooks_performanceresourcetimingrequeststart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_requeststart"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>The high resolution millisecond timestamp representing the time immediately
before Node.js receives the first byte of the response from the server.</p>
<h4><code>performanceResourceTiming.responseEnd</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingresponseend" id="all_perf_hooks_performanceresourcetimingresponseend">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_responseend"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>The high resolution millisecond timestamp representing the time immediately
after Node.js receives the last byte of the resource or immediately before
the transport connection is closed, whichever comes first.</p>
<h4><code>performanceResourceTiming.transferSize</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingtransfersize" id="all_perf_hooks_performanceresourcetimingtransfersize">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_transfersize"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>A number representing the size (in octets) of the fetched resource. The size
includes the response header fields plus the response payload body.</p>
<h4><code>performanceResourceTiming.encodedBodySize</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingencodedbodysize" id="all_perf_hooks_performanceresourcetimingencodedbodysize">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_encodedbodysize"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>A number representing the size (in octets) received from the fetch
(HTTP or cache), of the payload body, before removing any applied
content-codings.</p>
<h4><code>performanceResourceTiming.decodedBodySize</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingdecodedbodysize" id="all_perf_hooks_performanceresourcetimingdecodedbodysize">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_decodedbodysize"></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.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>A number representing the size (in octets) received from the fetch
(HTTP or cache), of the message body, after removing any applied
content-codings.</p>
<h4><code>performanceResourceTiming.toJSON()</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingtojson" id="all_perf_hooks_performanceresourcetimingtojson">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_tojson"></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.0.0</td>
<td><p>This method must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Returns a <code>object</code> that is the JSON representation of the
<code>PerformanceResourceTiming</code> object</p>
</section><section><h3>Class: <code>PerformanceObserver</code><span><a class="mark" href="#all_perf_hooks_class-performanceobserver" id="all_perf_hooks_class-performanceobserver">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performanceobserver"></a></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<h4><code>PerformanceObserver.supportedEntryTypes</code><span><a class="mark" href="#all_perf_hooks_performanceobserversupportedentrytypes" id="all_perf_hooks_performanceobserversupportedentrytypes">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserver_supportedentrytypes"></a></h4>
<div class="api_metadata">
<span>Added in: v16.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>Get supported types.</p>
<h4><code>new PerformanceObserver(callback)</code><span><a class="mark" href="#all_perf_hooks_new-performanceobservercallback" id="all_perf_hooks_new-performanceobservercallback">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_new_performanceobserver_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>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>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</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>
<ul>
<li><code>list</code> <a href="#all_perf_hooks_class-performanceobserverentrylist" class="type"><PerformanceObserverEntryList></a></li>
<li><code>observer</code> <a href="#all_perf_hooks_class-performanceobserver" class="type"><PerformanceObserver></a></li>
</ul>
</li>
</ul>
<p><code>PerformanceObserver</code> objects provide notifications when new
<code>PerformanceEntry</code> instances have been added to the Performance Timeline.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
performance,
<span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">list, observer</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(list.<span class="hljs-title function_">getEntries</span>());
performance.<span class="hljs-title function_">clearMarks</span>();
performance.<span class="hljs-title function_">clearMeasures</span>();
observer.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'mark'</span>], <span class="hljs-attr">buffered</span>: <span class="hljs-literal">true</span> });
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'test'</span>);</code> <button class="copy-button">copy</button></pre>
<p>Because <code>PerformanceObserver</code> instances introduce their own additional
performance overhead, instances should not be left subscribed to notifications
indefinitely. Users should disconnect observers as soon as they are no
longer needed.</p>
<p>The <code>callback</code> is invoked when a <code>PerformanceObserver</code> is
notified about new <code>PerformanceEntry</code> instances. The callback receives a
<code>PerformanceObserverEntryList</code> instance and a reference to the
<code>PerformanceObserver</code>.</p>
<h4><code>performanceObserver.disconnect()</code><span><a class="mark" href="#all_perf_hooks_performanceobserverdisconnect" id="all_perf_hooks_performanceobserverdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserver_disconnect"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>Disconnects the <code>PerformanceObserver</code> instance from all notifications.</p>
<h4><code>performanceObserver.observe(options)</code><span><a class="mark" href="#all_perf_hooks_performanceobserverobserveoptions" id="all_perf_hooks_performanceobserverobserveoptions">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserver_observe_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>v16.7.0</td>
<td><p>Updated to conform to Performance Timeline Level 2. The buffered option has been added back.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Updated to conform to User Timing Level 3. The buffered option has been removed.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></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>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A single <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry></a> type. Must not be given
if <code>entryTypes</code> is already specified.</li>
<li><code>entryTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array of strings identifying the types of
<a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry></a> instances the observer is interested in. If not
provided an error will be thrown.</li>
<li><code>buffered</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If true, the observer callback is called with a
list global <code>PerformanceEntry</code> buffered entries. If false, only
<code>PerformanceEntry</code>s created after the time point are sent to the
observer callback. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Subscribes the <a href="#all_perf_hooks_class-performanceobserver" class="type"><PerformanceObserver></a> instance to notifications of new
<a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry></a> instances identified either by <code>options.entryTypes</code>
or <code>options.type</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
performance,
<span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">list, observer</span>) =></span> {
<span class="hljs-comment">// Called once asynchronously. `list` contains three items.</span>
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">type</span>: <span class="hljs-string">'mark'</span> });
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n < <span class="hljs-number">3</span>; n++)
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">`test<span class="hljs-subst">${n}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>performanceObserver.takeRecords()</code><span><a class="mark" href="#all_perf_hooks_performanceobservertakerecords" id="all_perf_hooks_performanceobservertakerecords">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserver_takerecords"></a></h4>
<div class="api_metadata">
<span>Added in: v16.0.0</span>
</div>
<ul>
<li>Returns: <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry[]></a> Current list of entries stored in the performance observer, emptying it out.</li>
</ul>
</section><section><h3>Class: <code>PerformanceObserverEntryList</code><span><a class="mark" href="#all_perf_hooks_class-performanceobserverentrylist" id="all_perf_hooks_class-performanceobserverentrylist">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performanceobserverentrylist"></a></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>The <code>PerformanceObserverEntryList</code> class is used to provide access to the
<code>PerformanceEntry</code> instances passed to a <code>PerformanceObserver</code>.
The constructor of this class is not exposed to users.</p>
<h4><code>performanceObserverEntryList.getEntries()</code><span><a class="mark" href="#all_perf_hooks_performanceobserverentrylistgetentries" id="all_perf_hooks_performanceobserverentrylistgetentries">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserverentrylist_getentries"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li>Returns: <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry[]></a></li>
</ul>
<p>Returns a list of <code>PerformanceEntry</code> objects in chronological order
with respect to <code>performanceEntry.startTime</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
performance,
<span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">perfObserverList, observer</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(perfObserverList.<span class="hljs-title function_">getEntries</span>());
<span class="hljs-comment">/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 81.465639,
* duration: 0,
* detail: null
* },
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 81.860064,
* duration: 0,
* detail: null
* }
* ]
*/</span>
performance.<span class="hljs-title function_">clearMarks</span>();
performance.<span class="hljs-title function_">clearMeasures</span>();
observer.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">type</span>: <span class="hljs-string">'mark'</span> });
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'test'</span>);
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'meow'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>performanceObserverEntryList.getEntriesByName(name[, type])</code><span><a class="mark" href="#all_perf_hooks_performanceobserverentrylistgetentriesbynamename-type" id="all_perf_hooks_performanceobserverentrylistgetentriesbynamename-type">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserverentrylist_getentriesbyname_name_type"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry[]></a></li>
</ul>
<p>Returns a list of <code>PerformanceEntry</code> objects in chronological order
with respect to <code>performanceEntry.startTime</code> whose <code>performanceEntry.name</code> is
equal to <code>name</code>, and optionally, whose <code>performanceEntry.entryType</code> is equal to
<code>type</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
performance,
<span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">perfObserverList, observer</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(perfObserverList.<span class="hljs-title function_">getEntriesByName</span>(<span class="hljs-string">'meow'</span>));
<span class="hljs-comment">/**
* [
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 98.545991,
* duration: 0,
* detail: null
* }
* ]
*/</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(perfObserverList.<span class="hljs-title function_">getEntriesByName</span>(<span class="hljs-string">'nope'</span>)); <span class="hljs-comment">// []</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(perfObserverList.<span class="hljs-title function_">getEntriesByName</span>(<span class="hljs-string">'test'</span>, <span class="hljs-string">'mark'</span>));
<span class="hljs-comment">/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 63.518931,
* duration: 0,
* detail: null
* }
* ]
*/</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(perfObserverList.<span class="hljs-title function_">getEntriesByName</span>(<span class="hljs-string">'test'</span>, <span class="hljs-string">'measure'</span>)); <span class="hljs-comment">// []</span>
performance.<span class="hljs-title function_">clearMarks</span>();
performance.<span class="hljs-title function_">clearMeasures</span>();
observer.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'mark'</span>, <span class="hljs-string">'measure'</span>] });
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'test'</span>);
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'meow'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>performanceObserverEntryList.getEntriesByType(type)</code><span><a class="mark" href="#all_perf_hooks_performanceobserverentrylistgetentriesbytypetype" id="all_perf_hooks_performanceobserverentrylistgetentriesbytypetype">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserverentrylist_getentriesbytype_type"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="#all_perf_hooks_class-performanceentry" class="type"><PerformanceEntry[]></a></li>
</ul>
<p>Returns a list of <code>PerformanceEntry</code> objects in chronological order
with respect to <code>performanceEntry.startTime</code> whose <code>performanceEntry.entryType</code>
is equal to <code>type</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
performance,
<span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">perfObserverList, observer</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(perfObserverList.<span class="hljs-title function_">getEntriesByType</span>(<span class="hljs-string">'mark'</span>));
<span class="hljs-comment">/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 55.897834,
* duration: 0,
* detail: null
* },
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 56.350146,
* duration: 0,
* detail: null
* }
* ]
*/</span>
performance.<span class="hljs-title function_">clearMarks</span>();
performance.<span class="hljs-title function_">clearMeasures</span>();
observer.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">type</span>: <span class="hljs-string">'mark'</span> });
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'test'</span>);
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'meow'</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>perf_hooks.createHistogram([options])</code><span><a class="mark" href="#all_perf_hooks_perf_hookscreatehistogramoptions" id="all_perf_hooks_perf_hookscreatehistogramoptions">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_perf_hooks_createhistogram_options"></a></h3>
<div class="api_metadata">
<span>Added in: v15.9.0, v14.18.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>
<ul>
<li><code>lowest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> The lowest discernible value. Must be an integer
value greater than 0. <strong>Default:</strong> <code>1</code>.</li>
<li><code>highest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> The highest recordable value. Must be an integer
value that is equal to or greater than two times <code>lowest</code>.
<strong>Default:</strong> <code>Number.MAX_SAFE_INTEGER</code>.</li>
<li><code>figures</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of accuracy digits. Must be a number between
<code>1</code> and <code>5</code>. <strong>Default:</strong> <code>3</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_perf_hooks_class-recordablehistogram-extends-histogram" class="type"><RecordableHistogram></a></li>
</ul>
<p>Returns a <a href="#all_perf_hooks_class-recordablehistogram-extends-histogram" class="type"><RecordableHistogram></a>.</p>
</section><section><h3><code>perf_hooks.monitorEventLoopDelay([options])</code><span><a class="mark" href="#all_perf_hooks_perf_hooksmonitoreventloopdelayoptions" id="all_perf_hooks_perf_hooksmonitoreventloopdelayoptions">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_perf_hooks_monitoreventloopdelay_options"></a></h3>
<div class="api_metadata">
<span>Added in: v11.10.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>
<ul>
<li><code>resolution</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The sampling rate in milliseconds. Must be greater
than zero. <strong>Default:</strong> <code>10</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_perf_hooks_class-intervalhistogram-extends-histogram" class="type"><IntervalHistogram></a></li>
</ul>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>Creates an <code>IntervalHistogram</code> object that samples and reports the event loop
delay over time. The delays will be reported in nanoseconds.</p>
<p>Using a timer to detect approximate event loop delay works because the
execution of timers is tied specifically to the lifecycle of the libuv
event loop. That is, a delay in the loop will cause a delay in the execution
of the timer, and those delays are specifically what this API is intended to
detect.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { monitorEventLoopDelay } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> h = <span class="hljs-title function_">monitorEventLoopDelay</span>({ <span class="hljs-attr">resolution</span>: <span class="hljs-number">20</span> });
h.<span class="hljs-title function_">enable</span>();
<span class="hljs-comment">// Do something.</span>
h.<span class="hljs-title function_">disable</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-property">min</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-property">max</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-property">mean</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-property">stddev</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-property">percentiles</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-title function_">percentile</span>(<span class="hljs-number">50</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-title function_">percentile</span>(<span class="hljs-number">99</span>));</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>Histogram</code><span><a class="mark" href="#all_perf_hooks_class-histogram" id="all_perf_hooks_class-histogram">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_histogram"></a></h3>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<h4><code>histogram.count</code><span><a class="mark" href="#all_perf_hooks_histogramcount" id="all_perf_hooks_histogramcount">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_count"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.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>The number of samples recorded by the histogram.</p>
<h4><code>histogram.countBigInt</code><span><a class="mark" href="#all_perf_hooks_histogramcountbigint" id="all_perf_hooks_histogramcountbigint">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_countbigint"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The number of samples recorded by the histogram.</p>
<h4><code>histogram.exceeds</code><span><a class="mark" href="#all_perf_hooks_histogramexceeds" id="all_perf_hooks_histogramexceeds">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_exceeds"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.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>The number of times the event loop delay exceeded the maximum 1 hour event
loop delay threshold.</p>
<h4><code>histogram.exceedsBigInt</code><span><a class="mark" href="#all_perf_hooks_histogramexceedsbigint" id="all_perf_hooks_histogramexceedsbigint">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_exceedsbigint"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The number of times the event loop delay exceeded the maximum 1 hour event
loop delay threshold.</p>
<h4><code>histogram.max</code><span><a class="mark" href="#all_perf_hooks_histogrammax" id="all_perf_hooks_histogrammax">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_max"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.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>The maximum recorded event loop delay.</p>
<h4><code>histogram.maxBigInt</code><span><a class="mark" href="#all_perf_hooks_histogrammaxbigint" id="all_perf_hooks_histogrammaxbigint">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_maxbigint"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The maximum recorded event loop delay.</p>
<h4><code>histogram.mean</code><span><a class="mark" href="#all_perf_hooks_histogrammean" id="all_perf_hooks_histogrammean">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_mean"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.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>The mean of the recorded event loop delays.</p>
<h4><code>histogram.min</code><span><a class="mark" href="#all_perf_hooks_histogrammin" id="all_perf_hooks_histogrammin">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_min"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.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>The minimum recorded event loop delay.</p>
<h4><code>histogram.minBigInt</code><span><a class="mark" href="#all_perf_hooks_histogramminbigint" id="all_perf_hooks_histogramminbigint">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_minbigint"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The minimum recorded event loop delay.</p>
<h4><code>histogram.percentile(percentile)</code><span><a class="mark" href="#all_perf_hooks_histogrampercentilepercentile" id="all_perf_hooks_histogrampercentilepercentile">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_percentile_percentile"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><code>percentile</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A percentile value in the range (0, 100].</li>
<li>Returns: <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 at the given percentile.</p>
<h4><code>histogram.percentileBigInt(percentile)</code><span><a class="mark" href="#all_perf_hooks_histogrampercentilebigintpercentile" id="all_perf_hooks_histogrampercentilebigintpercentile">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_percentilebigint_percentile"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.0</span>
</div>
<ul>
<li><code>percentile</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A percentile value in the range (0, 100].</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>Returns the value at the given percentile.</p>
<h4><code>histogram.percentiles</code><span><a class="mark" href="#all_perf_hooks_histogrampercentiles" id="all_perf_hooks_histogrampercentiles">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_percentiles"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type"><Map></a></li>
</ul>
<p>Returns a <code>Map</code> object detailing the accumulated percentile distribution.</p>
<h4><code>histogram.percentilesBigInt</code><span><a class="mark" href="#all_perf_hooks_histogrampercentilesbigint" id="all_perf_hooks_histogrampercentilesbigint">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_percentilesbigint"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type"><Map></a></li>
</ul>
<p>Returns a <code>Map</code> object detailing the accumulated percentile distribution.</p>
<h4><code>histogram.reset()</code><span><a class="mark" href="#all_perf_hooks_histogramreset" id="all_perf_hooks_histogramreset">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_reset"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<p>Resets the collected histogram data.</p>
<h4><code>histogram.stddev</code><span><a class="mark" href="#all_perf_hooks_histogramstddev" id="all_perf_hooks_histogramstddev">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_stddev"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.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>The standard deviation of the recorded event loop delays.</p>
</section><section><h3>Class: <code>IntervalHistogram extends Histogram</code><span><a class="mark" href="#all_perf_hooks_class-intervalhistogram-extends-histogram" id="all_perf_hooks_class-intervalhistogram-extends-histogram">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_intervalhistogram_extends_histogram"></a></h3>
<p>A <code>Histogram</code> that is periodically updated on a given interval.</p>
<h4><code>histogram.disable()</code><span><a class="mark" href="#all_perf_hooks_histogramdisable" id="all_perf_hooks_histogramdisable">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_disable"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</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>Disables the update interval timer. Returns <code>true</code> if the timer was
stopped, <code>false</code> if it was already stopped.</p>
<h4><code>histogram.enable()</code><span><a class="mark" href="#all_perf_hooks_histogramenable" id="all_perf_hooks_histogramenable">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_enable"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</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>Enables the update interval timer. Returns <code>true</code> if the timer was
started, <code>false</code> if it was already started.</p>
<h4>Cloning an <code>IntervalHistogram</code><span><a class="mark" href="#all_perf_hooks_cloning-an-intervalhistogram" id="all_perf_hooks_cloning-an-intervalhistogram">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_cloning_an_intervalhistogram"></a></h4>
<p><a href="#all_perf_hooks_class-intervalhistogram-extends-histogram" class="type"><IntervalHistogram></a> instances can be cloned via <a href="#all_worker_threads_class-messageport" class="type"><MessagePort></a>. On the receiving
end, the histogram is cloned as a plain <a href="#all_perf_hooks_class-histogram" class="type"><Histogram></a> object that does not
implement the <code>enable()</code> and <code>disable()</code> methods.</p>
</section><section><h3>Class: <code>RecordableHistogram extends Histogram</code><span><a class="mark" href="#all_perf_hooks_class-recordablehistogram-extends-histogram" id="all_perf_hooks_class-recordablehistogram-extends-histogram">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_recordablehistogram_extends_histogram"></a></h3>
<div class="api_metadata">
<span>Added in: v15.9.0, v14.18.0</span>
</div>
<h4><code>histogram.add(other)</code><span><a class="mark" href="#all_perf_hooks_histogramaddother" id="all_perf_hooks_histogramaddother">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_add_other"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.0</span>
</div>
<ul>
<li><code>other</code> <a href="#all_perf_hooks_class-recordablehistogram-extends-histogram" class="type"><RecordableHistogram></a></li>
</ul>
<p>Adds the values from <code>other</code> to this histogram.</p>
<h4><code>histogram.record(val)</code><span><a class="mark" href="#all_perf_hooks_histogramrecordval" id="all_perf_hooks_histogramrecordval">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_record_val"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0, v14.18.0</span>
</div>
<ul>
<li><code>val</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> The amount to record in the histogram.</li>
</ul>
<h4><code>histogram.recordDelta()</code><span><a class="mark" href="#all_perf_hooks_histogramrecorddelta" id="all_perf_hooks_histogramrecorddelta">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_recorddelta"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0, v14.18.0</span>
</div>
<p>Calculates the amount of time (in nanoseconds) that has passed since the
previous call to <code>recordDelta()</code> and records that amount in the histogram.</p>
</section><section><h3>Examples<span><a class="mark" href="#all_perf_hooks_examples" id="all_perf_hooks_examples">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_examples"></a></h3>
<h4>Measuring the duration of async operations<span><a class="mark" href="#all_perf_hooks_measuring-the-duration-of-async-operations" id="all_perf_hooks_measuring-the-duration-of-async-operations">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_measuring_the_duration_of_async_operations"></a></h4>
<p>The following example uses the <a href="async_hooks.html">Async Hooks</a> and Performance APIs to measure
the actual duration of a Timeout operation (including the amount of time it took
to execute the callback).</p>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> {
performance,
<span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> set = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>();
<span class="hljs-keyword">const</span> hook = async_hooks.<span class="hljs-title function_">createHook</span>({
<span class="hljs-title function_">init</span>(<span class="hljs-params">id, type</span>) {
<span class="hljs-keyword">if</span> (type === <span class="hljs-string">'Timeout'</span>) {
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">`Timeout-<span class="hljs-subst">${id}</span>-Init`</span>);
set.<span class="hljs-title function_">add</span>(id);
}
},
<span class="hljs-title function_">destroy</span>(<span class="hljs-params">id</span>) {
<span class="hljs-keyword">if</span> (set.<span class="hljs-title function_">has</span>(id)) {
set.<span class="hljs-title function_">delete</span>(id);
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">`Timeout-<span class="hljs-subst">${id}</span>-Destroy`</span>);
performance.<span class="hljs-title function_">measure</span>(<span class="hljs-string">`Timeout-<span class="hljs-subst">${id}</span>`</span>,
<span class="hljs-string">`Timeout-<span class="hljs-subst">${id}</span>-Init`</span>,
<span class="hljs-string">`Timeout-<span class="hljs-subst">${id}</span>-Destroy`</span>);
}
},
});
hook.<span class="hljs-title function_">enable</span>();
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">list, observer</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(list.<span class="hljs-title function_">getEntries</span>()[<span class="hljs-number">0</span>]);
performance.<span class="hljs-title function_">clearMarks</span>();
performance.<span class="hljs-title function_">clearMeasures</span>();
observer.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'measure'</span>], <span class="hljs-attr">buffered</span>: <span class="hljs-literal">true</span> });
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">1000</span>);</code> <button class="copy-button">copy</button></pre>
<h4>Measuring how long it takes to load dependencies<span><a class="mark" href="#all_perf_hooks_measuring-how-long-it-takes-to-load-dependencies" id="all_perf_hooks_measuring-how-long-it-takes-to-load-dependencies">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_measuring_how_long_it_takes_to_load_dependencies"></a></h4>
<p>The following example measures the duration of <code>require()</code> operations to load
dependencies:</p>
<!-- eslint-disable no-global-assign -->
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> {
performance,
<span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> mod = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-comment">// Monkey patch the require function</span>
mod.<span class="hljs-property">Module</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">require</span> =
performance.<span class="hljs-title function_">timerify</span>(mod.<span class="hljs-property">Module</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">require</span>);
<span class="hljs-built_in">require</span> = performance.<span class="hljs-title function_">timerify</span>(<span class="hljs-built_in">require</span>);
<span class="hljs-comment">// Activate the observer</span>
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">list</span>) =></span> {
<span class="hljs-keyword">const</span> entries = list.<span class="hljs-title function_">getEntries</span>();
entries.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">entry</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`require('<span class="hljs-subst">${entry[<span class="hljs-number">0</span>]}</span>')`</span>, entry.<span class="hljs-property">duration</span>);
});
performance.<span class="hljs-title function_">clearMarks</span>();
performance.<span class="hljs-title function_">clearMeasures</span>();
obs.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'function'</span>], <span class="hljs-attr">buffered</span>: <span class="hljs-literal">true</span> });
<span class="hljs-built_in">require</span>(<span class="hljs-string">'some-module'</span>);</code> <button class="copy-button">copy</button></pre>
<h4>Measuring how long one HTTP round-trip takes<span><a class="mark" href="#all_perf_hooks_measuring-how-long-one-http-round-trip-takes" id="all_perf_hooks_measuring-how-long-one-http-round-trip-takes">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_measuring_how_long_one_http_round_trip_takes"></a></h4>
<p>The following example is used to trace the time spent by HTTP client
(<code>OutgoingMessage</code>) and HTTP request (<code>IncomingMessage</code>). For HTTP client,
it means the time interval between starting the request and receiving the
response, and for HTTP request, it means the time interval between receiving
the request and sending the response:</p>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">PerformanceObserver</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</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> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> {
items.<span class="hljs-title function_">getEntries</span>().<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">item</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(item);
});
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'http'</span>] });
<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">PORT</span> = <span class="hljs-number">8080</span>;
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-variable constant_">PORT</span>, <span class="hljs-function">() =></span> {
http.<span class="hljs-title function_">get</span>(<span class="hljs-string">`http://127.0.0.1:<span class="hljs-subst">${PORT}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Measuring how long the <code>net.connect</code> (only for TCP) takes when the connection is successful<span><a class="mark" href="#all_perf_hooks_measuring-how-long-the-netconnect-only-for-tcp-takes-when-the-connection-is-successful" id="all_perf_hooks_measuring-how-long-the-netconnect-only-for-tcp-takes-when-the-connection-is-successful">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_measuring_how_long_the_net_connect_only_for_tcp_takes_when_the_connection_is_successful"></a></h4>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">PerformanceObserver</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> {
items.<span class="hljs-title function_">getEntries</span>().<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">item</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(item);
});
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'net'</span>] });
<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">PORT</span> = <span class="hljs-number">8080</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_">destroy</span>();
}).<span class="hljs-title function_">listen</span>(<span class="hljs-variable constant_">PORT</span>, <span class="hljs-function">() =></span> {
net.<span class="hljs-title function_">connect</span>(<span class="hljs-variable constant_">PORT</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Measuring how long the DNS takes when the request is successful<span><a class="mark" href="#all_perf_hooks_measuring-how-long-the-dns-takes-when-the-request-is-successful" id="all_perf_hooks_measuring-how-long-the-dns-takes-when-the-request-is-successful">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_measuring_how_long_the_dns_takes_when_the_request_is_successful"></a></h4>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">PerformanceObserver</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> {
items.<span class="hljs-title function_">getEntries</span>().<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">item</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(item);
});
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'dns'</span>] });
dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'localhost'</span>, <span class="hljs-function">() =></span> {});
dns.<span class="hljs-property">promises</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'localhost'</span>);</code> <button class="copy-button">copy</button></pre></section>
</section>
<section><h2>Permissions<span><a class="mark" href="#all_permissions_permissions" id="all_permissions_permissions">#</a></span><a aria-hidden="true" class="legacy" id="permissions_permissions"></a></h2>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/src/permission.cc">src/permission.cc</a></p>
<p>Permissions can be used to control what system resources the
Node.js process has access to or what actions the process can take
with those resources. Permissions can also control what modules can
be accessed by other modules.</p>
<ul>
<li>
<p><a href="#all_permissions_module-based-permissions">Module-based permissions</a> control which files
or URLs are available to other modules during application execution.
This can be used to control what modules can be accessed by third-party
dependencies, for example.</p>
</li>
<li>
<p><a href="#all_permissions_process-based-permissions">Process-based permissions</a> control the Node.js
process's access to resources.
The resource can be entirely allowed or denied, or actions related to it can
be controlled. For example, file system reads can be allowed while denying
writes.
This feature does not protect against malicious code. According to the Node.js
<a href="https://github.com/nodejs/node/blob/main/SECURITY.md">Security Policy</a>, Node.js trusts any code it is asked to run.</p>
</li>
</ul>
<p>The permission model implements a "seat belt" approach, which prevents trusted
code from unintentionally changing files or using resources that access has
not explicitly been granted to. It does not provide security guarantees in the
presence of malicious code. Malicious code can bypass the permission model and
execute arbitrary code without the restrictions imposed by the permission
model.</p>
<p>If you find a potential security vulnerability, please refer to our
<a href="https://github.com/nodejs/node/blob/main/SECURITY.md">Security Policy</a>.</p>
<section><h3>Module-based permissions<span><a class="mark" href="#all_permissions_module-based-permissions" id="all_permissions_module-based-permissions">#</a></span><a aria-hidden="true" class="legacy" id="permissions_module_based_permissions"></a></h3>
<h4>Policies<span><a class="mark" href="#all_permissions_policies" id="all_permissions_policies">#</a></span><a aria-hidden="true" class="legacy" id="permissions_policies"></a></h4>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Will be removed shortly</div><p></p>
<p>Node.js contains experimental support for creating policies on loading code.</p>
<p>Policies are a security feature intended to ensure the integrity
of the loaded code.</p>
<p>While it does not function as a provenance mechanism to trace the origin of
code, it serves as a robust defense against the execution of malicious code.
Unlike runtime-based models that may restrict capabilities once the code is
loaded, Node.js policies focus on preventing malicious code from ever being
fully loaded into the application in the first place.</p>
<p>The use of policies assumes safe practices for the policy
files such as ensuring that policy files cannot be overwritten by the Node.js
application by using file permissions.</p>
<p>A best practice would be to ensure that the policy manifest is read-only for
the running Node.js application and that the file cannot be changed
by the running Node.js application in any way. A typical setup would be to
create the policy file as a different user id than the one running Node.js
and granting read permissions to the user id running Node.js.</p>
<h5>Enabling<span><a class="mark" href="#all_permissions_enabling" id="all_permissions_enabling">#</a></span><a aria-hidden="true" class="legacy" id="permissions_enabling"></a></h5>
<p>The <code>--experimental-policy</code> flag can be used to enable features for policies
when loading modules.</p>
<p>Once this has been set, all modules must conform to a policy manifest file
passed to the flag:</p>
<pre><code class="language-bash">node --experimental-policy=policy.json app.js</code> <button class="copy-button">copy</button></pre>
<p>The policy manifest will be used to enforce constraints on code loaded by
Node.js.</p>
<p>To mitigate tampering with policy files on disk, an integrity for
the policy file itself may be provided via <code>--policy-integrity</code>.
This allows running <code>node</code> and asserting the policy file contents
even if the file is changed on disk.</p>
<pre><code class="language-bash">node --experimental-policy=policy.json --policy-integrity=<span class="hljs-string">"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"</span> app.js</code> <button class="copy-button">copy</button></pre>
<h5>Features<span><a class="mark" href="#all_permissions_features" id="all_permissions_features">#</a></span><a aria-hidden="true" class="legacy" id="permissions_features"></a></h5>
<h6>Error behavior<span><a class="mark" href="#all_permissions_error-behavior" id="all_permissions_error-behavior">#</a></span><a aria-hidden="true" class="legacy" id="permissions_error_behavior"></a></h6>
<p>When a policy check fails, Node.js by default will throw an error.
It is possible to change the error behavior to one of a few possibilities
by defining an "onerror" field in a policy manifest. The following values are
available to change the behavior:</p>
<ul>
<li><code>"exit"</code>: will exit the process immediately.
No cleanup code will be allowed to run.</li>
<li><code>"log"</code>: will log the error at the site of the failure.</li>
<li><code>"throw"</code>: will throw a JS error at the site of the failure. This is the
default.</li>
</ul>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"onerror"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"log"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"resources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"./app/checked.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"integrity"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h6>Integrity checks<span><a class="mark" href="#all_permissions_integrity-checks" id="all_permissions_integrity-checks">#</a></span><a aria-hidden="true" class="legacy" id="permissions_integrity_checks"></a></h6>
<p>Policy files must use integrity checks with Subresource Integrity strings
compatible with the browser
<a href="https://www.w3.org/TR/SRI/#the-integrity-attribute">integrity attribute</a>
associated with absolute URLs.</p>
<p>When using <code>require()</code> or <code>import</code> all resources involved in loading are checked
for integrity if a policy manifest has been specified. If a resource does not
match the integrity listed in the manifest, an error will be thrown.</p>
<p>An example policy file that would allow loading a file <code>checked.js</code>:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"resources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"./app/checked.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"integrity"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Each resource listed in the policy manifest can be of one the following
formats to determine its location:</p>
<ol>
<li>A <a href="https://url.spec.whatwg.org/#relative-url-with-fragment-string">relative-URL string</a> to a resource from the manifest such as <code>./resource.js</code>, <code>../resource.js</code>, or <code>/resource.js</code>.</li>
<li>A complete URL string to a resource such as <code>file:///resource.js</code>.</li>
</ol>
<p>When loading resources the entire URL must match including search parameters
and hash fragment. <code>./a.js?b</code> will not be used when attempting to load
<code>./a.js</code> and vice versa.</p>
<p>To generate integrity strings, a script such as
<code>node -e 'process.stdout.write("sha256-");process.stdin.pipe(crypto.createHash("sha256").setEncoding("base64")).pipe(process.stdout)' < FILE</code>
can be used.</p>
<p>Integrity can be specified as the boolean value <code>true</code> to accept any
body for the resource which can be useful for local development. It is not
recommended in production since it would allow unexpected alteration of
resources to be considered valid.</p>
<h6>Dependency redirection<span><a class="mark" href="#all_permissions_dependency-redirection" id="all_permissions_dependency-redirection">#</a></span><a aria-hidden="true" class="legacy" id="permissions_dependency_redirection"></a></h6>
<p>An application may need to ship patched versions of modules or to prevent
modules from allowing all modules access to all other modules. Redirection
can be used by intercepting attempts to load the modules wishing to be
replaced.</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"resources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"./app/checked.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"fs"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"os"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./app/node_modules/alt-os"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"http"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span> <span class="hljs-attr">"import"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span> <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The dependencies are keyed by the requested specifier string and have values
of either <code>true</code>, <code>null</code>, a string pointing to a module to be resolved,
or a conditions object.</p>
<p>The specifier string does not perform any searching and must match exactly what
is provided to the <code>require()</code> or <code>import</code> except for a canonicalization step.
Therefore, multiple specifiers may be needed in the policy if it uses multiple
different strings to point to the same module (such as excluding the extension).</p>
<p>Specifier strings are canonicalized but not resolved prior to be used for
matching in order to have some compatibility with import maps, for example if a
resource <code>file:///C:/app/utils.js</code> was given the following redirection from a
policy located at <code>file:///C:/app/policy.json</code>:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"resources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"file:///C:/app/utils.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"./utils.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./utils-v2.js"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Any specifier used to load <code>file:///C:/app/utils.js</code> would then be intercepted
and redirected to <code>file:///C:/app/utils-v2.js</code> instead regardless of using an
absolute or relative specifier. However, if a specifier that is not an absolute
or relative URL string is used, it would not be intercepted. So, if an import
such as <code>import('#utils')</code> was used, it would not be intercepted.</p>
<p>If the value of the redirection is <code>true</code>, a "dependencies" field at the top of
the policy file will be used. If that field at the top of the policy file is
<code>true</code> the default node searching algorithms are used to find the module.</p>
<p>If the value of the redirection is a string, it is resolved relative to
the manifest and then immediately used without searching.</p>
<p>Any specifier string for which resolution is attempted and that is not listed in
the dependencies results in an error according to the policy.</p>
<p>A boolean value of <code>true</code> for the dependencies map can be specified to allow a
module to load any specifier without redirection. This can be useful for local
development and may have some valid usage in production, but should be used
only with care after auditing a module to ensure its behavior is valid.</p>
<p>Similar to <code>"exports"</code> in <code>package.json</code>, dependencies can also be specified to
be objects containing conditions which branch how dependencies are loaded. In
the preceding example, <code>"http"</code> is allowed when the <code>"import"</code> condition is
part of loading it.</p>
<p>A value of <code>null</code> for the resolved value causes the resolution to fail. This
can be used to ensure some kinds of dynamic access are explicitly prevented.</p>
<p>Unknown values for the resolved module location cause failures but are
not guaranteed to be forward compatible.</p>
<p>All the guarantees for policy redirection are specified in the
<a href="#all_permissions_guarantees">Guarantees</a> section.</p>
<h6>Example: Patched dependency<span><a class="mark" href="#all_permissions_example-patched-dependency" id="all_permissions_example-patched-dependency">#</a></span><a aria-hidden="true" class="legacy" id="permissions_example_patched_dependency"></a></h6>
<p>Redirected dependencies can provide attenuated or modified functionality as fits
the application. For example, log data about timing of function durations by
wrapping the original:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> original = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fn'</span>);
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">fn</span>(<span class="hljs-params">...args</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">time</span>();
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span>.<span class="hljs-property">target</span> ?
<span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">construct</span>(original, args) :
<span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">apply</span>(original, <span class="hljs-variable language_">this</span>, args);
} <span class="hljs-keyword">finally</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">timeEnd</span>();
}
};</code> <button class="copy-button">copy</button></pre>
<h5>Scopes<span><a class="mark" href="#all_permissions_scopes" id="all_permissions_scopes">#</a></span><a aria-hidden="true" class="legacy" id="permissions_scopes"></a></h5>
<p>Use the <code>"scopes"</code> field of a manifest to set configuration for many resources
at once. The <code>"scopes"</code> field works by matching resources by their segments.
If a scope or resource includes <code>"cascade": true</code>, unknown specifiers will
be searched for in their containing scope. The containing scope for cascading
is found by recursively reducing the resource URL by removing segments for
<a href="https://url.spec.whatwg.org/#special-scheme">special schemes</a>, keeping trailing <code>"/"</code> suffixes, and removing the query and
hash fragment. This leads to the eventual reduction of the URL to its origin.
If the URL is non-special the scope will be located by the URL's origin. If no
scope is found for the origin or in the case of opaque origins, a protocol
string can be used as a scope. If no scope is found for the URL's protocol, a
final empty string <code>""</code> scope will be used.</p>
<p>Note, <code>blob:</code> URLs adopt their origin from the path they contain, and so a scope
of <code>"blob:https://nodejs.org"</code> will have no effect since no URL can have an
origin of <code>blob:https://nodejs.org</code>; URLs starting with
<code>blob:https://nodejs.org/</code> will use <code>https://nodejs.org</code> for its origin and
thus <code>https:</code> for its protocol scope. For opaque origin <code>blob:</code> URLs they will
have <code>blob:</code> for their protocol scope since they do not adopt origins.</p>
<h6>Example<span><a class="mark" href="#all_permissions_example" id="all_permissions_example">#</a></span><a aria-hidden="true" class="legacy" id="permissions_example"></a></h6>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"scopes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"file:///C:/app/"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span><span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"file:"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span><span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">""</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span><span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Given a file located at <code>file:///C:/app/bin/main.js</code>, the following scopes would
be checked in order:</p>
<ol>
<li><code>"file:///C:/app/bin/"</code></li>
</ol>
<p>This determines the policy for all file based resources within
<code>"file:///C:/app/bin/"</code>. This is not in the <code>"scopes"</code> field of the policy and
would be skipped. Adding this scope to the policy would cause it to be used
prior to the <code>"file:///C:/app/"</code> scope.</p>
<ol start="2">
<li><code>"file:///C:/app/"</code></li>
</ol>
<p>This determines the policy for all file based resources within
<code>"file:///C:/app/"</code>. This is in the <code>"scopes"</code> field of the policy and it would
determine the policy for the resource at <code>file:///C:/app/bin/main.js</code>. If the
scope has <code>"cascade": true</code>, any unsatisfied queries about the resource would
delegate to the next relevant scope for <code>file:///C:/app/bin/main.js</code>, <code>"file:"</code>.</p>
<ol start="3">
<li><code>"file:///C:/"</code></li>
</ol>
<p>This determines the policy for all file based resources within <code>"file:///C:/"</code>.
This is not in the <code>"scopes"</code> field of the policy and would be skipped. It would
not be used for <code>file:///C:/app/bin/main.js</code> unless <code>"file:///C:/app/"</code> is set
to cascade or is not in the <code>"scopes"</code> of the policy.</p>
<ol start="4">
<li><code>"file:///"</code></li>
</ol>
<p>This determines the policy for all file based resources on the <code>localhost</code>. This
is not in the <code>"scopes"</code> field of the policy and would be skipped. It would not
be used for <code>file:///C:/app/bin/main.js</code> unless <code>"file:///C:/"</code> is set to
cascade or is not in the <code>"scopes"</code> of the policy.</p>
<ol start="5">
<li><code>"file:"</code></li>
</ol>
<p>This determines the policy for all file based resources. It would not be used
for <code>file:///C:/app/bin/main.js</code> unless <code>"file:///"</code> is set to cascade or is not
in the <code>"scopes"</code> of the policy.</p>
<ol start="6">
<li><code>""</code></li>
</ol>
<p>This determines the policy for all resources. It would not be used for
<code>file:///C:/app/bin/main.js</code> unless <code>"file:"</code> is set to cascade.</p>
<h6>Integrity using scopes<span><a class="mark" href="#all_permissions_integrity-using-scopes" id="all_permissions_integrity-using-scopes">#</a></span><a aria-hidden="true" class="legacy" id="permissions_integrity_using_scopes"></a></h6>
<p>Setting an integrity to <code>true</code> on a scope will set the integrity for any
resource not found in the manifest to <code>true</code>.</p>
<p>Setting an integrity to <code>null</code> on a scope will set the integrity for any
resource not found in the manifest to fail matching.</p>
<p>Not including an integrity is the same as setting the integrity to <code>null</code>.</p>
<p><code>"cascade"</code> for integrity checks will be ignored if <code>"integrity"</code> is explicitly
set.</p>
<p>The following example allows loading any file:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"scopes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"file:"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"integrity"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h6>Dependency redirection using scopes<span><a class="mark" href="#all_permissions_dependency-redirection-using-scopes" id="all_permissions_dependency-redirection-using-scopes">#</a></span><a aria-hidden="true" class="legacy" id="permissions_dependency_redirection_using_scopes"></a></h6>
<p>The following example, would allow access to <code>fs</code> for all resources within
<code>./app/</code>:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"resources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"./app/checked.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"cascade"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"integrity"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"scopes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"./app/"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"fs"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The following example, would allow access to <code>fs</code> for all <code>data:</code> resources:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"resources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"data:text/javascript,import('node:fs');"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"cascade"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"integrity"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"scopes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"data:"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"fs"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h6>Example: import maps emulation<span><a class="mark" href="#all_permissions_example-import-maps-emulation" id="all_permissions_example-import-maps-emulation">#</a></span><a aria-hidden="true" class="legacy" id="permissions_example_import_maps_emulation"></a></h6>
<p>Given an import map:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"react"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./app/node_modules/react/index.js"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"scopes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"./ssr/"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"react"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./app/node_modules/server-side-react/index.js"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"scopes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">""</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"cascade"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"react"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./app/node_modules/react/index.js"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"./ssr/"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"cascade"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"react"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./app/node_modules/server-side-react/index.js"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p><a href="https://url.spec.whatwg.org/#relative-url-with-fragment-string">Import maps</a> assume you can get any resource by default. This means
<code>"dependencies"</code> at the top level of the policy should be set to <code>true</code>.
Policies require this to be opt-in since it enables all resources of the
application cross linkage which doesn't make sense for many scenarios. They also
assume any given scope has access to any scope above its allowed dependencies;
all scopes emulating import maps must set <code>"cascade": true</code>.</p>
<p>Import maps only have a single top level scope for their "imports". So for
emulating <code>"imports"</code> use the <code>""</code> scope. For emulating <code>"scopes"</code> use the
<code>"scopes"</code> in a similar manner to how <code>"scopes"</code> works in import maps.</p>
<p>Caveats: Policies do not use string matching for various finding of scope. They
do URL traversals. This means things like <code>blob:</code> and <code>data:</code> URLs might not be
entirely interoperable between the two systems. For example import maps can
partially match a <code>data:</code> or <code>blob:</code> URL by partitioning the URL on a <code>/</code>
character, policies intentionally cannot. For <code>blob:</code> URLs import map scopes do
not adopt the origin of the <code>blob:</code> URL.</p>
<p>Additionally, import maps only work on <code>import</code> so it may be desirable to add a
<code>"import"</code> condition to all dependency mappings.</p>
<h5>Guarantees<span><a class="mark" href="#all_permissions_guarantees" id="all_permissions_guarantees">#</a></span><a aria-hidden="true" class="legacy" id="permissions_guarantees"></a></h5>
<ul>
<li>The policies guarantee the file integrity when a module is loaded using
<code>require()</code>, <code>import()</code> or <code>new Module()</code>.</li>
<li>Redirection does not prevent access to APIs through means such as direct
access to <code>require.cache</code> which allow access to loaded modules.
Policy redirection only affects specifiers to <code>require()</code> and
<code>import</code>.</li>
<li>The approval of the module integrity in policies threat model implies
they are allowed to muck with and even circumvent security features once
loaded so environmental/runtime hardening is expected.</li>
</ul>
</section><section><h3>Process-based permissions<span><a class="mark" href="#all_permissions_process-based-permissions" id="all_permissions_process-based-permissions">#</a></span><a aria-hidden="true" class="legacy" id="permissions_process_based_permissions"></a></h3>
<h4>Permission Model<span><a class="mark" href="#all_permissions_permission-model" id="all_permissions_permission-model">#</a></span><a aria-hidden="true" class="legacy" id="permissions_permission_model"></a></h4>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>The Node.js Permission Model is a mechanism for restricting access to specific
resources during execution.
The API exists behind a flag <a href="#all_cli_--experimental-permission"><code>--experimental-permission</code></a> which when enabled,
will restrict access to all available permissions.</p>
<p>The available permissions are documented by the <a href="#all_cli_--experimental-permission"><code>--experimental-permission</code></a>
flag.</p>
<p>When starting Node.js with <code>--experimental-permission</code>,
the ability to access the file system through the <code>fs</code> module, spawn processes,
use <code>node:worker_threads</code>, use native addons, use WASI, and enable the runtime inspector
will be restricted.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission index.js</span>
node:internal/modules/cjs/loader:171
const result = internalModuleStat(filename);
^
Error: Access to this API has been restricted
at stat (node:internal/modules/cjs/loader:171:18)
at Module._findPath (node:internal/modules/cjs/loader:627:16)
at resolveMainPath (node:internal/modules/run_main:19:25)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:24)
at node:internal/main/run_main_module:23:47 {
code: 'ERR_ACCESS_DENIED',
permission: 'FileSystemRead',
resource: '/home/user/index.js'
}</code> <button class="copy-button">copy</button></pre>
<p>Allowing access to spawning a process and creating worker threads can be done
using the <a href="#all_cli_--allow-child-process"><code>--allow-child-process</code></a> and <a href="#all_cli_--allow-worker"><code>--allow-worker</code></a> respectively.</p>
<p>To allow native addons when using permission model, use the <a href="#all_cli_--allow-addons"><code>--allow-addons</code></a>
flag. For WASI, use the <a href="#all_cli_--allow-wasi"><code>--allow-wasi</code></a> flag.</p>
<h5>Runtime API<span><a class="mark" href="#all_permissions_runtime-api" id="all_permissions_runtime-api">#</a></span><a aria-hidden="true" class="legacy" id="permissions_runtime_api"></a></h5>
<p>When enabling the Permission Model through the <a href="#all_cli_--experimental-permission"><code>--experimental-permission</code></a>
flag a new property <code>permission</code> is added to the <code>process</code> object.
This property contains one function:</p>
<h6><code>permission.has(scope[, reference])</code><span><a class="mark" href="#all_permissions_permissionhasscope-reference" id="all_permissions_permissionhasscope-reference">#</a></span><a aria-hidden="true" class="legacy" id="permissions_permission_has_scope_reference"></a></h6>
<p>API call to check permissions at runtime (<a href="#all_process_processpermissionhasscope-reference"><code>permission.has()</code></a>)</p>
<pre><code class="language-js">process.<span class="hljs-property">permission</span>.<span class="hljs-title function_">has</span>(<span class="hljs-string">'fs.write'</span>); <span class="hljs-comment">// true</span>
process.<span class="hljs-property">permission</span>.<span class="hljs-title function_">has</span>(<span class="hljs-string">'fs.write'</span>, <span class="hljs-string">'/home/rafaelgss/protected-folder'</span>); <span class="hljs-comment">// true</span>
process.<span class="hljs-property">permission</span>.<span class="hljs-title function_">has</span>(<span class="hljs-string">'fs.read'</span>); <span class="hljs-comment">// true</span>
process.<span class="hljs-property">permission</span>.<span class="hljs-title function_">has</span>(<span class="hljs-string">'fs.read'</span>, <span class="hljs-string">'/home/rafaelgss/protected-folder'</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<h5>File System Permissions<span><a class="mark" href="#all_permissions_file-system-permissions" id="all_permissions_file-system-permissions">#</a></span><a aria-hidden="true" class="legacy" id="permissions_file_system_permissions"></a></h5>
<p>The Permission Model, by default, restricts access to the file system through the <code>node:fs</code> module.
It does not guarantee that users will not be able to access the file system through other means,
such as through the <code>node:sqlite</code> module.</p>
<p>To allow access to the file system, use the <a href="#all_cli_--allow-fs-read"><code>--allow-fs-read</code></a> and
<a href="#all_cli_--allow-fs-write"><code>--allow-fs-write</code></a> flags:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission --allow-fs-read=* --allow-fs-write=* index.js</span>
Hello world!
(node:19836) ExperimentalWarning: Permission is an experimental feature
(Use `node --trace-warnings ...` to show where the warning was created)</code> <button class="copy-button">copy</button></pre>
<p>The valid arguments for both flags are:</p>
<ul>
<li><code>*</code> - To allow all <code>FileSystemRead</code> or <code>FileSystemWrite</code> operations,
respectively.</li>
<li>Paths delimited by comma (<code>,</code>) to allow only matching <code>FileSystemRead</code> or
<code>FileSystemWrite</code> operations, respectively.</li>
</ul>
<p>Example:</p>
<ul>
<li><code>--allow-fs-read=*</code> - It will allow all <code>FileSystemRead</code> operations.</li>
<li><code>--allow-fs-write=*</code> - It will allow all <code>FileSystemWrite</code> operations.</li>
<li><code>--allow-fs-write=/tmp/</code> - It will allow <code>FileSystemWrite</code> access to the <code>/tmp/</code>
folder.</li>
<li><code>--allow-fs-read=/tmp/ --allow-fs-read=/home/.gitignore</code> - It allows <code>FileSystemRead</code> access
to the <code>/tmp/</code> folder <strong>and</strong> the <code>/home/.gitignore</code> path.</li>
</ul>
<p>Wildcards are supported too:</p>
<ul>
<li><code>--allow-fs-read=/home/test*</code> will allow read access to everything
that matches the wildcard. e.g: <code>/home/test/file1</code> or <code>/home/test2</code></li>
</ul>
<p>After passing a wildcard character (<code>*</code>) all subsequent characters will
be ignored. For example: <code>/home/*.js</code> will work similar to <code>/home/*</code>.</p>
<p>When the permission model is initialized, it will automatically add a wildcard
(*) if the specified directory exists. For example, if <code>/home/test/files</code>
exists, it will be treated as <code>/home/test/files/*</code>. However, if the directory
does not exist, the wildcard will not be added, and access will be limited to
<code>/home/test/files</code>. If you want to allow access to a folder that does not exist
yet, make sure to explicitly include the wildcard:
<code>/my-path/folder-do-not-exist/*</code>.</p>
<h5>Permission Model constraints<span><a class="mark" href="#all_permissions_permission-model-constraints" id="all_permissions_permission-model-constraints">#</a></span><a aria-hidden="true" class="legacy" id="permissions_permission_model_constraints"></a></h5>
<p>There are constraints you need to know before using this system:</p>
<ul>
<li>The model does not inherit to a child node process or a worker thread.</li>
<li>When using the Permission Model the following features will be restricted:
<ul>
<li>Native modules</li>
<li>Child process</li>
<li>Worker Threads</li>
<li>Inspector protocol</li>
<li>File system access</li>
<li>WASI</li>
</ul>
</li>
<li>The Permission Model is initialized after the Node.js environment is set up.
However, certain flags such as <code>--env-file</code> or <code>--openssl-config</code> are designed
to read files before environment initialization. As a result, such flags are
not subject to the rules of the Permission Model. The same applies for V8
flags that can be set via runtime through <code>v8.setFlagsFromString</code>.</li>
<li>OpenSSL engines cannot be requested at runtime when the Permission
Model is enabled, affecting the built-in crypto, https, and tls modules.</li>
<li>Using existing file descriptors via the <code>node:fs</code> module bypasses the
Permission Model.</li>
</ul>
<h5>Limitations and Known Issues<span><a class="mark" href="#all_permissions_limitations-and-known-issues" id="all_permissions_limitations-and-known-issues">#</a></span><a aria-hidden="true" class="legacy" id="permissions_limitations_and_known_issues"></a></h5>
<ul>
<li>Symbolic links will be followed even to locations outside of the set of paths
that access has been granted to. Relative symbolic links may allow access to
arbitrary files and directories. When starting applications with the
permission model enabled, you must ensure that no paths to which access has
been granted contain relative symbolic links.</li>
</ul></section>
</section>
<section><h2>Process<span><a class="mark" href="#all_process_process" id="all_process_process">#</a></span><a aria-hidden="true" class="legacy" id="process_process"></a></h2>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/process.js">lib/process.js</a></p>
<p>The <code>process</code> object provides information about, and control over, the current
Node.js process.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>Process events<span><a class="mark" href="#all_process_process-events" id="all_process_process-events">#</a></span><a aria-hidden="true" class="legacy" id="process_process_events"></a></h3>
<p>The <code>process</code> object is an instance of <a href="#all_events_class-eventemitter"><code>EventEmitter</code></a>.</p>
<h4>Event: <code>'beforeExit'</code><span><a class="mark" href="#all_process_event-beforeexit" id="all_process_event-beforeexit">#</a></span><a aria-hidden="true" class="legacy" id="process_event_beforeexit"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div>
<p>The <code>'beforeExit'</code> event is emitted when Node.js empties its event loop and has
no additional work to schedule. Normally, the Node.js process will exit when
there is no work scheduled, but a listener registered on the <code>'beforeExit'</code>
event can make asynchronous calls, and thereby cause the Node.js process to
continue.</p>
<p>The listener callback function is invoked with the value of
<a href="#all_process_processexitcode_1"><code>process.exitCode</code></a> passed as the only argument.</p>
<p>The <code>'beforeExit'</code> event is <em>not</em> emitted for conditions causing explicit
termination, such as calling <a href="#all_process_processexitcode"><code>process.exit()</code></a> or uncaught exceptions.</p>
<p>The <code>'beforeExit'</code> should <em>not</em> be used as an alternative to the <code>'exit'</code> event
unless the intention is to schedule additional work.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'beforeExit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Process beforeExit event with code: '</span>, code);
});
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Process exit event with code: '</span>, code);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This message is displayed first.'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// This message is displayed first.</span>
<span class="hljs-comment">// Process beforeExit event with code: 0</span>
<span class="hljs-comment">// Process exit event with code: 0</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'beforeExit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Process beforeExit event with code: '</span>, code);
});
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Process exit event with code: '</span>, code);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This message is displayed first.'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// This message is displayed first.</span>
<span class="hljs-comment">// Process beforeExit event with code: 0</span>
<span class="hljs-comment">// Process exit event with code: 0</span></code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'disconnect'</code><span><a class="mark" href="#all_process_event-disconnect" id="all_process_event-disconnect">#</a></span><a aria-hidden="true" class="legacy" id="process_event_disconnect"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<p>If the Node.js process is spawned with an IPC channel (see the <a href="child_process.html">Child Process</a>
and <a href="cluster.html">Cluster</a> documentation), the <code>'disconnect'</code> event will be emitted when
the IPC channel is closed.</p>
<h4>Event: <code>'exit'</code><span><a class="mark" href="#all_process_event-exit" id="all_process_event-exit">#</a></span><a aria-hidden="true" class="legacy" id="process_event_exit"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.7</span>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>The <code>'exit'</code> event is emitted when the Node.js process is about to exit as a
result of either:</p>
<ul>
<li>The <code>process.exit()</code> method being called explicitly;</li>
<li>The Node.js event loop no longer having any additional work to perform.</li>
</ul>
<p>There is no way to prevent the exiting of the event loop at this point, and once
all <code>'exit'</code> listeners have finished running the Node.js process will terminate.</p>
<p>The listener callback function is invoked with the exit code specified either
by the <a href="#all_process_processexitcode_1"><code>process.exitCode</code></a> property, or the <code>exitCode</code> argument passed to the
<a href="#all_process_processexitcode"><code>process.exit()</code></a> method.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`About to exit with code: <span class="hljs-subst">${code}</span>`</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`About to exit with code: <span class="hljs-subst">${code}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Listener functions <strong>must</strong> only perform <strong>synchronous</strong> operations. The Node.js
process will exit immediately after calling the <code>'exit'</code> event listeners
causing any additional work still queued in the event loop to be abandoned.
In the following example, for instance, the timeout will never occur:</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></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">'This will not run'</span>);
}, <span class="hljs-number">0</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></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">'This will not run'</span>);
}, <span class="hljs-number">0</span>);
});</code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'message'</code><span><a class="mark" href="#all_process_event-message" id="all_process_event-message">#</a></span><a aria-hidden="true" class="legacy" id="process_event_message"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.10</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <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#Number_type" class="type"><number></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 parsed JSON object
or a serializable primitive value.</li>
<li><code>sendHandle</code> <a href="#all_net_class-netserver" class="type"><net.Server></a> | <a href="#all_net_class-netsocket" class="type"><net.Socket></a> a <a href="#all_net_class-netserver"><code>net.Server</code></a> or <a href="#all_net_class-netsocket"><code>net.Socket</code></a>
object, or undefined.</li>
</ul>
<p>If the Node.js process is spawned with an IPC channel (see the <a href="child_process.html">Child Process</a>
and <a href="cluster.html">Cluster</a> documentation), the <code>'message'</code> event is emitted whenever a
message sent by a parent process using <a href="#all_child_process_subprocesssendmessage-sendhandle-options-callback"><code>childprocess.send()</code></a> is received by
the child process.</p>
<p>The message goes through serialization and parsing. The resulting message might
not be the same as what is originally sent.</p>
<p>If the <code>serialization</code> option was set to <code>advanced</code> used when spawning the
process, the <code>message</code> argument can contain data that JSON is not able
to represent.
See <a href="#all_child_process_advanced-serialization">Advanced serialization for <code>child_process</code></a> for more details.</p>
<h4>Event: <code>'multipleResolves'</code><span><a class="mark" href="#all_process_event-multipleresolves" id="all_process_event-multipleresolves">#</a></span><a aria-hidden="true" class="legacy" id="process_event_multipleresolves"></a></h4>
<div class="api_metadata">
<span>Added in: v10.12.0</span><span>Deprecated since: v17.6.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The resolution type. One of <code>'resolve'</code> or <code>'reject'</code>.</li>
<li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> The promise that resolved or rejected more than once.</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The value with which the promise was either resolved or
rejected after the original resolve.</li>
</ul>
<p>The <code>'multipleResolves'</code> event is emitted whenever a <code>Promise</code> has been either:</p>
<ul>
<li>Resolved more than once.</li>
<li>Rejected more than once.</li>
<li>Rejected after resolve.</li>
<li>Resolved after reject.</li>
</ul>
<p>This is useful for tracking potential errors in an application while using the
<code>Promise</code> constructor, as multiple resolutions are silently swallowed. However,
the occurrence of this event does not necessarily indicate an error. For
example, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race"><code>Promise.race()</code></a> can trigger a <code>'multipleResolves'</code> event.</p>
<p>Because of the unreliability of the event in cases like the
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race"><code>Promise.race()</code></a> example above it has been deprecated.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'multipleResolves'</span>, <span class="hljs-function">(<span class="hljs-params">type, promise, reason</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(type, promise, reason);
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>));
});
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">main</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'First call'</span>);
<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'Swallowed resolve'</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">'Swallowed reject'</span>));
});
} <span class="hljs-keyword">catch</span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Failed'</span>);
}
}
<span class="hljs-title function_">main</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);
<span class="hljs-comment">// resolve: Promise { 'First call' } 'Swallowed resolve'</span>
<span class="hljs-comment">// reject: Promise { 'First call' } Error: Swallowed reject</span>
<span class="hljs-comment">// at Promise (*)</span>
<span class="hljs-comment">// at new Promise (<anonymous>)</span>
<span class="hljs-comment">// at main (*)</span>
<span class="hljs-comment">// First call</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'multipleResolves'</span>, <span class="hljs-function">(<span class="hljs-params">type, promise, reason</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(type, promise, reason);
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>));
});
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">main</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'First call'</span>);
<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'Swallowed resolve'</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">'Swallowed reject'</span>));
});
} <span class="hljs-keyword">catch</span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Failed'</span>);
}
}
<span class="hljs-title function_">main</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);
<span class="hljs-comment">// resolve: Promise { 'First call' } 'Swallowed resolve'</span>
<span class="hljs-comment">// reject: Promise { 'First call' } Error: Swallowed reject</span>
<span class="hljs-comment">// at Promise (*)</span>
<span class="hljs-comment">// at new Promise (<anonymous>)</span>
<span class="hljs-comment">// at main (*)</span>
<span class="hljs-comment">// First call</span></code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'rejectionHandled'</code><span><a class="mark" href="#all_process_event-rejectionhandled" id="all_process_event-rejectionhandled">#</a></span><a aria-hidden="true" class="legacy" id="process_event_rejectionhandled"></a></h4>
<div class="api_metadata">
<span>Added in: v1.4.1</span>
</div>
<ul>
<li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> The late handled promise.</li>
</ul>
<p>The <code>'rejectionHandled'</code> event is emitted whenever a <code>Promise</code> has been rejected
and an error handler was attached to it (using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch"><code>promise.catch()</code></a>, for
example) later than one turn of the Node.js event loop.</p>
<p>The <code>Promise</code> object would have previously been emitted in an
<code>'unhandledRejection'</code> event, but during the course of processing gained a
rejection handler.</p>
<p>There is no notion of a top level for a <code>Promise</code> chain at which rejections can
always be handled. Being inherently asynchronous in nature, a <code>Promise</code>
rejection can be handled at a future point in time, possibly much later than
the event loop turn it takes for the <code>'unhandledRejection'</code> event to be emitted.</p>
<p>Another way of stating this is that, unlike in synchronous code where there is
an ever-growing list of unhandled exceptions, with Promises there can be a
growing-and-shrinking list of unhandled rejections.</p>
<p>In synchronous code, the <code>'uncaughtException'</code> event is emitted when the list of
unhandled exceptions grows.</p>
<p>In asynchronous code, the <code>'unhandledRejection'</code> event is emitted when the list
of unhandled rejections grows, and the <code>'rejectionHandled'</code> event is emitted
when the list of unhandled rejections shrinks.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> unhandledRejections = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unhandledRejection'</span>, <span class="hljs-function">(<span class="hljs-params">reason, promise</span>) =></span> {
unhandledRejections.<span class="hljs-title function_">set</span>(promise, reason);
});
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'rejectionHandled'</span>, <span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {
unhandledRejections.<span class="hljs-title function_">delete</span>(promise);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> unhandledRejections = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unhandledRejection'</span>, <span class="hljs-function">(<span class="hljs-params">reason, promise</span>) =></span> {
unhandledRejections.<span class="hljs-title function_">set</span>(promise, reason);
});
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'rejectionHandled'</span>, <span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {
unhandledRejections.<span class="hljs-title function_">delete</span>(promise);
});</code><button class="copy-button">copy</button></pre>
<p>In this example, the <code>unhandledRejections</code> <code>Map</code> will grow and shrink over time,
reflecting rejections that start unhandled and then become handled. It is
possible to record such errors in an error log, either periodically (which is
likely best for long-running application) or upon process exit (which is likely
most convenient for scripts).</p>
<h4>Event: <code>'workerMessage'</code><span><a class="mark" href="#all_process_event-workermessage" id="all_process_event-workermessage">#</a></span><a aria-hidden="true" class="legacy" id="process_event_workermessage"></a></h4>
<div class="api_metadata">
<span>Added in: v20.19.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> A value transmitted using <a href="#all_worker_threads_workerpostmessagetothreadthreadid-value-transferlist-timeout"><code>postMessageToThread()</code></a>.</li>
<li><code>source</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The transmitting worker thread ID or <code>0</code> for the main thread.</li>
</ul>
<p>The <code>'workerMessage'</code> event is emitted for any incoming message send by the other
party by using <a href="#all_worker_threads_workerpostmessagetothreadthreadid-value-transferlist-timeout"><code>postMessageToThread()</code></a>.</p>
<h4>Event: <code>'uncaughtException'</code><span><a class="mark" href="#all_process_event-uncaughtexception" id="all_process_event-uncaughtexception">#</a></span><a aria-hidden="true" class="legacy" id="process_event_uncaughtexception"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0, v10.17.0</td>
<td><p>Added the <code>origin</code> argument.</p></td></tr>
<tr><td>v0.1.18</td>
<td><p><span>Added in: v0.1.18</span></p></td></tr>
</tbody></table>
</details>
</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> The uncaught exception.</li>
<li><code>origin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Indicates if the exception originates from an unhandled
rejection or from a synchronous error. Can either be <code>'uncaughtException'</code> or
<code>'unhandledRejection'</code>. The latter is used when an exception happens in a
<code>Promise</code> based async context (or if a <code>Promise</code> is rejected) and
<a href="#all_cli_--unhandled-rejectionsmode"><code>--unhandled-rejections</code></a> flag set to <code>strict</code> or <code>throw</code> (which is the
default) and the rejection is not handled, or when a rejection happens during
the command line entry point's ES module static loading phase.</li>
</ul>
<p>The <code>'uncaughtException'</code> event is emitted when an uncaught JavaScript
exception bubbles all the way back to the event loop. By default, Node.js
handles such exceptions by printing the stack trace to <code>stderr</code> and exiting
with code 1, overriding any previously set <a href="#all_process_processexitcode_1"><code>process.exitCode</code></a>.
Adding a handler for the <code>'uncaughtException'</code> event overrides this default
behavior. Alternatively, change the <a href="#all_process_processexitcode_1"><code>process.exitCode</code></a> in the
<code>'uncaughtException'</code> handler which will result in the process exiting with the
provided exit code. Otherwise, in the presence of such handler the process will
exit with 0.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'uncaughtException'</span>, <span class="hljs-function">(<span class="hljs-params">err, origin</span>) =></span> {
fs.<span class="hljs-title function_">writeSync</span>(
process.<span class="hljs-property">stderr</span>.<span class="hljs-property">fd</span>,
<span class="hljs-string">`Caught exception: <span class="hljs-subst">${err}</span>\n`</span> +
<span class="hljs-string">`Exception origin: <span class="hljs-subst">${origin}</span>\n`</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">'This will still run.'</span>);
}, <span class="hljs-number">500</span>);
<span class="hljs-comment">// Intentionally cause an exception, but don't catch it.</span>
<span class="hljs-title function_">nonexistentFunc</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This will not run.'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'uncaughtException'</span>, <span class="hljs-function">(<span class="hljs-params">err, origin</span>) =></span> {
fs.<span class="hljs-title function_">writeSync</span>(
process.<span class="hljs-property">stderr</span>.<span class="hljs-property">fd</span>,
<span class="hljs-string">`Caught exception: <span class="hljs-subst">${err}</span>\n`</span> +
<span class="hljs-string">`Exception origin: <span class="hljs-subst">${origin}</span>\n`</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">'This will still run.'</span>);
}, <span class="hljs-number">500</span>);
<span class="hljs-comment">// Intentionally cause an exception, but don't catch it.</span>
<span class="hljs-title function_">nonexistentFunc</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This will not run.'</span>);</code><button class="copy-button">copy</button></pre>
<p>It is possible to monitor <code>'uncaughtException'</code> events without overriding the
default behavior to exit the process by installing a
<code>'uncaughtExceptionMonitor'</code> listener.</p>
<h5>Warning: Using <code>'uncaughtException'</code> correctly<span><a class="mark" href="#all_process_warning-using-uncaughtexception-correctly" id="all_process_warning-using-uncaughtexception-correctly">#</a></span><a aria-hidden="true" class="legacy" id="process_warning_using_uncaughtexception_correctly"></a></h5>
<p><code>'uncaughtException'</code> is a crude mechanism for exception handling
intended to be used only as a last resort. The event <em>should not</em> be used as
an equivalent to <code>On Error Resume Next</code>. Unhandled exceptions inherently mean
that an application is in an undefined state. Attempting to resume application
code without properly recovering from the exception can cause additional
unforeseen and unpredictable issues.</p>
<p>Exceptions thrown from within the event handler will not be caught. Instead the
process will exit with a non-zero exit code and the stack trace will be printed.
This is to avoid infinite recursion.</p>
<p>Attempting to resume normally after an uncaught exception can be similar to
pulling out the power cord when upgrading a computer. Nine out of ten
times, nothing happens. But the tenth time, the system becomes corrupted.</p>
<p>The correct use of <code>'uncaughtException'</code> is to perform synchronous cleanup
of allocated resources (e.g. file descriptors, handles, etc) before shutting
down the process. <strong>It is not safe to resume normal operation after
<code>'uncaughtException'</code>.</strong></p>
<p>To restart a crashed application in a more reliable way, whether
<code>'uncaughtException'</code> is emitted or not, an external monitor should be employed
in a separate process to detect application failures and recover or restart as
needed.</p>
<h4>Event: <code>'uncaughtExceptionMonitor'</code><span><a class="mark" href="#all_process_event-uncaughtexceptionmonitor" id="all_process_event-uncaughtexceptionmonitor">#</a></span><a aria-hidden="true" class="legacy" id="process_event_uncaughtexceptionmonitor"></a></h4>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.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> The uncaught exception.</li>
<li><code>origin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Indicates if the exception originates from an unhandled
rejection or from synchronous errors. Can either be <code>'uncaughtException'</code> or
<code>'unhandledRejection'</code>. The latter is used when an exception happens in a
<code>Promise</code> based async context (or if a <code>Promise</code> is rejected) and
<a href="#all_cli_--unhandled-rejectionsmode"><code>--unhandled-rejections</code></a> flag set to <code>strict</code> or <code>throw</code> (which is the
default) and the rejection is not handled, or when a rejection happens during
the command line entry point's ES module static loading phase.</li>
</ul>
<p>The <code>'uncaughtExceptionMonitor'</code> event is emitted before an
<code>'uncaughtException'</code> event is emitted or a hook installed via
<a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> is called.</p>
<p>Installing an <code>'uncaughtExceptionMonitor'</code> listener does not change the behavior
once an <code>'uncaughtException'</code> event is emitted. The process will
still crash if no <code>'uncaughtException'</code> listener is installed.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'uncaughtExceptionMonitor'</span>, <span class="hljs-function">(<span class="hljs-params">err, origin</span>) =></span> {
<span class="hljs-title class_">MyMonitoringTool</span>.<span class="hljs-title function_">logSync</span>(err, origin);
});
<span class="hljs-comment">// Intentionally cause an exception, but don't catch it.</span>
<span class="hljs-title function_">nonexistentFunc</span>();
<span class="hljs-comment">// Still crashes Node.js</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'uncaughtExceptionMonitor'</span>, <span class="hljs-function">(<span class="hljs-params">err, origin</span>) =></span> {
<span class="hljs-title class_">MyMonitoringTool</span>.<span class="hljs-title function_">logSync</span>(err, origin);
});
<span class="hljs-comment">// Intentionally cause an exception, but don't catch it.</span>
<span class="hljs-title function_">nonexistentFunc</span>();
<span class="hljs-comment">// Still crashes Node.js</span></code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'unhandledRejection'</code><span><a class="mark" href="#all_process_event-unhandledrejection" id="all_process_event-unhandledrejection">#</a></span><a aria-hidden="true" class="legacy" id="process_event_unhandledrejection"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>Not handling <code>Promise</code> rejections is deprecated.</p></td></tr>
<tr><td>v6.6.0</td>
<td><p>Unhandled <code>Promise</code> rejections will now emit a process warning.</p></td></tr>
<tr><td>v1.4.1</td>
<td><p><span>Added in: v1.4.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The object with which the promise was rejected
(typically an <a href="#all_errors_class-error"><code>Error</code></a> object).</li>
<li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> The rejected promise.</li>
</ul>
<p>The <code>'unhandledRejection'</code> event is emitted whenever a <code>Promise</code> is rejected and
no error handler is attached to the promise within a turn of the event loop.
When programming with Promises, exceptions are encapsulated as "rejected
promises". Rejections can be caught and handled using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch"><code>promise.catch()</code></a> and
are propagated through a <code>Promise</code> chain. The <code>'unhandledRejection'</code> event is
useful for detecting and keeping track of promises that were rejected whose
rejections have not yet been handled.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unhandledRejection'</span>, <span class="hljs-function">(<span class="hljs-params">reason, promise</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Unhandled Rejection at:'</span>, promise, <span class="hljs-string">'reason:'</span>, reason);
<span class="hljs-comment">// Application specific logging, throwing an error, or other logic here</span>
});
somePromise.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-keyword">return</span> <span class="hljs-title function_">reportToUser</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">pasre</span>(res)); <span class="hljs-comment">// Note the typo (`pasre`)</span>
}); <span class="hljs-comment">// No `.catch()` or `.then()`</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unhandledRejection'</span>, <span class="hljs-function">(<span class="hljs-params">reason, promise</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Unhandled Rejection at:'</span>, promise, <span class="hljs-string">'reason:'</span>, reason);
<span class="hljs-comment">// Application specific logging, throwing an error, or other logic here</span>
});
somePromise.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-keyword">return</span> <span class="hljs-title function_">reportToUser</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">pasre</span>(res)); <span class="hljs-comment">// Note the typo (`pasre`)</span>
}); <span class="hljs-comment">// No `.catch()` or `.then()`</span></code><button class="copy-button">copy</button></pre>
<p>The following will also trigger the <code>'unhandledRejection'</code> event to be
emitted:</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">SomeResource</span>(<span class="hljs-params"></span>) {
<span class="hljs-comment">// Initially set the loaded status to a rejected promise</span>
<span class="hljs-variable language_">this</span>.<span class="hljs-property">loaded</span> = <span class="hljs-title class_">Promise</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">'Resource not yet loaded!'</span>));
}
<span class="hljs-keyword">const</span> resource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SomeResource</span>();
<span class="hljs-comment">// no .catch or .then on resource.loaded for at least a turn</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">SomeResource</span>(<span class="hljs-params"></span>) {
<span class="hljs-comment">// Initially set the loaded status to a rejected promise</span>
<span class="hljs-variable language_">this</span>.<span class="hljs-property">loaded</span> = <span class="hljs-title class_">Promise</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">'Resource not yet loaded!'</span>));
}
<span class="hljs-keyword">const</span> resource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SomeResource</span>();
<span class="hljs-comment">// no .catch or .then on resource.loaded for at least a turn</span></code><button class="copy-button">copy</button></pre>
<p>In this example case, it is possible to track the rejection as a developer error
as would typically be the case for other <code>'unhandledRejection'</code> events. To
address such failures, a non-operational
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch"><code>.catch(() => { })</code></a> handler may be attached to
<code>resource.loaded</code>, which would prevent the <code>'unhandledRejection'</code> event from
being emitted.</p>
<h4>Event: <code>'warning'</code><span><a class="mark" href="#all_process_event-warning" id="all_process_event-warning">#</a></span><a aria-hidden="true" class="legacy" id="process_event_warning"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<ul>
<li><code>warning</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> Key properties of the warning are:
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the warning. <strong>Default:</strong> <code>'Warning'</code>.</li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A system-provided description of the warning.</li>
<li><code>stack</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A stack trace to the location in the code where the warning
was issued.</li>
</ul>
</li>
</ul>
<p>The <code>'warning'</code> event is emitted whenever Node.js emits a process warning.</p>
<p>A process warning is similar to an error in that it describes exceptional
conditions that are being brought to the user's attention. However, warnings
are not part of the normal Node.js and JavaScript error handling flow.
Node.js can emit warnings whenever it detects bad coding practices that could
lead to sub-optimal application performance, bugs, or security vulnerabilities.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'warning'</span>, <span class="hljs-function">(<span class="hljs-params">warning</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">name</span>); <span class="hljs-comment">// Print the warning name</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">message</span>); <span class="hljs-comment">// Print the warning message</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">stack</span>); <span class="hljs-comment">// Print the stack trace</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'warning'</span>, <span class="hljs-function">(<span class="hljs-params">warning</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">name</span>); <span class="hljs-comment">// Print the warning name</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">message</span>); <span class="hljs-comment">// Print the warning message</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">stack</span>); <span class="hljs-comment">// Print the stack trace</span>
});</code><button class="copy-button">copy</button></pre>
<p>By default, Node.js will print process warnings to <code>stderr</code>. The <code>--no-warnings</code>
command-line option can be used to suppress the default console output but the
<code>'warning'</code> event will still be emitted by the <code>process</code> object. Currently, it
is not possible to suppress specific warning types other than deprecation
warnings. To suppress deprecation warnings, check out the <a href="#all_cli_--no-deprecation"><code>--no-deprecation</code></a>
flag.</p>
<p>The following example illustrates the warning that is printed to <code>stderr</code> when
too many listeners have been added to an event:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">events.defaultMaxListeners = 1;</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.on(<span class="hljs-string">'foo'</span>, () => {});</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.on(<span class="hljs-string">'foo'</span>, () => {});</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">(node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak</span>
detected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit</code> <button class="copy-button">copy</button></pre>
<p>In contrast, the following example turns off the default warning output and
adds a custom handler to the <code>'warning'</code> event:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --no-warnings</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">const p = process.on(<span class="hljs-string">'warning'</span>, (warning) => console.warn(<span class="hljs-string">'Do not do that!'</span>));</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">events.defaultMaxListeners = 1;</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.on(<span class="hljs-string">'foo'</span>, () => {});</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.on(<span class="hljs-string">'foo'</span>, () => {});</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">Do not <span class="hljs-keyword">do</span> that!</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>--trace-warnings</code> command-line option can be used to have the default
console output for warnings include the full stack trace of the warning.</p>
<p>Launching Node.js using the <code>--throw-deprecation</code> command-line flag will
cause custom deprecation warnings to be thrown as exceptions.</p>
<p>Using the <code>--trace-deprecation</code> command-line flag will cause the custom
deprecation to be printed to <code>stderr</code> along with the stack trace.</p>
<p>Using the <code>--no-deprecation</code> command-line flag will suppress all reporting
of the custom deprecation.</p>
<p>The <code>*-deprecation</code> command-line flags only affect warnings that use the name
<code>'DeprecationWarning'</code>.</p>
<h5>Emitting custom warnings<span><a class="mark" href="#all_process_emitting-custom-warnings" id="all_process_emitting-custom-warnings">#</a></span><a aria-hidden="true" class="legacy" id="process_emitting_custom_warnings"></a></h5>
<p>See the <a href="#all_process_processemitwarningwarning-type-code-ctor"><code>process.emitWarning()</code></a> method for issuing
custom or application-specific warnings.</p>
<h5>Node.js warning names<span><a class="mark" href="#all_process_nodejs-warning-names" id="all_process_nodejs-warning-names">#</a></span><a aria-hidden="true" class="legacy" id="process_node_js_warning_names"></a></h5>
<p>There are no strict guidelines for warning types (as identified by the <code>name</code>
property) emitted by Node.js. New types of warnings can be added at any time.
A few of the warning types that are most common include:</p>
<ul>
<li><code>'DeprecationWarning'</code> - Indicates use of a deprecated Node.js API or feature.
Such warnings must include a <code>'code'</code> property identifying the
<a href="deprecations.html">deprecation code</a>.</li>
<li><code>'ExperimentalWarning'</code> - Indicates use of an experimental Node.js API or
feature. Such features must be used with caution as they may change at any
time and are not subject to the same strict semantic-versioning and long-term
support policies as supported features.</li>
<li><code>'MaxListenersExceededWarning'</code> - Indicates that too many listeners for a
given event have been registered on either an <code>EventEmitter</code> or <code>EventTarget</code>.
This is often an indication of a memory leak.</li>
<li><code>'TimeoutOverflowWarning'</code> - Indicates that a numeric value that cannot fit
within a 32-bit signed integer has been provided to either the <code>setTimeout()</code>
or <code>setInterval()</code> functions.</li>
<li><code>'UnsupportedWarning'</code> - Indicates use of an unsupported option or feature
that will be ignored rather than treated as an error. One example is use of
the HTTP response status message when using the HTTP/2 compatibility API.</li>
</ul>
<h4>Event: <code>'worker'</code><span><a class="mark" href="#all_process_event-worker" id="all_process_event-worker">#</a></span><a aria-hidden="true" class="legacy" id="process_event_worker"></a></h4>
<div class="api_metadata">
<span>Added in: v16.2.0, v14.18.0</span>
</div>
<ul>
<li><code>worker</code> <a href="#all_worker_threads_class-worker" class="type"><Worker></a> The <a href="#all_worker_threads_class-worker" class="type"><Worker></a> that was created.</li>
</ul>
<p>The <code>'worker'</code> event is emitted after a new <a href="#all_worker_threads_class-worker" class="type"><Worker></a> thread has been created.</p>
<h4>Signal events<span><a class="mark" href="#all_process_signal-events" id="all_process_signal-events">#</a></span><a aria-hidden="true" class="legacy" id="process_signal_events"></a></h4>
<p>Signal events will be emitted when the Node.js process receives a signal. Please
refer to <a href="http://man7.org/linux/man-pages/man7/signal.7.html"><code>signal(7)</code></a> for a listing of standard POSIX signal names such as
<code>'SIGINT'</code>, <code>'SIGHUP'</code>, etc.</p>
<p>Signals are not available on <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
<p>The signal handler will receive the signal's name (<code>'SIGINT'</code>,
<code>'SIGTERM'</code>, etc.) as the first argument.</p>
<p>The name of each event will be the uppercase common name for the signal (e.g.
<code>'SIGINT'</code> for <code>SIGINT</code> signals).</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-comment">// Begin reading from stdin so the process does not exit.</span>
process.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">resume</span>();
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Received SIGINT. Press Control-D to exit.'</span>);
});
<span class="hljs-comment">// Using a single function to handle multiple signals</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">handle</span>(<span class="hljs-params">signal</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${signal}</span>`</span>);
}
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, handle);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGTERM'</span>, handle);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-comment">// Begin reading from stdin so the process does not exit.</span>
process.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">resume</span>();
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Received SIGINT. Press Control-D to exit.'</span>);
});
<span class="hljs-comment">// Using a single function to handle multiple signals</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">handle</span>(<span class="hljs-params">signal</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${signal}</span>`</span>);
}
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, handle);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGTERM'</span>, handle);</code><button class="copy-button">copy</button></pre>
<ul>
<li><code>'SIGUSR1'</code> is reserved by Node.js to start the <a href="debugger.html">debugger</a>. It's possible to
install a listener but doing so might interfere with the debugger.</li>
<li><code>'SIGTERM'</code> and <code>'SIGINT'</code> have default handlers on non-Windows platforms that
reset the terminal mode before exiting with code <code>128 + signal number</code>. If one
of these signals has a listener installed, its default behavior will be
removed (Node.js will no longer exit).</li>
<li><code>'SIGPIPE'</code> is ignored by default. It can have a listener installed.</li>
<li><code>'SIGHUP'</code> is generated on Windows when the console window is closed, and on
other platforms under various similar conditions. See <a href="http://man7.org/linux/man-pages/man7/signal.7.html"><code>signal(7)</code></a>. It can have a
listener installed, however Node.js will be unconditionally terminated by
Windows about 10 seconds later. On non-Windows platforms, the default
behavior of <code>SIGHUP</code> is to terminate Node.js, but once a listener has been
installed its default behavior will be removed.</li>
<li><code>'SIGTERM'</code> is not supported on Windows, it can be listened on.</li>
<li><code>'SIGINT'</code> from the terminal is supported on all platforms, and can usually be
generated with <kbd>Ctrl</kbd>+<kbd>C</kbd> (though this may be configurable).
It is not generated when <a href="#all_tty_readstreamsetrawmodemode">terminal raw mode</a> is enabled
and <kbd>Ctrl</kbd>+<kbd>C</kbd> is used.</li>
<li><code>'SIGBREAK'</code> is delivered on Windows when <kbd>Ctrl</kbd>+<kbd>Break</kbd> is
pressed. On non-Windows platforms, it can be listened on, but there is no way
to send or generate it.</li>
<li><code>'SIGWINCH'</code> is delivered when the console has been resized. On Windows, this
will only happen on write to the console when the cursor is being moved, or
when a readable tty is used in raw mode.</li>
<li><code>'SIGKILL'</code> cannot have a listener installed, it will unconditionally
terminate Node.js on all platforms.</li>
<li><code>'SIGSTOP'</code> cannot have a listener installed.</li>
<li><code>'SIGBUS'</code>, <code>'SIGFPE'</code>, <code>'SIGSEGV'</code>, and <code>'SIGILL'</code>, when not raised
artificially using <a href="http://man7.org/linux/man-pages/man2/kill.2.html"><code>kill(2)</code></a>, inherently leave the process in a state from
which it is not safe to call JS listeners. Doing so might cause the process
to stop responding.</li>
<li><code>0</code> can be sent to test for the existence of a process, it has no effect if
the process exists, but will throw an error if the process does not exist.</li>
</ul>
<p>Windows does not support signals so has no equivalent to termination by signal,
but Node.js offers some emulation with <a href="#all_process_processkillpid-signal"><code>process.kill()</code></a>, and
<a href="#all_child_process_subprocesskillsignal"><code>subprocess.kill()</code></a>:</p>
<ul>
<li>Sending <code>SIGINT</code>, <code>SIGTERM</code>, and <code>SIGKILL</code> will cause the unconditional
termination of the target process, and afterwards, subprocess will report that
the process was terminated by signal.</li>
<li>Sending signal <code>0</code> can be used as a platform independent way to test for the
existence of a process.</li>
</ul>
</section><section><h3><code>process.abort()</code><span><a class="mark" href="#all_process_processabort" id="all_process_processabort">#</a></span><a aria-hidden="true" class="legacy" id="process_process_abort"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<p>The <code>process.abort()</code> method causes the Node.js process to exit immediately and
generate a core file.</p>
<p>This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.allowedNodeEnvironmentFlags</code><span><a class="mark" href="#all_process_processallowednodeenvironmentflags" id="all_process_processallowednodeenvironmentflags">#</a></span><a aria-hidden="true" class="legacy" id="process_process_allowednodeenvironmentflags"></a></h3>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set" class="type"><Set></a></li>
</ul>
<p>The <code>process.allowedNodeEnvironmentFlags</code> property is a special,
read-only <code>Set</code> of flags allowable within the <a href="#all_cli_node_optionsoptions"><code>NODE_OPTIONS</code></a>
environment variable.</p>
<p><code>process.allowedNodeEnvironmentFlags</code> extends <code>Set</code>, but overrides
<code>Set.prototype.has</code> to recognize several different possible flag
representations. <code>process.allowedNodeEnvironmentFlags.has()</code> will
return <code>true</code> in the following cases:</p>
<ul>
<li>Flags may omit leading single (<code>-</code>) or double (<code>--</code>) dashes; e.g.,
<code>inspect-brk</code> for <code>--inspect-brk</code>, or <code>r</code> for <code>-r</code>.</li>
<li>Flags passed through to V8 (as listed in <code>--v8-options</code>) may replace
one or more <em>non-leading</em> dashes for an underscore, or vice-versa;
e.g., <code>--perf_basic_prof</code>, <code>--perf-basic-prof</code>, <code>--perf_basic-prof</code>,
etc.</li>
<li>Flags may contain one or more equals (<code>=</code>) characters; all
characters after and including the first equals will be ignored;
e.g., <code>--stack-trace-limit=100</code>.</li>
<li>Flags <em>must</em> be allowable within <a href="#all_cli_node_optionsoptions"><code>NODE_OPTIONS</code></a>.</li>
</ul>
<p>When iterating over <code>process.allowedNodeEnvironmentFlags</code>, flags will
appear only <em>once</em>; each will begin with one or more dashes. Flags
passed through to V8 will contain underscores instead of non-leading
dashes:</p>
<pre class="with-64-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> { allowedNodeEnvironmentFlags } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
allowedNodeEnvironmentFlags.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">flag</span>) =></span> {
<span class="hljs-comment">// -r</span>
<span class="hljs-comment">// --inspect-brk</span>
<span class="hljs-comment">// --abort_on_uncaught_exception</span>
<span class="hljs-comment">// ...</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { allowedNodeEnvironmentFlags } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
allowedNodeEnvironmentFlags.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">flag</span>) =></span> {
<span class="hljs-comment">// -r</span>
<span class="hljs-comment">// --inspect-brk</span>
<span class="hljs-comment">// --abort_on_uncaught_exception</span>
<span class="hljs-comment">// ...</span>
});</code><button class="copy-button">copy</button></pre>
<p>The methods <code>add()</code>, <code>clear()</code>, and <code>delete()</code> of
<code>process.allowedNodeEnvironmentFlags</code> do nothing, and will fail
silently.</p>
<p>If Node.js was compiled <em>without</em> <a href="#all_cli_node_optionsoptions"><code>NODE_OPTIONS</code></a> support (shown in
<a href="#all_process_processconfig"><code>process.config</code></a>), <code>process.allowedNodeEnvironmentFlags</code> will
contain what <em>would have</em> been allowable.</p>
</section><section><h3><code>process.arch</code><span><a class="mark" href="#all_process_processarch" id="all_process_processarch">#</a></span><a aria-hidden="true" class="legacy" id="process_process_arch"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The operating system CPU architecture for which the Node.js binary was compiled.
Possible values are: <code>'arm'</code>, <code>'arm64'</code>, <code>'ia32'</code>, <code>'loong64'</code>, <code>'mips'</code>,
<code>'mipsel'</code>, <code>'ppc'</code>, <code>'ppc64'</code>, <code>'riscv64'</code>, <code>'s390'</code>, <code>'s390x'</code>, and <code>'x64'</code>.</p>
<pre class="with-41-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> { arch } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This processor architecture is <span class="hljs-subst">${arch}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { arch } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This processor architecture is <span class="hljs-subst">${arch}</span>`</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.argv</code><span><a class="mark" href="#all_process_processargv" id="all_process_processargv">#</a></span><a aria-hidden="true" class="legacy" id="process_process_argv"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>The <code>process.argv</code> property returns an array containing the command-line
arguments passed when the Node.js process was launched. The first element will
be <a href="#all_process_processexecpath"><code>process.execPath</code></a>. See <code>process.argv0</code> if access to the original value
of <code>argv[0]</code> is needed. The second element will be the path to the JavaScript
file being executed. The remaining elements will be any additional command-line
arguments.</p>
<p>For example, assuming the following script for <code>process-args.js</code>:</p>
<pre class="with-41-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> { argv } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-comment">// print process.argv</span>
argv.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">val, index</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${index}</span>: <span class="hljs-subst">${val}</span>`</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { argv } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-comment">// print process.argv</span>
argv.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">val, index</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${index}</span>: <span class="hljs-subst">${val}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Launching the Node.js process as:</p>
<pre><code class="language-bash">node process-args.js one two=three four</code> <button class="copy-button">copy</button></pre>
<p>Would generate the output:</p>
<pre><code class="language-text">0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>process.argv0</code><span><a class="mark" href="#all_process_processargv0" id="all_process_processargv0">#</a></span><a aria-hidden="true" class="legacy" id="process_process_argv0"></a></h3>
<div class="api_metadata">
<span>Added in: v6.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>process.argv0</code> property stores a read-only copy of the original value of
<code>argv[0]</code> passed when Node.js starts.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">bash -c <span class="hljs-string">'exec -a customArgv0 ./node'</span></span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.argv[0]</span>
'/Volumes/code/external/node/out/Release/node'
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.argv0</span>
'customArgv0'</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>process.channel</code><span><a class="mark" href="#all_process_processchannel" id="all_process_processchannel">#</a></span><a aria-hidden="true" class="legacy" id="process_process_channel"></a></h3>
<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>The object no longer accidentally exposes native C++ bindings.</p></td></tr>
<tr><td>v7.1.0</td>
<td><p><span>Added in: v7.1.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>If the Node.js process was spawned with an IPC channel (see the
<a href="child_process.html">Child Process</a> documentation), the <code>process.channel</code>
property is a reference to the IPC channel. If no IPC channel exists, this
property is <code>undefined</code>.</p>
<h4><code>process.channel.ref()</code><span><a class="mark" href="#all_process_processchannelref" id="all_process_processchannelref">#</a></span><a aria-hidden="true" class="legacy" id="process_process_channel_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v7.1.0</span>
</div>
<p>This method makes the IPC channel keep the event loop of the process
running if <code>.unref()</code> has been called before.</p>
<p>Typically, this is managed through the number of <code>'disconnect'</code> and <code>'message'</code>
listeners on the <code>process</code> object. However, this method can be used to
explicitly request a specific behavior.</p>
<h4><code>process.channel.unref()</code><span><a class="mark" href="#all_process_processchannelunref" id="all_process_processchannelunref">#</a></span><a aria-hidden="true" class="legacy" id="process_process_channel_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v7.1.0</span>
</div>
<p>This method makes the IPC channel not keep the event loop of the process
running, and lets it finish even while the channel is open.</p>
<p>Typically, this is managed through the number of <code>'disconnect'</code> and <code>'message'</code>
listeners on the <code>process</code> object. However, this method can be used to
explicitly request a specific behavior.</p>
</section><section><h3><code>process.chdir(directory)</code><span><a class="mark" href="#all_process_processchdirdirectory" id="all_process_processchdirdirectory">#</a></span><a aria-hidden="true" class="legacy" id="process_process_chdir_directory"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<ul>
<li><code>directory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>process.chdir()</code> method changes the current working directory of the
Node.js process or throws an exception if doing so fails (for instance, if
the specified <code>directory</code> does not exist).</p>
<pre class="with-47-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> { chdir, cwd } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Starting directory: <span class="hljs-subst">${cwd()}</span>`</span>);
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">chdir</span>(<span class="hljs-string">'/tmp'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New directory: <span class="hljs-subst">${cwd()}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`chdir: <span class="hljs-subst">${err}</span>`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { chdir, cwd } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Starting directory: <span class="hljs-subst">${cwd()}</span>`</span>);
<span class="hljs-keyword">try</span> {
<span class="hljs-title function_">chdir</span>(<span class="hljs-string">'/tmp'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New directory: <span class="hljs-subst">${cwd()}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`chdir: <span class="hljs-subst">${err}</span>`</span>);
}</code><button class="copy-button">copy</button></pre>
<p>This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.config</code><span><a class="mark" href="#all_process_processconfig" id="all_process_processconfig">#</a></span><a aria-hidden="true" class="legacy" id="process_process_config"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>The <code>process.config</code> object is now frozen.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Modifying process.config has been deprecated.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>process.config</code> property returns a frozen <code>Object</code> containing the
JavaScript representation of the configure options used to compile the current
Node.js executable. This is the same as the <code>config.gypi</code> file that was produced
when running the <code>./configure</code> script.</p>
<p>An example of the possible output looks like:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
<span class="hljs-attr">target_defaults</span>:
{ <span class="hljs-attr">cflags</span>: [],
<span class="hljs-attr">default_configuration</span>: <span class="hljs-string">'Release'</span>,
<span class="hljs-attr">defines</span>: [],
<span class="hljs-attr">include_dirs</span>: [],
<span class="hljs-attr">libraries</span>: [] },
<span class="hljs-attr">variables</span>:
{
<span class="hljs-attr">host_arch</span>: <span class="hljs-string">'x64'</span>,
<span class="hljs-attr">napi_build_version</span>: <span class="hljs-number">5</span>,
<span class="hljs-attr">node_install_npm</span>: <span class="hljs-string">'true'</span>,
<span class="hljs-attr">node_prefix</span>: <span class="hljs-string">''</span>,
<span class="hljs-attr">node_shared_cares</span>: <span class="hljs-string">'false'</span>,
<span class="hljs-attr">node_shared_http_parser</span>: <span class="hljs-string">'false'</span>,
<span class="hljs-attr">node_shared_libuv</span>: <span class="hljs-string">'false'</span>,
<span class="hljs-attr">node_shared_zlib</span>: <span class="hljs-string">'false'</span>,
<span class="hljs-attr">node_use_openssl</span>: <span class="hljs-string">'true'</span>,
<span class="hljs-attr">node_shared_openssl</span>: <span class="hljs-string">'false'</span>,
<span class="hljs-attr">strict_aliasing</span>: <span class="hljs-string">'true'</span>,
<span class="hljs-attr">target_arch</span>: <span class="hljs-string">'x64'</span>,
<span class="hljs-attr">v8_use_snapshot</span>: <span class="hljs-number">1</span>
}
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>process.connected</code><span><a class="mark" href="#all_process_processconnected" id="all_process_processconnected">#</a></span><a aria-hidden="true" class="legacy" id="process_process_connected"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.2</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 the Node.js process is spawned with an IPC channel (see the <a href="child_process.html">Child Process</a>
and <a href="cluster.html">Cluster</a> documentation), the <code>process.connected</code> property will return
<code>true</code> so long as the IPC channel is connected and will return <code>false</code> after
<code>process.disconnect()</code> is called.</p>
<p>Once <code>process.connected</code> is <code>false</code>, it is no longer possible to send messages
over the IPC channel using <code>process.send()</code>.</p>
</section><section><h3><code>process.constrainedMemory()</code><span><a class="mark" href="#all_process_processconstrainedmemory" id="all_process_processconstrainedmemory">#</a></span><a aria-hidden="true" class="legacy" id="process_process_constrainedmemory"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Aligned return value with <code>uv_get_constrained_memory</code>.</p></td></tr>
<tr><td>v19.6.0, v18.15.0</td>
<td><p><span>Added in: v19.6.0, v18.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Gets the amount of memory available to the process (in bytes) based on
limits imposed by the OS. If there is no such constraint, or the constraint
is unknown, <code>0</code> is returned.</p>
<p>See <a href="https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory"><code>uv_get_constrained_memory</code></a> for more
information.</p>
</section><section><h3><code>process.availableMemory()</code><span><a class="mark" href="#all_process_processavailablememory" id="all_process_processavailablememory">#</a></span><a aria-hidden="true" class="legacy" id="process_process_availablememory"></a></h3>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Gets the amount of free memory that is still available to the process
(in bytes).</p>
<p>See <a href="https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_available_memory"><code>uv_get_available_memory</code></a> for more
information.</p>
</section><section><h3><code>process.cpuUsage([previousValue])</code><span><a class="mark" href="#all_process_processcpuusagepreviousvalue" id="all_process_processcpuusagepreviousvalue">#</a></span><a aria-hidden="true" class="legacy" id="process_process_cpuusage_previousvalue"></a></h3>
<div class="api_metadata">
<span>Added in: v6.1.0</span>
</div>
<ul>
<li><code>previousValue</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A previous return value from calling
<code>process.cpuUsage()</code></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>user</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>system</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
</li>
</ul>
<p>The <code>process.cpuUsage()</code> method returns the user and system CPU time usage of
the current process, in an object with properties <code>user</code> and <code>system</code>, whose
values are microsecond values (millionth of a second). These values measure time
spent in user and system code respectively, and may end up being greater than
actual elapsed time if multiple CPU cores are performing work for this process.</p>
<p>The result of a previous call to <code>process.cpuUsage()</code> can be passed as the
argument to the function, to get a diff reading.</p>
<pre class="with-45-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> { cpuUsage } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> startUsage = <span class="hljs-title function_">cpuUsage</span>();
<span class="hljs-comment">// { user: 38579, system: 6986 }</span>
<span class="hljs-comment">// spin the CPU for 500 milliseconds</span>
<span class="hljs-keyword">const</span> now = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
<span class="hljs-keyword">while</span> (<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>() - now < <span class="hljs-number">500</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">cpuUsage</span>(startUsage));
<span class="hljs-comment">// { user: 514883, system: 11226 }</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { cpuUsage } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> startUsage = <span class="hljs-title function_">cpuUsage</span>();
<span class="hljs-comment">// { user: 38579, system: 6986 }</span>
<span class="hljs-comment">// spin the CPU for 500 milliseconds</span>
<span class="hljs-keyword">const</span> now = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
<span class="hljs-keyword">while</span> (<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>() - now < <span class="hljs-number">500</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">cpuUsage</span>(startUsage));
<span class="hljs-comment">// { user: 514883, system: 11226 }</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.cwd()</code><span><a class="mark" href="#all_process_processcwd" id="all_process_processcwd">#</a></span><a aria-hidden="true" class="legacy" id="process_process_cwd"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.8</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>process.cwd()</code> method returns the current working directory of the Node.js
process.</p>
<pre class="with-40-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> { cwd } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current directory: <span class="hljs-subst">${cwd()}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { cwd } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current directory: <span class="hljs-subst">${cwd()}</span>`</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.debugPort</code><span><a class="mark" href="#all_process_processdebugport" id="all_process_processdebugport">#</a></span><a aria-hidden="true" class="legacy" id="process_process_debugport"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.2</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>The port used by the Node.js debugger when enabled.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
process.<span class="hljs-property">debugPort</span> = <span class="hljs-number">5858</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
process.<span class="hljs-property">debugPort</span> = <span class="hljs-number">5858</span>;</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.disconnect()</code><span><a class="mark" href="#all_process_processdisconnect" id="all_process_processdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="process_process_disconnect"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.2</span>
</div>
<p>If the Node.js process is spawned with an IPC channel (see the <a href="child_process.html">Child Process</a>
and <a href="cluster.html">Cluster</a> documentation), the <code>process.disconnect()</code> method will close the
IPC channel to the parent process, allowing the child process to exit gracefully
once there are no other connections keeping it alive.</p>
<p>The effect of calling <code>process.disconnect()</code> is the same as calling
<a href="#all_child_process_subprocessdisconnect"><code>ChildProcess.disconnect()</code></a> from the parent process.</p>
<p>If the Node.js process was not spawned with an IPC channel,
<code>process.disconnect()</code> will be <code>undefined</code>.</p>
</section><section><h3><code>process.dlopen(module, filename[, flags])</code><span><a class="mark" href="#all_process_processdlopenmodule-filename-flags" id="all_process_processdlopenmodule-filename-flags">#</a></span><a aria-hidden="true" class="legacy" id="process_process_dlopen_module_filename_flags"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Added support for the <code>flags</code> argument.</p></td></tr>
<tr><td>v0.1.16</td>
<td><p><span>Added in: v0.1.16</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>module</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>flags</code> <a href="#all_os_dlopen-constants" class="type"><os.constants.dlopen></a> <strong>Default:</strong> <code>os.constants.dlopen.RTLD_LAZY</code></li>
</ul>
<p>The <code>process.dlopen()</code> method allows dynamically loading shared objects. It is
primarily used by <code>require()</code> to load C++ Addons, and should not be used
directly, except in special cases. In other words, <a href="#all_globals_require"><code>require()</code></a> should be
preferred over <code>process.dlopen()</code> unless there are specific reasons such as
custom dlopen flags or loading from ES modules.</p>
<p>The <code>flags</code> argument is an integer that allows to specify dlopen
behavior. See the <a href="#all_os_dlopen-constants"><code>os.constants.dlopen</code></a> documentation for details.</p>
<p>An important requirement when calling <code>process.dlopen()</code> is that the <code>module</code>
instance must be passed. Functions exported by the C++ Addon are then
accessible via <code>module.exports</code>.</p>
<p>The example below shows how to load a C++ Addon, named <code>local.node</code>,
that exports a <code>foo</code> function. All the symbols are loaded before
the call returns, by passing the <code>RTLD_NOW</code> constant. In this example
the constant is assumed to be available.</p>
<pre class="with-43-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> { dlopen } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> { constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-keyword">import</span> { fileURLToPath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = { <span class="hljs-attr">exports</span>: {} };
<span class="hljs-title function_">dlopen</span>(<span class="hljs-variable language_">module</span>, <span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'local.node'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>)),
constants.<span class="hljs-property">dlopen</span>.<span class="hljs-property">RTLD_NOW</span>);
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-title function_">foo</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { dlopen } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> { constants } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>);
<span class="hljs-keyword">const</span> { join } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = { <span class="hljs-attr">exports</span>: {} };
<span class="hljs-title function_">dlopen</span>(<span class="hljs-variable language_">module</span>, <span class="hljs-title function_">join</span>(__dirname, <span class="hljs-string">'local.node'</span>), constants.<span class="hljs-property">dlopen</span>.<span class="hljs-property">RTLD_NOW</span>);
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-title function_">foo</span>();</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.emitWarning(warning[, options])</code><span><a class="mark" href="#all_process_processemitwarningwarning-options" id="all_process_processemitwarningwarning-options">#</a></span><a aria-hidden="true" class="legacy" id="process_process_emitwarning_warning_options"></a></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>warning</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/Reference/Global_Objects/Error" class="type"><Error></a> The warning to emit.</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>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> When <code>warning</code> is a <code>String</code>, <code>type</code> is the name to use
for the <em>type</em> of warning being emitted. <strong>Default:</strong> <code>'Warning'</code>.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A unique identifier for the warning instance being emitted.</li>
<li><code>ctor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> When <code>warning</code> is a <code>String</code>, <code>ctor</code> is an optional
function used to limit the generated stack trace. <strong>Default:</strong>
<code>process.emitWarning</code>.</li>
<li><code>detail</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Additional text to include with the error.</li>
</ul>
</li>
</ul>
<p>The <code>process.emitWarning()</code> method can be used to emit custom or application
specific process warnings. These can be listened for by adding a handler to the
<a href="#all_process_event-warning"><code>'warning'</code></a> event.</p>
<pre class="with-48-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> { emitWarning } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-comment">// Emit a warning with a code and additional detail.</span>
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something happened!'</span>, {
<span class="hljs-attr">code</span>: <span class="hljs-string">'MY_WARNING'</span>,
<span class="hljs-attr">detail</span>: <span class="hljs-string">'This is some additional information'</span>,
});
<span class="hljs-comment">// Emits:</span>
<span class="hljs-comment">// (node:56338) [MY_WARNING] Warning: Something happened!</span>
<span class="hljs-comment">// This is some additional information</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { emitWarning } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-comment">// Emit a warning with a code and additional detail.</span>
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something happened!'</span>, {
<span class="hljs-attr">code</span>: <span class="hljs-string">'MY_WARNING'</span>,
<span class="hljs-attr">detail</span>: <span class="hljs-string">'This is some additional information'</span>,
});
<span class="hljs-comment">// Emits:</span>
<span class="hljs-comment">// (node:56338) [MY_WARNING] Warning: Something happened!</span>
<span class="hljs-comment">// This is some additional information</span></code><button class="copy-button">copy</button></pre>
<p>In this example, an <code>Error</code> object is generated internally by
<code>process.emitWarning()</code> and passed through to the
<a href="#all_process_event-warning"><code>'warning'</code></a> handler.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'warning'</span>, <span class="hljs-function">(<span class="hljs-params">warning</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">name</span>); <span class="hljs-comment">// 'Warning'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">message</span>); <span class="hljs-comment">// 'Something happened!'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">code</span>); <span class="hljs-comment">// 'MY_WARNING'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">stack</span>); <span class="hljs-comment">// Stack trace</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">detail</span>); <span class="hljs-comment">// 'This is some additional information'</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'warning'</span>, <span class="hljs-function">(<span class="hljs-params">warning</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">name</span>); <span class="hljs-comment">// 'Warning'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">message</span>); <span class="hljs-comment">// 'Something happened!'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">code</span>); <span class="hljs-comment">// 'MY_WARNING'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">stack</span>); <span class="hljs-comment">// Stack trace</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">detail</span>); <span class="hljs-comment">// 'This is some additional information'</span>
});</code><button class="copy-button">copy</button></pre>
<p>If <code>warning</code> is passed as an <code>Error</code> object, the <code>options</code> argument is ignored.</p>
</section><section><h3><code>process.emitWarning(warning[, type[, code]][, ctor])</code><span><a class="mark" href="#all_process_processemitwarningwarning-type-code-ctor" id="all_process_processemitwarningwarning-type-code-ctor">#</a></span><a aria-hidden="true" class="legacy" id="process_process_emitwarning_warning_type_code_ctor"></a></h3>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<ul>
<li><code>warning</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/Reference/Global_Objects/Error" class="type"><Error></a> The warning to emit.</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> When <code>warning</code> is a <code>String</code>, <code>type</code> is the name to use
for the <em>type</em> of warning being emitted. <strong>Default:</strong> <code>'Warning'</code>.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A unique identifier for the warning instance being emitted.</li>
<li><code>ctor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> When <code>warning</code> is a <code>String</code>, <code>ctor</code> is an optional
function used to limit the generated stack trace. <strong>Default:</strong>
<code>process.emitWarning</code>.</li>
</ul>
<p>The <code>process.emitWarning()</code> method can be used to emit custom or application
specific process warnings. These can be listened for by adding a handler to the
<a href="#all_process_event-warning"><code>'warning'</code></a> event.</p>
<pre class="with-48-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> { emitWarning } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-comment">// Emit a warning using a string.</span>
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something happened!'</span>);
<span class="hljs-comment">// Emits: (node: 56338) Warning: Something happened!</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { emitWarning } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-comment">// Emit a warning using a string.</span>
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something happened!'</span>);
<span class="hljs-comment">// Emits: (node: 56338) Warning: Something happened!</span></code><button class="copy-button">copy</button></pre>
<pre class="with-48-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> { emitWarning } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-comment">// Emit a warning using a string and a type.</span>
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something Happened!'</span>, <span class="hljs-string">'CustomWarning'</span>);
<span class="hljs-comment">// Emits: (node:56338) CustomWarning: Something Happened!</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { emitWarning } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-comment">// Emit a warning using a string and a type.</span>
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something Happened!'</span>, <span class="hljs-string">'CustomWarning'</span>);
<span class="hljs-comment">// Emits: (node:56338) CustomWarning: Something Happened!</span></code><button class="copy-button">copy</button></pre>
<pre class="with-48-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> { emitWarning } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something happened!'</span>, <span class="hljs-string">'CustomWarning'</span>, <span class="hljs-string">'WARN001'</span>);
<span class="hljs-comment">// Emits: (node:56338) [WARN001] CustomWarning: Something happened!</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { emitWarning } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
process.<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something happened!'</span>, <span class="hljs-string">'CustomWarning'</span>, <span class="hljs-string">'WARN001'</span>);
<span class="hljs-comment">// Emits: (node:56338) [WARN001] CustomWarning: Something happened!</span></code><button class="copy-button">copy</button></pre>
<p>In each of the previous examples, an <code>Error</code> object is generated internally by
<code>process.emitWarning()</code> and passed through to the <a href="#all_process_event-warning"><code>'warning'</code></a>
handler.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'warning'</span>, <span class="hljs-function">(<span class="hljs-params">warning</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">name</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">message</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">code</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">stack</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'warning'</span>, <span class="hljs-function">(<span class="hljs-params">warning</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">name</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">message</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">code</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">stack</span>);
});</code><button class="copy-button">copy</button></pre>
<p>If <code>warning</code> is passed as an <code>Error</code> object, it will be passed through to the
<code>'warning'</code> event handler unmodified (and the optional <code>type</code>,
<code>code</code> and <code>ctor</code> arguments will be ignored):</p>
<pre class="with-48-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> { emitWarning } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-comment">// Emit a warning using an Error object.</span>
<span class="hljs-keyword">const</span> myWarning = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Something happened!'</span>);
<span class="hljs-comment">// Use the Error name property to specify the type name</span>
myWarning.<span class="hljs-property">name</span> = <span class="hljs-string">'CustomWarning'</span>;
myWarning.<span class="hljs-property">code</span> = <span class="hljs-string">'WARN001'</span>;
<span class="hljs-title function_">emitWarning</span>(myWarning);
<span class="hljs-comment">// Emits: (node:56338) [WARN001] CustomWarning: Something happened!</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { emitWarning } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-comment">// Emit a warning using an Error object.</span>
<span class="hljs-keyword">const</span> myWarning = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Something happened!'</span>);
<span class="hljs-comment">// Use the Error name property to specify the type name</span>
myWarning.<span class="hljs-property">name</span> = <span class="hljs-string">'CustomWarning'</span>;
myWarning.<span class="hljs-property">code</span> = <span class="hljs-string">'WARN001'</span>;
<span class="hljs-title function_">emitWarning</span>(myWarning);
<span class="hljs-comment">// Emits: (node:56338) [WARN001] CustomWarning: Something happened!</span></code><button class="copy-button">copy</button></pre>
<p>A <code>TypeError</code> is thrown if <code>warning</code> is anything other than a string or <code>Error</code>
object.</p>
<p>While process warnings use <code>Error</code> objects, the process warning
mechanism is <strong>not</strong> a replacement for normal error handling mechanisms.</p>
<p>The following additional handling is implemented if the warning <code>type</code> is
<code>'DeprecationWarning'</code>:</p>
<ul>
<li>If the <code>--throw-deprecation</code> command-line flag is used, the deprecation
warning is thrown as an exception rather than being emitted as an event.</li>
<li>If the <code>--no-deprecation</code> command-line flag is used, the deprecation
warning is suppressed.</li>
<li>If the <code>--trace-deprecation</code> command-line flag is used, the deprecation
warning is printed to <code>stderr</code> along with the full stack trace.</li>
</ul>
<h4>Avoiding duplicate warnings<span><a class="mark" href="#all_process_avoiding-duplicate-warnings" id="all_process_avoiding-duplicate-warnings">#</a></span><a aria-hidden="true" class="legacy" id="process_avoiding_duplicate_warnings"></a></h4>
<p>As a best practice, warnings should be emitted only once per process. To do
so, place the <code>emitWarning()</code> behind a boolean.</p>
<pre class="with-48-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> { emitWarning } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">emitMyWarning</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">if</span> (!emitMyWarning.<span class="hljs-property">warned</span>) {
emitMyWarning.<span class="hljs-property">warned</span> = <span class="hljs-literal">true</span>;
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Only warn once!'</span>);
}
}
<span class="hljs-title function_">emitMyWarning</span>();
<span class="hljs-comment">// Emits: (node: 56339) Warning: Only warn once!</span>
<span class="hljs-title function_">emitMyWarning</span>();
<span class="hljs-comment">// Emits nothing</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { emitWarning } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">emitMyWarning</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">if</span> (!emitMyWarning.<span class="hljs-property">warned</span>) {
emitMyWarning.<span class="hljs-property">warned</span> = <span class="hljs-literal">true</span>;
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Only warn once!'</span>);
}
}
<span class="hljs-title function_">emitMyWarning</span>();
<span class="hljs-comment">// Emits: (node: 56339) Warning: Only warn once!</span>
<span class="hljs-title function_">emitMyWarning</span>();
<span class="hljs-comment">// Emits nothing</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.env</code><span><a class="mark" href="#all_process_processenv" id="all_process_processenv">#</a></span><a aria-hidden="true" class="legacy" id="process_process_env"></a></h3>
<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>Worker threads will now use a copy of the parent thread's <code>process.env</code> by default, configurable through the <code>env</code> option of the <code>Worker</code> constructor.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Implicit conversion of variable value to string is deprecated.</p></td></tr>
<tr><td>v0.1.27</td>
<td><p><span>Added in: v0.1.27</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>process.env</code> property returns an object containing the user environment.
See <a href="http://man7.org/linux/man-pages/man7/environ.7.html"><code>environ(7)</code></a>.</p>
<p>An example of this object looks like:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
<span class="hljs-attr">TERM</span>: <span class="hljs-string">'xterm-256color'</span>,
<span class="hljs-attr">SHELL</span>: <span class="hljs-string">'/usr/local/bin/bash'</span>,
<span class="hljs-attr">USER</span>: <span class="hljs-string">'maciej'</span>,
<span class="hljs-attr">PATH</span>: <span class="hljs-string">'~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'</span>,
<span class="hljs-attr">PWD</span>: <span class="hljs-string">'/Users/maciej'</span>,
<span class="hljs-attr">EDITOR</span>: <span class="hljs-string">'vim'</span>,
<span class="hljs-attr">SHLVL</span>: <span class="hljs-string">'1'</span>,
<span class="hljs-attr">HOME</span>: <span class="hljs-string">'/Users/maciej'</span>,
<span class="hljs-attr">LOGNAME</span>: <span class="hljs-string">'maciej'</span>,
<span class="hljs-attr">_</span>: <span class="hljs-string">'/usr/local/bin/node'</span>
}</code> <button class="copy-button">copy</button></pre>
<p>It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.
In other words, the following example would not work:</p>
<pre><code class="language-bash">node -e <span class="hljs-string">'process.env.foo = "bar"'</span> && <span class="hljs-built_in">echo</span> <span class="hljs-variable">$foo</span></code> <button class="copy-button">copy</button></pre>
<p>While the following will:</p>
<pre class="with-40-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> { env } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
env.<span class="hljs-property">foo</span> = <span class="hljs-string">'bar'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">foo</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { env } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
env.<span class="hljs-property">foo</span> = <span class="hljs-string">'bar'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">foo</span>);</code><button class="copy-button">copy</button></pre>
<p>Assigning a property on <code>process.env</code> will implicitly convert the value
to a string. <strong>This behavior is deprecated.</strong> Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.</p>
<pre class="with-40-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> { env } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
env.<span class="hljs-property">test</span> = <span class="hljs-literal">null</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">test</span>);
<span class="hljs-comment">// => 'null'</span>
env.<span class="hljs-property">test</span> = <span class="hljs-literal">undefined</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">test</span>);
<span class="hljs-comment">// => 'undefined'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { env } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
env.<span class="hljs-property">test</span> = <span class="hljs-literal">null</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">test</span>);
<span class="hljs-comment">// => 'null'</span>
env.<span class="hljs-property">test</span> = <span class="hljs-literal">undefined</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">test</span>);
<span class="hljs-comment">// => 'undefined'</span></code><button class="copy-button">copy</button></pre>
<p>Use <code>delete</code> to delete a property from <code>process.env</code>.</p>
<pre class="with-40-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> { env } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
env.<span class="hljs-property">TEST</span> = <span class="hljs-number">1</span>;
<span class="hljs-keyword">delete</span> env.<span class="hljs-property">TEST</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">TEST</span>);
<span class="hljs-comment">// => undefined</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { env } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
env.<span class="hljs-property">TEST</span> = <span class="hljs-number">1</span>;
<span class="hljs-keyword">delete</span> env.<span class="hljs-property">TEST</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">TEST</span>);
<span class="hljs-comment">// => undefined</span></code><button class="copy-button">copy</button></pre>
<p>On Windows operating systems, environment variables are case-insensitive.</p>
<pre class="with-40-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> { env } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
env.<span class="hljs-property">TEST</span> = <span class="hljs-number">1</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">test</span>);
<span class="hljs-comment">// => 1</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { env } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
env.<span class="hljs-property">TEST</span> = <span class="hljs-number">1</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">test</span>);
<span class="hljs-comment">// => 1</span></code><button class="copy-button">copy</button></pre>
<p>Unless explicitly specified when creating a <a href="#all_worker_threads_class-worker"><code>Worker</code></a> instance,
each <a href="#all_worker_threads_class-worker"><code>Worker</code></a> thread has its own copy of <code>process.env</code>, based on its
parent thread's <code>process.env</code>, or whatever was specified as the <code>env</code> option
to the <a href="#all_worker_threads_class-worker"><code>Worker</code></a> constructor. Changes to <code>process.env</code> will not be visible
across <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of
<code>process.env</code> on a <a href="#all_worker_threads_class-worker"><code>Worker</code></a> instance operates in a case-sensitive manner
unlike the main thread.</p>
</section><section><h3><code>process.execArgv</code><span><a class="mark" href="#all_process_processexecargv" id="all_process_processexecargv">#</a></span><a aria-hidden="true" class="legacy" id="process_process_execargv"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>The <code>process.execArgv</code> property returns the set of Node.js-specific command-line
options passed when the Node.js process was launched. These options do not
appear in the array returned by the <a href="#all_process_processargv"><code>process.argv</code></a> property, and do not
include the Node.js executable, the name of the script, or any options following
the script name. These options are useful in order to spawn child processes with
the same execution environment as the parent.</p>
<pre><code class="language-bash">node --icu-data-dir=./foo --require ./bar.js script.js --version</code> <button class="copy-button">copy</button></pre>
<p>Results in <code>process.execArgv</code>:</p>
<pre><code class="language-json"><span class="hljs-punctuation">[</span><span class="hljs-string">"--icu-data-dir=./foo"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"--require"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"./bar.js"</span><span class="hljs-punctuation">]</span></code> <button class="copy-button">copy</button></pre>
<p>And <code>process.argv</code>:</p>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js">[<span class="hljs-string">'/usr/local/bin/node'</span>, <span class="hljs-string">'script.js'</span>, <span class="hljs-string">'--version'</span>]</code> <button class="copy-button">copy</button></pre>
<p>Refer to <a href="#all_worker_threads_new-workerfilename-options"><code>Worker</code> constructor</a> for the detailed behavior of worker
threads with this property.</p>
</section><section><h3><code>process.execPath</code><span><a class="mark" href="#all_process_processexecpath" id="all_process_processexecpath">#</a></span><a aria-hidden="true" class="legacy" id="process_process_execpath"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>process.execPath</code> property returns the absolute pathname of the executable
that started the Node.js process. Symbolic links, if any, are resolved.</p>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js"><span class="hljs-string">'/usr/local/bin/node'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>process.exit([code])</code><span><a class="mark" href="#all_process_processexitcode" id="all_process_processexitcode">#</a></span><a aria-hidden="true" class="legacy" id="process_process_exit_code"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Only accepts a code of type number, or of type string if it represents an integer.</p></td></tr>
<tr><td>v0.1.13</td>
<td><p><span>Added in: v0.1.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></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#Undefined_type" class="type"><undefined></a> The exit code. For string type, only
integer strings (e.g.,'1') are allowed. <strong>Default:</strong> <code>0</code>.</li>
</ul>
<p>The <code>process.exit()</code> method instructs Node.js to terminate the process
synchronously with an exit status of <code>code</code>. If <code>code</code> is omitted, exit uses
either the 'success' code <code>0</code> or the value of <code>process.exitCode</code> if it has been
set. Node.js will not terminate until all the <a href="#all_process_event-exit"><code>'exit'</code></a> event listeners are
called.</p>
<p>To exit with a 'failure' code:</p>
<pre class="with-41-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> { exit } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { exit } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>);</code><button class="copy-button">copy</button></pre>
<p>The shell that executed Node.js should see the exit code as <code>1</code>.</p>
<p>Calling <code>process.exit()</code> will force the process to exit as quickly as possible
even if there are still asynchronous operations pending that have not yet
completed fully, including I/O operations to <code>process.stdout</code> and
<code>process.stderr</code>.</p>
<p>In most situations, it is not actually necessary to call <code>process.exit()</code>
explicitly. The Node.js process will exit on its own <em>if there is no additional
work pending</em> in the event loop. The <code>process.exitCode</code> property can be set to
tell the process which exit code to use when the process exits gracefully.</p>
<p>For instance, the following example illustrates a <em>misuse</em> of the
<code>process.exit()</code> method that could lead to data printed to stdout being
truncated and lost:</p>
<pre class="with-41-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> { exit } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-comment">// This is an example of what *not* to do:</span>
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">someConditionNotMet</span>()) {
<span class="hljs-title function_">printUsageToStdout</span>();
<span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { exit } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-comment">// This is an example of what *not* to do:</span>
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">someConditionNotMet</span>()) {
<span class="hljs-title function_">printUsageToStdout</span>();
<span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>);
}</code><button class="copy-button">copy</button></pre>
<p>The reason this is problematic is because writes to <code>process.stdout</code> in Node.js
are sometimes <em>asynchronous</em> and may occur over multiple ticks of the Node.js
event loop. Calling <code>process.exit()</code>, however, forces the process to exit
<em>before</em> those additional writes to <code>stdout</code> can be performed.</p>
<p>Rather than calling <code>process.exit()</code> directly, the code <em>should</em> set the
<code>process.exitCode</code> and allow the process to exit naturally by avoiding
scheduling any additional work for the event loop:</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-comment">// How to properly set the exit code while letting</span>
<span class="hljs-comment">// the process exit gracefully.</span>
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">someConditionNotMet</span>()) {
<span class="hljs-title function_">printUsageToStdout</span>();
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-comment">// How to properly set the exit code while letting</span>
<span class="hljs-comment">// the process exit gracefully.</span>
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">someConditionNotMet</span>()) {
<span class="hljs-title function_">printUsageToStdout</span>();
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}</code><button class="copy-button">copy</button></pre>
<p>If it is necessary to terminate the Node.js process due to an error condition,
throwing an <em>uncaught</em> error and allowing the process to terminate accordingly
is safer than calling <code>process.exit()</code>.</p>
<p>In <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads, this function stops the current thread rather
than the current process.</p>
</section><section><h3><code>process.exitCode</code><span><a class="mark" href="#all_process_processexitcode_1" id="all_process_processexitcode_1">#</a></span><a aria-hidden="true" class="legacy" id="process_process_exitcode"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Only accepts a code of type number, or of type string if it represents an integer.</p></td></tr>
<tr><td>v0.11.8</td>
<td><p><span>Added in: v0.11.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></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#Undefined_type" class="type"><undefined></a> The exit code. For string type, only
integer strings (e.g.,'1') are allowed. <strong>Default:</strong> <code>undefined</code>.</li>
</ul>
<p>A number which will be the process exit code, when the process either
exits gracefully, or is exited via <a href="#all_process_processexitcode"><code>process.exit()</code></a> without specifying
a code.</p>
<p>Specifying a code to <a href="#all_process_processexitcode"><code>process.exit(code)</code></a> will override any
previous setting of <code>process.exitCode</code>.</p>
</section><section><h3><code>process.features.cached_builtins</code><span><a class="mark" href="#all_process_processfeaturescached_builtins" id="all_process_processfeaturescached_builtins">#</a></span><a aria-hidden="true" class="legacy" id="process_process_features_cached_builtins"></a></h3>
<div class="api_metadata">
<span>Added in: v12.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>A boolean value that is <code>true</code> if the current Node.js build is caching builtin modules.</p>
</section><section><h3><code>process.features.debug</code><span><a class="mark" href="#all_process_processfeaturesdebug" id="all_process_processfeaturesdebug">#</a></span><a aria-hidden="true" class="legacy" id="process_process_features_debug"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.5</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>A boolean value that is <code>true</code> if the current Node.js build is a debug build.</p>
</section><section><h3><code>process.features.inspector</code><span><a class="mark" href="#all_process_processfeaturesinspector" id="all_process_processfeaturesinspector">#</a></span><a aria-hidden="true" class="legacy" id="process_process_features_inspector"></a></h3>
<div class="api_metadata">
<span>Added in: v11.10.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>A boolean value that is <code>true</code> if the current Node.js build includes the inspector.</p>
</section><section><h3><code>process.features.ipv6</code><span><a class="mark" href="#all_process_processfeaturesipv6" id="all_process_processfeaturesipv6">#</a></span><a aria-hidden="true" class="legacy" id="process_process_features_ipv6"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.3</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>A boolean value that is <code>true</code> if the current Node.js build includes support for IPv6.</p>
</section><section><h3><code>process.features.require_module</code><span><a class="mark" href="#all_process_processfeaturesrequire_module" id="all_process_processfeaturesrequire_module">#</a></span><a aria-hidden="true" class="legacy" id="process_process_features_require_module"></a></h3>
<div class="api_metadata">
<span>Added in: v20.19.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>A boolean value that is <code>true</code> if the current Node.js build supports
<a href="#all_modules_loading-ecmascript-modules-using-require">loading ECMAScript modules using <code>require()</code></a>.</p>
</section><section><h3><code>process.features.tls</code><span><a class="mark" href="#all_process_processfeaturestls" id="all_process_processfeaturestls">#</a></span><a aria-hidden="true" class="legacy" id="process_process_features_tls"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.3</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>A boolean value that is <code>true</code> if the current Node.js build includes support for TLS.</p>
</section><section><h3><code>process.features.tls_alpn</code><span><a class="mark" href="#all_process_processfeaturestls_alpn" id="all_process_processfeaturestls_alpn">#</a></span><a aria-hidden="true" class="legacy" id="process_process_features_tls_alpn"></a></h3>
<div class="api_metadata">
<span>Added in: v4.8.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>A boolean value that is <code>true</code> if the current Node.js build includes support for ALPN in TLS.</p>
<hr>
</section><section><h3><code>process.features.tls_ocsp</code><span><a class="mark" href="#all_process_processfeaturestls_ocsp" id="all_process_processfeaturestls_ocsp">#</a></span><a aria-hidden="true" class="legacy" id="process_process_features_tls_ocsp"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.13</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>A boolean value that is <code>true</code> if the current Node.js build includes support for OCSP in TLS.</p>
<hr>
</section><section><h3><code>process.features.tls_sni</code><span><a class="mark" href="#all_process_processfeaturestls_sni" id="all_process_processfeaturestls_sni">#</a></span><a aria-hidden="true" class="legacy" id="process_process_features_tls_sni"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.3</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>A boolean value that is <code>true</code> if the current Node.js build includes support for SNI in TLS.</p>
<hr>
</section><section><h3><code>process.features.uv</code><span><a class="mark" href="#all_process_processfeaturesuv" id="all_process_processfeaturesuv">#</a></span><a aria-hidden="true" class="legacy" id="process_process_features_uv"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.3</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>A boolean value that is <code>true</code> if the current Node.js build includes support for libuv.
Since it's currently not possible to build Node.js without libuv, this value is always <code>true</code>.</p>
</section><section><h3><code>process.getActiveResourcesInfo()</code><span><a class="mark" href="#all_process_processgetactiveresourcesinfo" id="all_process_processgetactiveresourcesinfo">#</a></span><a aria-hidden="true" class="legacy" id="process_process_getactiveresourcesinfo"></a></h3>
<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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>The <code>process.getActiveResourcesInfo()</code> method returns an array of strings
containing the types of the active resources that are currently keeping the
event loop alive.</p>
<pre class="with-59-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> { getActiveResourcesInfo } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-built_in">setTimeout</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Before:'</span>, <span class="hljs-title function_">getActiveResourcesInfo</span>());
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">1000</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'After:'</span>, <span class="hljs-title function_">getActiveResourcesInfo</span>());
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// Before: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap' ]</span>
<span class="hljs-comment">// After: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { getActiveResourcesInfo } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-built_in">setTimeout</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Before:'</span>, <span class="hljs-title function_">getActiveResourcesInfo</span>());
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">1000</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'After:'</span>, <span class="hljs-title function_">getActiveResourcesInfo</span>());
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ]</span>
<span class="hljs-comment">// After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.getBuiltinModule(id)</code><span><a class="mark" href="#all_process_processgetbuiltinmoduleid" id="all_process_processgetbuiltinmoduleid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_getbuiltinmodule_id"></a></h3>
<div class="api_metadata">
<span>Added in: v20.16.0</span>
</div>
<ul>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> ID of the built-in module being requested.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
</ul>
<p><code>process.getBuiltinModule(id)</code> provides a way to load built-in modules
in a globally available function. ES Modules that need to support
other environments can use it to conditionally load a Node.js built-in
when it is run in Node.js, without having to deal with the resolution
error that can be thrown by <code>import</code> in a non-Node.js environment or
having to use dynamic <code>import()</code> which either turns the module into
an asynchronous module, or turns a synchronous API into an asynchronous one.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">if</span> (globalThis.<span class="hljs-property">process</span>?.<span class="hljs-property">getBuiltinModule</span>) {
<span class="hljs-comment">// Run in Node.js, use the Node.js fs module.</span>
<span class="hljs-keyword">const</span> fs = globalThis.<span class="hljs-property">process</span>.<span class="hljs-title function_">getBuiltinModule</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-comment">// If `require()` is needed to load user-modules, use createRequire()</span>
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = globalThis.<span class="hljs-property">process</span>.<span class="hljs-title function_">getBuiltinModule</span>(<span class="hljs-string">'module'</span>);
<span class="hljs-keyword">const</span> <span class="hljs-built_in">require</span> = <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">createRequire</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
<span class="hljs-keyword">const</span> foo = <span class="hljs-built_in">require</span>(<span class="hljs-string">'foo'</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>If <code>id</code> specifies a built-in module available in the current Node.js process,
<code>process.getBuiltinModule(id)</code> method returns the corresponding built-in
module. If <code>id</code> does not correspond to any built-in module, <code>undefined</code>
is returned.</p>
<p><code>process.getBuiltinModule(id)</code> accepts built-in module IDs that are recognized
by <a href="#all_module_moduleisbuiltinmodulename"><code>module.isBuiltin(id)</code></a>. Some built-in modules must be loaded with the
<code>node:</code> prefix, see <a href="#all_modules_built-in-modules-with-mandatory-node-prefix">built-in modules with mandatory <code>node:</code> prefix</a>.
The references returned by <code>process.getBuiltinModule(id)</code> always point to
the built-in module corresponding to <code>id</code> even if users modify
<a href="#all_modules_requirecache"><code>require.cache</code></a> so that <code>require(id)</code> returns something else.</p>
</section><section><h3><code>process.getegid()</code><span><a class="mark" href="#all_process_processgetegid" id="all_process_processgetegid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_getegid"></a></h3>
<div class="api_metadata">
<span>Added in: v2.0.0</span>
</div>
<p>The <code>process.getegid()</code> method returns the numerical effective group identity
of the Node.js process. (See <a href="http://man7.org/linux/man-pages/man2/getegid.2.html"><code>getegid(2)</code></a>.)</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getegid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getegid()}</span>`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getegid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getegid()}</span>`</span>);
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
</section><section><h3><code>process.geteuid()</code><span><a class="mark" href="#all_process_processgeteuid" id="all_process_processgeteuid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_geteuid"></a></h3>
<div class="api_metadata">
<span>Added in: v2.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>process.geteuid()</code> method returns the numerical effective user identity of
the process. (See <a href="http://man7.org/linux/man-pages/man2/geteuid.2.html"><code>geteuid(2)</code></a>.)</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">geteuid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.geteuid()}</span>`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">geteuid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.geteuid()}</span>`</span>);
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
</section><section><h3><code>process.getgid()</code><span><a class="mark" href="#all_process_processgetgid" id="all_process_processgetgid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_getgid"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>process.getgid()</code> method returns the numerical group identity of the
process. (See <a href="http://man7.org/linux/man-pages/man2/getgid.2.html"><code>getgid(2)</code></a>.)</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getgid()}</span>`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getgid()}</span>`</span>);
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
</section><section><h3><code>process.getgroups()</code><span><a class="mark" href="#all_process_processgetgroups" id="all_process_processgetgroups">#</a></span><a aria-hidden="true" class="legacy" id="process_process_getgroups"></a></h3>
<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/Data_structures#Number_type" class="type"><integer[]></a></li>
</ul>
<p>The <code>process.getgroups()</code> method returns an array with the supplementary group
IDs. POSIX leaves it unspecified if the effective group ID is included but
Node.js ensures it always is.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgroups</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// [ 16, 21, 297 ]</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgroups</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// [ 16, 21, 297 ]</span>
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
</section><section><h3><code>process.getuid()</code><span><a class="mark" href="#all_process_processgetuid" id="all_process_processgetuid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_getuid"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.28</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>The <code>process.getuid()</code> method returns the numeric user identity of the process.
(See <a href="http://man7.org/linux/man-pages/man2/getuid.2.html"><code>getuid(2)</code></a>.)</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getuid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.getuid()}</span>`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getuid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.getuid()}</span>`</span>);
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
</section><section><h3><code>process.hasUncaughtExceptionCaptureCallback()</code><span><a class="mark" href="#all_process_processhasuncaughtexceptioncapturecallback" id="all_process_processhasuncaughtexceptioncapturecallback">#</a></span><a aria-hidden="true" class="legacy" id="process_process_hasuncaughtexceptioncapturecallback"></a></h3>
<div class="api_metadata">
<span>Added in: v9.3.0</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>Indicates whether a callback has been set using
<a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback()</code></a>.</p>
</section><section><h3><code>process.hrtime([time])</code><span><a class="mark" href="#all_process_processhrtimetime" id="all_process_processhrtimetime">#</a></span><a aria-hidden="true" class="legacy" id="process_process_hrtime_time"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.6</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy. Use <a href="#all_process_processhrtimebigint"><code>process.hrtime.bigint()</code></a> instead.</div><p></p>
<ul>
<li><code>time</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a> The result of a previous call to <code>process.hrtime()</code></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>This is the legacy version of <a href="#all_process_processhrtimebigint"><code>process.hrtime.bigint()</code></a>
before <code>bigint</code> was introduced in JavaScript.</p>
<p>The <code>process.hrtime()</code> method returns the current high-resolution real time
in a <code>[seconds, nanoseconds]</code> tuple <code>Array</code>, where <code>nanoseconds</code> is the
remaining part of the real time that can't be represented in second precision.</p>
<p><code>time</code> is an optional parameter that must be the result of a previous
<code>process.hrtime()</code> call to diff with the current time. If the parameter
passed in is not a tuple <code>Array</code>, a <code>TypeError</code> will be thrown. Passing in a
user-defined array instead of the result of a previous call to
<code>process.hrtime()</code> will lead to undefined behavior.</p>
<p>These times are relative to an arbitrary time in the
past, and not related to the time of day and therefore not subject to clock
drift. The primary use is for measuring performance between intervals:</p>
<pre class="with-43-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> { hrtime } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">NS_PER_SEC</span> = <span class="hljs-number">1e9</span>;
<span class="hljs-keyword">const</span> time = <span class="hljs-title function_">hrtime</span>();
<span class="hljs-comment">// [ 1800216, 25 ]</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> diff = <span class="hljs-title function_">hrtime</span>(time);
<span class="hljs-comment">// [ 1, 552 ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Benchmark took <span class="hljs-subst">${diff[<span class="hljs-number">0</span>] * NS_PER_SEC + diff[<span class="hljs-number">1</span>]}</span> nanoseconds`</span>);
<span class="hljs-comment">// Benchmark took 1000000552 nanoseconds</span>
}, <span class="hljs-number">1000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { hrtime } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">NS_PER_SEC</span> = <span class="hljs-number">1e9</span>;
<span class="hljs-keyword">const</span> time = <span class="hljs-title function_">hrtime</span>();
<span class="hljs-comment">// [ 1800216, 25 ]</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> diff = <span class="hljs-title function_">hrtime</span>(time);
<span class="hljs-comment">// [ 1, 552 ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Benchmark took <span class="hljs-subst">${diff[<span class="hljs-number">0</span>] * NS_PER_SEC + diff[<span class="hljs-number">1</span>]}</span> nanoseconds`</span>);
<span class="hljs-comment">// Benchmark took 1000000552 nanoseconds</span>
}, <span class="hljs-number">1000</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.hrtime.bigint()</code><span><a class="mark" href="#all_process_processhrtimebigint" id="all_process_processhrtimebigint">#</a></span><a aria-hidden="true" class="legacy" id="process_process_hrtime_bigint"></a></h3>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a></li>
</ul>
<p>The <code>bigint</code> version of the <a href="#all_process_processhrtimetime"><code>process.hrtime()</code></a> method returning the
current high-resolution real time in nanoseconds as a <code>bigint</code>.</p>
<p>Unlike <a href="#all_process_processhrtimetime"><code>process.hrtime()</code></a>, it does not support an additional <code>time</code>
argument since the difference can just be computed directly
by subtraction of the two <code>bigint</code>s.</p>
<pre class="with-43-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> { hrtime } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> start = hrtime.<span class="hljs-title function_">bigint</span>();
<span class="hljs-comment">// 191051479007711n</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> end = hrtime.<span class="hljs-title function_">bigint</span>();
<span class="hljs-comment">// 191052633396993n</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Benchmark took <span class="hljs-subst">${end - start}</span> nanoseconds`</span>);
<span class="hljs-comment">// Benchmark took 1154389282 nanoseconds</span>
}, <span class="hljs-number">1000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { hrtime } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> start = hrtime.<span class="hljs-title function_">bigint</span>();
<span class="hljs-comment">// 191051479007711n</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> end = hrtime.<span class="hljs-title function_">bigint</span>();
<span class="hljs-comment">// 191052633396993n</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Benchmark took <span class="hljs-subst">${end - start}</span> nanoseconds`</span>);
<span class="hljs-comment">// Benchmark took 1154389282 nanoseconds</span>
}, <span class="hljs-number">1000</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.initgroups(user, extraGroup)</code><span><a class="mark" href="#all_process_processinitgroupsuser-extragroup" id="all_process_processinitgroupsuser-extragroup">#</a></span><a aria-hidden="true" class="legacy" id="process_process_initgroups_user_extragroup"></a></h3>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>user</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#Number_type" class="type"><number></a> The user name or numeric identifier.</li>
<li><code>extraGroup</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#Number_type" class="type"><number></a> A group name or numeric identifier.</li>
</ul>
<p>The <code>process.initgroups()</code> method reads the <code>/etc/group</code> file and initializes
the group access list, using all groups of which the user is a member. This is
a privileged operation that requires that the Node.js process either have <code>root</code>
access or the <code>CAP_SETGID</code> capability.</p>
<p>Use care when dropping privileges:</p>
<pre class="with-66-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> { getgroups, initgroups, setgid } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// [ 0 ]</span>
<span class="hljs-title function_">initgroups</span>(<span class="hljs-string">'nodeuser'</span>, <span class="hljs-number">1000</span>); <span class="hljs-comment">// switch user</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// [ 27, 30, 46, 1000, 0 ]</span>
<span class="hljs-title function_">setgid</span>(<span class="hljs-number">1000</span>); <span class="hljs-comment">// drop root gid</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// [ 27, 30, 46, 1000 ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { getgroups, initgroups, setgid } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// [ 0 ]</span>
<span class="hljs-title function_">initgroups</span>(<span class="hljs-string">'nodeuser'</span>, <span class="hljs-number">1000</span>); <span class="hljs-comment">// switch user</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// [ 27, 30, 46, 1000, 0 ]</span>
<span class="hljs-title function_">setgid</span>(<span class="hljs-number">1000</span>); <span class="hljs-comment">// drop root gid</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// [ 27, 30, 46, 1000 ]</span></code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.kill(pid[, signal])</code><span><a class="mark" href="#all_process_processkillpid-signal" id="all_process_processkillpid-signal">#</a></span><a aria-hidden="true" class="legacy" id="process_process_kill_pid_signal"></a></h3>
<div class="api_metadata">
<span>Added in: v0.0.6</span>
</div>
<ul>
<li><code>pid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A process ID</li>
<li><code>signal</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#Number_type" class="type"><number></a> The signal to send, either as a string or number.
<strong>Default:</strong> <code>'SIGTERM'</code>.</li>
</ul>
<p>The <code>process.kill()</code> method sends the <code>signal</code> to the process identified by
<code>pid</code>.</p>
<p>Signal names are strings such as <code>'SIGINT'</code> or <code>'SIGHUP'</code>. See <a href="#all_process_signal-events">Signal Events</a>
and <a href="http://man7.org/linux/man-pages/man2/kill.2.html"><code>kill(2)</code></a> for more information.</p>
<p>This method will throw an error if the target <code>pid</code> does not exist. As a special
case, a signal of <code>0</code> can be used to test for the existence of a process.
Windows platforms will throw an error if the <code>pid</code> is used to kill a process
group.</p>
<p>Even though the name of this function is <code>process.kill()</code>, it is really just a
signal sender, like the <code>kill</code> system call. The signal sent may do something
other than kill the target process.</p>
<pre class="with-45-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> process, { kill } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGHUP'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Got SIGHUP signal.'</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">'Exiting.'</span>);
process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">0</span>);
}, <span class="hljs-number">100</span>);
<span class="hljs-title function_">kill</span>(process.<span class="hljs-property">pid</span>, <span class="hljs-string">'SIGHUP'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGHUP'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Got SIGHUP signal.'</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">'Exiting.'</span>);
process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">0</span>);
}, <span class="hljs-number">100</span>);
process.<span class="hljs-title function_">kill</span>(process.<span class="hljs-property">pid</span>, <span class="hljs-string">'SIGHUP'</span>);</code><button class="copy-button">copy</button></pre>
<p>When <code>SIGUSR1</code> is received by a Node.js process, Node.js will start the
debugger. See <a href="#all_process_signal-events">Signal Events</a>.</p>
</section><section><h3><code>process.loadEnvFile(path)</code><span><a class="mark" href="#all_process_processloadenvfilepath" id="all_process_processloadenvfilepath">#</a></span><a aria-hidden="true" class="legacy" id="process_process_loadenvfile_path"></a></h3>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a>. <strong>Default:</strong> <code>'./.env'</code></li>
</ul>
<p>Loads the <code>.env</code> file into <code>process.env</code>. Usage of <code>NODE_OPTIONS</code>
in the <code>.env</code> file will not have any effect on Node.js.</p>
<pre class="with-48-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> { loadEnvFile } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-title function_">loadEnvFile</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { loadEnvFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-title function_">loadEnvFile</span>();</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.mainModule</code><span><a class="mark" href="#all_process_processmainmodule" id="all_process_processmainmodule">#</a></span><a aria-hidden="true" class="legacy" id="process_process_mainmodule"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.17</span><span>Deprecated since: v14.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_modules_accessing-the-main-module"><code>require.main</code></a> instead.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>process.mainModule</code> property provides an alternative way of retrieving
<a href="#all_modules_accessing-the-main-module"><code>require.main</code></a>. The difference is that if the main module changes at
runtime, <a href="#all_modules_accessing-the-main-module"><code>require.main</code></a> may still refer to the original main module in
modules that were required before the change occurred. Generally, it's
safe to assume that the two refer to the same module.</p>
<p>As with <a href="#all_modules_accessing-the-main-module"><code>require.main</code></a>, <code>process.mainModule</code> will be <code>undefined</code> if there
is no entry script.</p>
</section><section><h3><code>process.memoryUsage()</code><span><a class="mark" href="#all_process_processmemoryusage" id="all_process_processmemoryusage">#</a></span><a aria-hidden="true" class="legacy" id="process_process_memoryusage"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.9.0, v12.17.0</td>
<td><p>Added <code>arrayBuffers</code> to the returned object.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>Added <code>external</code> to the returned object.</p></td></tr>
<tr><td>v0.1.16</td>
<td><p><span>Added in: v0.1.16</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>rss</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>heapTotal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>heapUsed</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>external</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>arrayBuffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
</li>
</ul>
<p>Returns an object describing the memory usage of the Node.js process measured in
bytes.</p>
<pre class="with-48-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> { memoryUsage } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">memoryUsage</span>());
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">// rss: 4935680,</span>
<span class="hljs-comment">// heapTotal: 1826816,</span>
<span class="hljs-comment">// heapUsed: 650472,</span>
<span class="hljs-comment">// external: 49879,</span>
<span class="hljs-comment">// arrayBuffers: 9386</span>
<span class="hljs-comment">// }</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { memoryUsage } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">memoryUsage</span>());
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">// rss: 4935680,</span>
<span class="hljs-comment">// heapTotal: 1826816,</span>
<span class="hljs-comment">// heapUsed: 650472,</span>
<span class="hljs-comment">// external: 49879,</span>
<span class="hljs-comment">// arrayBuffers: 9386</span>
<span class="hljs-comment">// }</span></code><button class="copy-button">copy</button></pre>
<ul>
<li><code>heapTotal</code> and <code>heapUsed</code> refer to V8's memory usage.</li>
<li><code>external</code> refers to the memory usage of C++ objects bound to JavaScript
objects managed by V8.</li>
<li><code>rss</code>, Resident Set Size, is the amount of space occupied in the main
memory device (that is a subset of the total allocated memory) for the
process, including all C++ and JavaScript objects and code.</li>
<li><code>arrayBuffers</code> refers to memory allocated for <code>ArrayBuffer</code>s and
<code>SharedArrayBuffer</code>s, including all Node.js <a href="buffer.html"><code>Buffer</code></a>s.
This is also included in the <code>external</code> value. When Node.js is used as an
embedded library, this value may be <code>0</code> because allocations for <code>ArrayBuffer</code>s
may not be tracked in that case.</li>
</ul>
<p>When using <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads, <code>rss</code> will be a value that is valid for the
entire process, while the other fields will only refer to the current thread.</p>
<p>The <code>process.memoryUsage()</code> method iterates over each page to gather
information about memory usage which might be slow depending on the
program memory allocations.</p>
</section><section><h3><code>process.memoryUsage.rss()</code><span><a class="mark" href="#all_process_processmemoryusagerss" id="all_process_processmemoryusagerss">#</a></span><a aria-hidden="true" class="legacy" id="process_process_memoryusage_rss"></a></h3>
<div class="api_metadata">
<span>Added in: v15.6.0, v14.18.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>The <code>process.memoryUsage.rss()</code> method returns an integer representing the
Resident Set Size (RSS) in bytes.</p>
<p>The Resident Set Size, is the amount of space occupied in the main
memory device (that is a subset of the total allocated memory) for the
process, including all C++ and JavaScript objects and code.</p>
<p>This is the same value as the <code>rss</code> property provided by <code>process.memoryUsage()</code>
but <code>process.memoryUsage.rss()</code> is faster.</p>
<pre class="with-48-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> { memoryUsage } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(memoryUsage.<span class="hljs-title function_">rss</span>());
<span class="hljs-comment">// 35655680</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { memoryUsage } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(memoryUsage.<span class="hljs-title function_">rss</span>());
<span class="hljs-comment">// 35655680</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.nextTick(callback[, ...args])</code><span><a class="mark" href="#all_process_processnexttickcallback-args" id="all_process_processnexttickcallback-args">#</a></span><a aria-hidden="true" class="legacy" id="process_process_nexttick_callback_args"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>Changed stability to Legacy.</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>v1.8.1</td>
<td><p>Additional arguments after <code>callback</code> are now supported.</p></td></tr>
<tr><td>v0.1.26</td>
<td><p><span>Added in: v0.1.26</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_globals_queuemicrotaskcallback"><code>queueMicrotask()</code></a> instead.</div><p></p>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Additional arguments to pass when invoking the <code>callback</code></li>
</ul>
<p><code>process.nextTick()</code> adds <code>callback</code> to the "next tick queue". This queue is
fully drained after the current operation on the JavaScript stack runs to
completion and before the event loop is allowed to continue. It's possible to
create an infinite loop if one were to recursively call <code>process.nextTick()</code>.
See the <a href="https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick#understanding-processnexttick">Event Loop</a> guide for more background.</p>
<pre class="with-45-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> { nextTick } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'start'</span>);
<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'nextTick callback'</span>);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'scheduled'</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// start</span>
<span class="hljs-comment">// scheduled</span>
<span class="hljs-comment">// nextTick callback</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { nextTick } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'start'</span>);
<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'nextTick callback'</span>);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'scheduled'</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// start</span>
<span class="hljs-comment">// scheduled</span>
<span class="hljs-comment">// nextTick callback</span></code><button class="copy-button">copy</button></pre>
<p>This is important when developing APIs in order to give users the opportunity
to assign event handlers <em>after</em> an object has been constructed but before any
I/O has occurred:</p>
<pre class="with-45-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> { nextTick } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyThing</span>(<span class="hljs-params">options</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">setupOptions</span>(options);
<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">startDoingStuff</span>();
});
}
<span class="hljs-keyword">const</span> thing = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyThing</span>();
thing.<span class="hljs-title function_">getReadyForStuff</span>();
<span class="hljs-comment">// thing.startDoingStuff() gets called now, not before.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { nextTick } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyThing</span>(<span class="hljs-params">options</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">setupOptions</span>(options);
<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">startDoingStuff</span>();
});
}
<span class="hljs-keyword">const</span> thing = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyThing</span>();
thing.<span class="hljs-title function_">getReadyForStuff</span>();
<span class="hljs-comment">// thing.startDoingStuff() gets called now, not before.</span></code><button class="copy-button">copy</button></pre>
<p>It is very important for APIs to be either 100% synchronous or 100%
asynchronous. Consider this example:</p>
<pre><code class="language-js"><span class="hljs-comment">// WARNING! DO NOT USE! BAD UNSAFE HAZARD!</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">maybeSync</span>(<span class="hljs-params">arg, cb</span>) {
<span class="hljs-keyword">if</span> (arg) {
<span class="hljs-title function_">cb</span>();
<span class="hljs-keyword">return</span>;
}
fs.<span class="hljs-title function_">stat</span>(<span class="hljs-string">'file'</span>, cb);
}</code> <button class="copy-button">copy</button></pre>
<p>This API is hazardous because in the following case:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> maybeTrue = <span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() > <span class="hljs-number">0.5</span>;
<span class="hljs-title function_">maybeSync</span>(maybeTrue, <span class="hljs-function">() =></span> {
<span class="hljs-title function_">foo</span>();
});
<span class="hljs-title function_">bar</span>();</code> <button class="copy-button">copy</button></pre>
<p>It is not clear whether <code>foo()</code> or <code>bar()</code> will be called first.</p>
<p>The following approach is much better:</p>
<pre class="with-45-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> { nextTick } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">definitelyAsync</span>(<span class="hljs-params">arg, cb</span>) {
<span class="hljs-keyword">if</span> (arg) {
<span class="hljs-title function_">nextTick</span>(cb);
<span class="hljs-keyword">return</span>;
}
fs.<span class="hljs-title function_">stat</span>(<span class="hljs-string">'file'</span>, cb);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { nextTick } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">definitelyAsync</span>(<span class="hljs-params">arg, cb</span>) {
<span class="hljs-keyword">if</span> (arg) {
<span class="hljs-title function_">nextTick</span>(cb);
<span class="hljs-keyword">return</span>;
}
fs.<span class="hljs-title function_">stat</span>(<span class="hljs-string">'file'</span>, cb);
}</code><button class="copy-button">copy</button></pre>
<h4>When to use <code>queueMicrotask()</code> vs. <code>process.nextTick()</code><span><a class="mark" href="#all_process_when-to-use-queuemicrotask-vs-processnexttick" id="all_process_when-to-use-queuemicrotask-vs-processnexttick">#</a></span><a aria-hidden="true" class="legacy" id="process_when_to_use_queuemicrotask_vs_process_nexttick"></a></h4>
<p>The <a href="#all_globals_queuemicrotaskcallback"><code>queueMicrotask()</code></a> API is an alternative to <code>process.nextTick()</code> that instead of using the
"next tick queue" defers execution of a function using the same microtask queue used to execute the
then, catch, and finally handlers of resolved promises.</p>
<p>Within Node.js, every time the "next tick queue" is drained, the microtask queue
is drained immediately after.</p>
<p>So in CJS modules <code>process.nextTick()</code> callbacks are always run before <code>queueMicrotask()</code> ones.
However since ESM modules are processed already as part of the microtask queue, there
<code>queueMicrotask()</code> callbacks are always exectued before <code>process.nextTick()</code> ones since Node.js
is already in the process of draining the microtask queue.</p>
<pre class="with-45-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> { nextTick } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'resolve'</span>));
<span class="hljs-title function_">queueMicrotask</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'microtask'</span>));
<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'nextTick'</span>));
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// resolve</span>
<span class="hljs-comment">// microtask</span>
<span class="hljs-comment">// nextTick</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { nextTick } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'resolve'</span>));
<span class="hljs-title function_">queueMicrotask</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'microtask'</span>));
<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'nextTick'</span>));
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// nextTick</span>
<span class="hljs-comment">// resolve</span>
<span class="hljs-comment">// microtask</span></code><button class="copy-button">copy</button></pre>
<p>For <em>most</em> userland use cases, the <code>queueMicrotask()</code> API provides a portable
and reliable mechanism for deferring execution that works across multiple
JavaScript platform environments and should be favored over <code>process.nextTick()</code>.
In simple scenarios, <code>queueMicrotask()</code> can be a drop-in replacement for
<code>process.nextTick()</code>.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'start'</span>);
<span class="hljs-title function_">queueMicrotask</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'microtask callback'</span>);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'scheduled'</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// start</span>
<span class="hljs-comment">// scheduled</span>
<span class="hljs-comment">// microtask callback</span></code> <button class="copy-button">copy</button></pre>
<p>One note-worthy difference between the two APIs is that <code>process.nextTick()</code>
allows specifying additional values that will be passed as arguments to the
deferred function when it is called. Achieving the same result with
<code>queueMicrotask()</code> requires using either a closure or a bound function:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">deferred</span>(<span class="hljs-params">a, b</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'microtask'</span>, a + b);
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'start'</span>);
<span class="hljs-title function_">queueMicrotask</span>(deferred.<span class="hljs-title function_">bind</span>(<span class="hljs-literal">undefined</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'scheduled'</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// start</span>
<span class="hljs-comment">// scheduled</span>
<span class="hljs-comment">// microtask 3</span></code> <button class="copy-button">copy</button></pre>
<p>There are minor differences in the way errors raised from within the next tick
queue and microtask queue are handled. Errors thrown within a queued microtask
callback should be handled within the queued callback when possible. If they are
not, the <code>process.on('uncaughtException')</code> event handler can be used to capture
and handle the errors.</p>
<p>When in doubt, unless the specific capabilities of <code>process.nextTick()</code> are
needed, use <code>queueMicrotask()</code>.</p>
</section><section><h3><code>process.noDeprecation</code><span><a class="mark" href="#all_process_processnodeprecation" id="all_process_processnodeprecation">#</a></span><a aria-hidden="true" class="legacy" id="process_process_nodeprecation"></a></h3>
<div class="api_metadata">
<span>Added in: v0.8.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>The <code>process.noDeprecation</code> property indicates whether the <code>--no-deprecation</code>
flag is set on the current Node.js process. See the documentation for
the <a href="#all_process_event-warning"><code>'warning'</code> event</a> and the
<a href="#all_process_processemitwarningwarning-type-code-ctor"><code>emitWarning()</code> method</a> for more information about this
flag's behavior.</p>
</section><section><h3><code>process.permission</code><span><a class="mark" href="#all_process_processpermission" id="all_process_processpermission">#</a></span><a aria-hidden="true" class="legacy" id="process_process_permission"></a></h3>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>This API is available through the <a href="#all_cli_--experimental-permission"><code>--experimental-permission</code></a> flag.</p>
<p><code>process.permission</code> is an object whose methods are used to manage permissions
for the current process. Additional documentation is available in the
<a href="#all_permissions_permission-model">Permission Model</a>.</p>
<h4><code>process.permission.has(scope[, reference])</code><span><a class="mark" href="#all_process_processpermissionhasscope-reference" id="all_process_processpermissionhasscope-reference">#</a></span><a aria-hidden="true" class="legacy" id="process_process_permission_has_scope_reference"></a></h4>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<ul>
<li><code>scope</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>reference</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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>Verifies that the process is able to access the given scope and reference.
If no reference is provided, a global scope is assumed, for instance,
<code>process.permission.has('fs.read')</code> will check if the process has ALL
file system read permissions.</p>
<p>The reference has a meaning based on the provided scope. For example,
the reference when the scope is File System means files and folders.</p>
<p>The available scopes are:</p>
<ul>
<li><code>fs</code> - All File System</li>
<li><code>fs.read</code> - File System read operations</li>
<li><code>fs.write</code> - File System write operations</li>
<li><code>child</code> - Child process spawning operations</li>
<li><code>worker</code> - Worker thread spawning operation</li>
</ul>
<pre><code class="language-js"><span class="hljs-comment">// Check if the process has permission to read the README file</span>
process.<span class="hljs-property">permission</span>.<span class="hljs-title function_">has</span>(<span class="hljs-string">'fs.read'</span>, <span class="hljs-string">'./README.md'</span>);
<span class="hljs-comment">// Check if the process has read permission operations</span>
process.<span class="hljs-property">permission</span>.<span class="hljs-title function_">has</span>(<span class="hljs-string">'fs.read'</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>process.pid</code><span><a class="mark" href="#all_process_processpid" id="all_process_processpid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_pid"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.15</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>The <code>process.pid</code> property returns the PID of the process.</p>
<pre class="with-40-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> { pid } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This process is pid <span class="hljs-subst">${pid}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { pid } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This process is pid <span class="hljs-subst">${pid}</span>`</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.platform</code><span><a class="mark" href="#all_process_processplatform" id="all_process_processplatform">#</a></span><a aria-hidden="true" class="legacy" id="process_process_platform"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>process.platform</code> property returns a string identifying the operating
system platform for which the Node.js binary was compiled.</p>
<p>Currently possible values are:</p>
<ul>
<li><code>'aix'</code></li>
<li><code>'darwin'</code></li>
<li><code>'freebsd'</code></li>
<li><code>'linux'</code></li>
<li><code>'openbsd'</code></li>
<li><code>'sunos'</code></li>
<li><code>'win32'</code></li>
</ul>
<pre class="with-45-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> { platform } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This platform is <span class="hljs-subst">${platform}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { platform } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This platform is <span class="hljs-subst">${platform}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<p>The value <code>'android'</code> may also be returned if the Node.js is built on the
Android operating system. However, Android support in Node.js
<a href="https://github.com/nodejs/node/blob/HEAD/BUILDING.md#android">is experimental</a>.</p>
</section><section><h3><code>process.ppid</code><span><a class="mark" href="#all_process_processppid" id="all_process_processppid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_ppid"></a></h3>
<div class="api_metadata">
<span>Added in: v9.2.0, v8.10.0, v6.13.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>The <code>process.ppid</code> property returns the PID of the parent of the
current process.</p>
<pre class="with-41-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> { ppid } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The parent process is pid <span class="hljs-subst">${ppid}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { ppid } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The parent process is pid <span class="hljs-subst">${ppid}</span>`</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.release</code><span><a class="mark" href="#all_process_processrelease" id="all_process_processrelease">#</a></span><a aria-hidden="true" class="legacy" id="process_process_release"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.2.0</td>
<td><p>The <code>lts</code> property is now supported.</p></td></tr>
<tr><td>v3.0.0</td>
<td><p><span>Added in: v3.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>process.release</code> property returns an <code>Object</code> containing metadata related
to the current release, including URLs for the source tarball and headers-only
tarball.</p>
<p><code>process.release</code> contains the following properties:</p>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A value that will always be <code>'node'</code>.</li>
<li><code>sourceUrl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> an absolute URL pointing to a <em><code>.tar.gz</code></em> file containing
the source code of the current release.</li>
<li><code>headersUrl</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> an absolute URL pointing to a <em><code>.tar.gz</code></em> file containing
only the source header files for the current release. This file is
significantly smaller than the full source file and can be used for compiling
Node.js native add-ons.</li>
<li><code>libUrl</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#Undefined_type" class="type"><undefined></a> an absolute URL pointing to a <em><code>node.lib</code></em> file
matching the architecture and version of the current release. This file is
used for compiling Node.js native add-ons. <em>This property is only present on
Windows builds of Node.js and will be missing on all other platforms.</em></li>
<li><code>lts</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#Undefined_type" class="type"><undefined></a> a string label identifying the <a href="https://github.com/nodejs/Release">LTS</a> label for this
release. This property only exists for LTS releases and is <code>undefined</code> for all
other release types, including <em>Current</em> releases. Valid values include the
LTS Release code names (including those that are no longer supported).
<ul>
<li><code>'Fermium'</code> for the 14.x LTS line beginning with 14.15.0.</li>
<li><code>'Gallium'</code> for the 16.x LTS line beginning with 16.13.0.</li>
<li><code>'Hydrogen'</code> for the 18.x LTS line beginning with 18.12.0.
For other LTS Release code names, see <a href="https://github.com/nodejs/node/blob/HEAD/doc/changelogs/CHANGELOG_ARCHIVE.md">Node.js Changelog Archive</a></li>
</ul>
</li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
<span class="hljs-attr">name</span>: <span class="hljs-string">'node'</span>,
<span class="hljs-attr">lts</span>: <span class="hljs-string">'Hydrogen'</span>,
<span class="hljs-attr">sourceUrl</span>: <span class="hljs-string">'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz'</span>,
<span class="hljs-attr">headersUrl</span>: <span class="hljs-string">'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz'</span>,
<span class="hljs-attr">libUrl</span>: <span class="hljs-string">'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib'</span>
}</code> <button class="copy-button">copy</button></pre>
<p>In custom builds from non-release versions of the source tree, only the
<code>name</code> property may be present. The additional properties should not be
relied upon to exist.</p>
</section><section><h3><code>process.report</code><span><a class="mark" href="#all_process_processreport" id="all_process_processreport">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p><code>process.report</code> is an object whose methods are used to generate diagnostic
reports for the current process. Additional documentation is available in the
<a href="report.html">report documentation</a>.</p>
<h4><code>process.report.compact</code><span><a class="mark" href="#all_process_processreportcompact" id="all_process_processreportcompact">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_compact"></a></h4>
<div class="api_metadata">
<span>Added in: v13.12.0, v12.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>Write reports in a compact format, single-line JSON, more easily consumable
by log processing systems than the default multi-line format designed for
human consumption.</p>
<pre class="with-43-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> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Reports are compact? <span class="hljs-subst">${report.compact}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Reports are compact? <span class="hljs-subst">${report.compact}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.directory</code><span><a class="mark" href="#all_process_processreportdirectory" id="all_process_processreportdirectory">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_directory"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p><span>Added in: v11.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Directory where the report is written. The default value is the empty string,
indicating that reports are written to the current working directory of the
Node.js process.</p>
<pre class="with-43-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> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report directory is <span class="hljs-subst">${report.directory}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report directory is <span class="hljs-subst">${report.directory}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.filename</code><span><a class="mark" href="#all_process_processreportfilename" id="all_process_processreportfilename">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_filename"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p><span>Added in: v11.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Filename where the report is written. If set to the empty string, the output
filename will be comprised of a timestamp, PID, and sequence number. The default
value is the empty string.</p>
<p>If the value of <code>process.report.filename</code> is set to <code>'stdout'</code> or <code>'stderr'</code>,
the report is written to the stdout or stderr of the process respectively.</p>
<pre class="with-43-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> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report filename is <span class="hljs-subst">${report.filename}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report filename is <span class="hljs-subst">${report.filename}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.getReport([err])</code><span><a class="mark" href="#all_process_processreportgetreporterr" id="all_process_processreportgetreporterr">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_getreport_err"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</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 custom error used for reporting the JavaScript stack.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns a JavaScript Object representation of a diagnostic report for the
running process. The report's JavaScript stack trace is taken from <code>err</code>, if
present.</p>
<pre class="with-43-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> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> util <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> data = report.<span class="hljs-title function_">getReport</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-property">header</span>.<span class="hljs-property">nodejsVersion</span>);
<span class="hljs-comment">// Similar to process.report.writeReport()</span>
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'my-report.log'</span>, util.<span class="hljs-title function_">inspect</span>(data), <span class="hljs-string">'utf8'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</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">const</span> data = report.<span class="hljs-title function_">getReport</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-property">header</span>.<span class="hljs-property">nodejsVersion</span>);
<span class="hljs-comment">// Similar to process.report.writeReport()</span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'my-report.log'</span>, util.<span class="hljs-title function_">inspect</span>(data), <span class="hljs-string">'utf8'</span>);</code><button class="copy-button">copy</button></pre>
<p>Additional documentation is available in the <a href="report.html">report documentation</a>.</p>
<h4><code>process.report.reportOnFatalError</code><span><a class="mark" href="#all_process_processreportreportonfatalerror" id="all_process_processreportreportonfatalerror">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_reportonfatalerror"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0, v14.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p><span>Added in: v11.12.0</span></p></td></tr>
</tbody></table>
</details>
</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>true</code>, a diagnostic report is generated on fatal errors, such as out of
memory errors or failed C++ assertions.</p>
<pre class="with-43-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> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report on fatal error: <span class="hljs-subst">${report.reportOnFatalError}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report on fatal error: <span class="hljs-subst">${report.reportOnFatalError}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.reportOnSignal</code><span><a class="mark" href="#all_process_processreportreportonsignal" id="all_process_processreportreportonsignal">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_reportonsignal"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p><span>Added in: v11.12.0</span></p></td></tr>
</tbody></table>
</details>
</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>true</code>, a diagnostic report is generated when the process receives the
signal specified by <code>process.report.signal</code>.</p>
<pre class="with-43-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> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report on signal: <span class="hljs-subst">${report.reportOnSignal}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report on signal: <span class="hljs-subst">${report.reportOnSignal}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.reportOnUncaughtException</code><span><a class="mark" href="#all_process_processreportreportonuncaughtexception" id="all_process_processreportreportonuncaughtexception">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_reportonuncaughtexception"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p><span>Added in: v11.12.0</span></p></td></tr>
</tbody></table>
</details>
</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>true</code>, a diagnostic report is generated on uncaught exception.</p>
<pre class="with-43-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> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report on exception: <span class="hljs-subst">${report.reportOnUncaughtException}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report on exception: <span class="hljs-subst">${report.reportOnUncaughtException}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.signal</code><span><a class="mark" href="#all_process_processreportsignal" id="all_process_processreportsignal">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_signal"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p><span>Added in: v11.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The signal used to trigger the creation of a diagnostic report. Defaults to
<code>'SIGUSR2'</code>.</p>
<pre class="with-43-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> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report signal: <span class="hljs-subst">${report.signal}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report signal: <span class="hljs-subst">${report.signal}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.writeReport([filename][, err])</code><span><a class="mark" href="#all_process_processreportwritereportfilename-err" id="all_process_processreportwritereportfilename-err">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_writereport_filename_err"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the file where the report is written. This
should be a relative path, that will be appended to the directory specified in
<code>process.report.directory</code>, or the current working directory of the Node.js
process, if unspecified.</p>
</li>
<li>
<p><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> A custom error used for reporting the JavaScript stack.</p>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Returns the filename of the generated report.</p>
</li>
</ul>
<p>Writes a diagnostic report to a file. If <code>filename</code> is not provided, the default
filename includes the date, time, PID, and a sequence number. The report's
JavaScript stack trace is taken from <code>err</code>, if present.</p>
<p>If the value of <code>filename</code> is set to <code>'stdout'</code> or <code>'stderr'</code>, the report is
written to the stdout or stderr of the process respectively.</p>
<pre class="with-43-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> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
report.<span class="hljs-title function_">writeReport</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
report.<span class="hljs-title function_">writeReport</span>();</code><button class="copy-button">copy</button></pre>
<p>Additional documentation is available in the <a href="report.html">report documentation</a>.</p>
</section><section><h3><code>process.resourceUsage()</code><span><a class="mark" href="#all_process_processresourceusage" id="all_process_processresourceusage">#</a></span><a aria-hidden="true" class="legacy" id="process_process_resourceusage"></a></h3>
<div class="api_metadata">
<span>Added in: v12.6.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> the resource usage for the current process. All of these
values come from the <code>uv_getrusage</code> call which returns
a <a href="https://docs.libuv.org/en/v1.x/misc.html#c.uv_rusage_t"><code>uv_rusage_t</code> struct</a>.
<ul>
<li><code>userCPUTime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_utime</code> computed in microseconds.
It is the same value as <a href="#all_process_processcpuusagepreviousvalue"><code>process.cpuUsage().user</code></a>.</li>
<li><code>systemCPUTime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_stime</code> computed in microseconds.
It is the same value as <a href="#all_process_processcpuusagepreviousvalue"><code>process.cpuUsage().system</code></a>.</li>
<li><code>maxRSS</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_maxrss</code> which is the maximum resident set
size used in kilobytes.</li>
<li><code>sharedMemorySize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_ixrss</code> but is not supported by
any platform.</li>
<li><code>unsharedDataSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_idrss</code> but is not supported by
any platform.</li>
<li><code>unsharedStackSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_isrss</code> but is not supported by
any platform.</li>
<li><code>minorPageFault</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_minflt</code> which is the number of
minor page faults for the process, see
<a href="https://en.wikipedia.org/wiki/Page_fault#Minor">this article for more details</a>.</li>
<li><code>majorPageFault</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_majflt</code> which is the number of
major page faults for the process, see
<a href="https://en.wikipedia.org/wiki/Page_fault#Major">this article for more details</a>. This field is not
supported on Windows.</li>
<li><code>swappedOut</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_nswap</code> but is not supported by any
platform.</li>
<li><code>fsRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_inblock</code> which is the number of times the
file system had to perform input.</li>
<li><code>fsWrite</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_oublock</code> which is the number of times the
file system had to perform output.</li>
<li><code>ipcSent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_msgsnd</code> but is not supported by any
platform.</li>
<li><code>ipcReceived</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_msgrcv</code> but is not supported by any
platform.</li>
<li><code>signalsCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_nsignals</code> but is not supported by any
platform.</li>
<li><code>voluntaryContextSwitches</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_nvcsw</code> which is the
number of times a CPU context switch resulted due to a process voluntarily
giving up the processor before its time slice was completed (usually to
await availability of a resource). This field is not supported on Windows.</li>
<li><code>involuntaryContextSwitches</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> maps to <code>ru_nivcsw</code> which is the
number of times a CPU context switch resulted due to a higher priority
process becoming runnable or because the current process exceeded its
time slice. This field is not supported on Windows.</li>
</ul>
</li>
</ul>
<pre class="with-50-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> { resourceUsage } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">resourceUsage</span>());
<span class="hljs-comment">/*
Will output:
{
userCPUTime: 82872,
systemCPUTime: 4143,
maxRSS: 33164,
sharedMemorySize: 0,
unsharedDataSize: 0,
unsharedStackSize: 0,
minorPageFault: 2469,
majorPageFault: 0,
swappedOut: 0,
fsRead: 0,
fsWrite: 8,
ipcSent: 0,
ipcReceived: 0,
signalsCount: 0,
voluntaryContextSwitches: 79,
involuntaryContextSwitches: 1
}
*/</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { resourceUsage } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">resourceUsage</span>());
<span class="hljs-comment">/*
Will output:
{
userCPUTime: 82872,
systemCPUTime: 4143,
maxRSS: 33164,
sharedMemorySize: 0,
unsharedDataSize: 0,
unsharedStackSize: 0,
minorPageFault: 2469,
majorPageFault: 0,
swappedOut: 0,
fsRead: 0,
fsWrite: 8,
ipcSent: 0,
ipcReceived: 0,
signalsCount: 0,
voluntaryContextSwitches: 79,
involuntaryContextSwitches: 1
}
*/</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.send(message[, sendHandle[, options]][, callback])</code><span><a class="mark" href="#all_process_processsendmessage-sendhandle-options-callback" id="all_process_processsendmessage-sendhandle-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="process_process_send_message_sendhandle_options_callback"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>sendHandle</code> <a href="#all_net_class-netserver" class="type"><net.Server></a> | <a href="#all_net_class-netsocket" class="type"><net.Socket></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> used to parameterize the sending of certain types of
handles.<code>options</code> supports the following properties:
<ul>
<li><code>keepOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> A value that can be used when passing instances of
<code>net.Socket</code>. When <code>true</code>, the socket is kept open in the sending process.
<strong>Default:</strong> <code>false</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></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>If Node.js is spawned with an IPC channel, the <code>process.send()</code> method can be
used to send messages to the parent process. Messages will be received as a
<a href="#all_child_process_event-message"><code>'message'</code></a> event on the parent's <a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> object.</p>
<p>If Node.js was not spawned with an IPC channel, <code>process.send</code> will be
<code>undefined</code>.</p>
<p>The message goes through serialization and parsing. The resulting message might
not be the same as what is originally sent.</p>
</section><section><h3><code>process.setegid(id)</code><span><a class="mark" href="#all_process_processsetegidid" id="all_process_processsetegidid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_setegid_id"></a></h3>
<div class="api_metadata">
<span>Added in: v2.0.0</span>
</div>
<ul>
<li><code>id</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#Number_type" class="type"><number></a> A group name or ID</li>
</ul>
<p>The <code>process.setegid()</code> method sets the effective group identity of the process.
(See <a href="http://man7.org/linux/man-pages/man2/setegid.2.html"><code>setegid(2)</code></a>.) The <code>id</code> can be passed as either a numeric ID or a group
name string. If a group name is specified, this method blocks while resolving
the associated a numeric ID.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getegid</span> && process.<span class="hljs-property">setegid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getegid()}</span>`</span>);
<span class="hljs-keyword">try</span> {
process.<span class="hljs-title function_">setegid</span>(<span class="hljs-number">501</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New gid: <span class="hljs-subst">${process.getegid()}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set gid: <span class="hljs-subst">${err}</span>`</span>);
}
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getegid</span> && process.<span class="hljs-property">setegid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getegid()}</span>`</span>);
<span class="hljs-keyword">try</span> {
process.<span class="hljs-title function_">setegid</span>(<span class="hljs-number">501</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New gid: <span class="hljs-subst">${process.getegid()}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set gid: <span class="hljs-subst">${err}</span>`</span>);
}
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.seteuid(id)</code><span><a class="mark" href="#all_process_processseteuidid" id="all_process_processseteuidid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_seteuid_id"></a></h3>
<div class="api_metadata">
<span>Added in: v2.0.0</span>
</div>
<ul>
<li><code>id</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#Number_type" class="type"><number></a> A user name or ID</li>
</ul>
<p>The <code>process.seteuid()</code> method sets the effective user identity of the process.
(See <a href="http://man7.org/linux/man-pages/man2/seteuid.2.html"><code>seteuid(2)</code></a>.) The <code>id</code> can be passed as either a numeric ID or a username
string. If a username is specified, the method blocks while resolving the
associated numeric ID.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">geteuid</span> && process.<span class="hljs-property">seteuid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.geteuid()}</span>`</span>);
<span class="hljs-keyword">try</span> {
process.<span class="hljs-title function_">seteuid</span>(<span class="hljs-number">501</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New uid: <span class="hljs-subst">${process.geteuid()}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set uid: <span class="hljs-subst">${err}</span>`</span>);
}
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">geteuid</span> && process.<span class="hljs-property">seteuid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.geteuid()}</span>`</span>);
<span class="hljs-keyword">try</span> {
process.<span class="hljs-title function_">seteuid</span>(<span class="hljs-number">501</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New uid: <span class="hljs-subst">${process.geteuid()}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set uid: <span class="hljs-subst">${err}</span>`</span>);
}
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.setgid(id)</code><span><a class="mark" href="#all_process_processsetgidid" id="all_process_processsetgidid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_setgid_id"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div>
<ul>
<li><code>id</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#Number_type" class="type"><number></a> The group name or ID</li>
</ul>
<p>The <code>process.setgid()</code> method sets the group identity of the process. (See
<a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>.) The <code>id</code> can be passed as either a numeric ID or a group name
string. If a group name is specified, this method blocks while resolving the
associated numeric ID.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgid</span> && process.<span class="hljs-property">setgid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getgid()}</span>`</span>);
<span class="hljs-keyword">try</span> {
process.<span class="hljs-title function_">setgid</span>(<span class="hljs-number">501</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New gid: <span class="hljs-subst">${process.getgid()}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set gid: <span class="hljs-subst">${err}</span>`</span>);
}
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgid</span> && process.<span class="hljs-property">setgid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getgid()}</span>`</span>);
<span class="hljs-keyword">try</span> {
process.<span class="hljs-title function_">setgid</span>(<span class="hljs-number">501</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New gid: <span class="hljs-subst">${process.getgid()}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set gid: <span class="hljs-subst">${err}</span>`</span>);
}
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.setgroups(groups)</code><span><a class="mark" href="#all_process_processsetgroupsgroups" id="all_process_processsetgroupsgroups">#</a></span><a aria-hidden="true" class="legacy" id="process_process_setgroups_groups"></a></h3>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>groups</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a></li>
</ul>
<p>The <code>process.setgroups()</code> method sets the supplementary group IDs for the
Node.js process. This is a privileged operation that requires the Node.js
process to have <code>root</code> or the <code>CAP_SETGID</code> capability.</p>
<p>The <code>groups</code> array can contain numeric group IDs, group names, or both.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgroups</span> && process.<span class="hljs-property">setgroups</span>) {
<span class="hljs-keyword">try</span> {
process.<span class="hljs-title function_">setgroups</span>([<span class="hljs-number">501</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// new groups</span>
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set groups: <span class="hljs-subst">${err}</span>`</span>);
}
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgroups</span> && process.<span class="hljs-property">setgroups</span>) {
<span class="hljs-keyword">try</span> {
process.<span class="hljs-title function_">setgroups</span>([<span class="hljs-number">501</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// new groups</span>
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set groups: <span class="hljs-subst">${err}</span>`</span>);
}
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.setuid(id)</code><span><a class="mark" href="#all_process_processsetuidid" id="all_process_processsetuidid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_setuid_id"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.28</span>
</div>
<ul>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>process.setuid(id)</code> method sets the user identity of the process. (See
<a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>.) The <code>id</code> can be passed as either a numeric ID or a username string.
If a username is specified, the method blocks while resolving the associated
numeric ID.</p>
<pre class="with-40-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getuid</span> && process.<span class="hljs-property">setuid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.getuid()}</span>`</span>);
<span class="hljs-keyword">try</span> {
process.<span class="hljs-title function_">setuid</span>(<span class="hljs-number">501</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New uid: <span class="hljs-subst">${process.getuid()}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set uid: <span class="hljs-subst">${err}</span>`</span>);
}
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getuid</span> && process.<span class="hljs-property">setuid</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.getuid()}</span>`</span>);
<span class="hljs-keyword">try</span> {
process.<span class="hljs-title function_">setuid</span>(<span class="hljs-number">501</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New uid: <span class="hljs-subst">${process.getuid()}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set uid: <span class="hljs-subst">${err}</span>`</span>);
}
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.setSourceMapsEnabled(val)</code><span><a class="mark" href="#all_process_processsetsourcemapsenabledval" id="all_process_processsetsourcemapsenabledval">#</a></span><a aria-hidden="true" class="legacy" id="process_process_setsourcemapsenabled_val"></a></h3>
<div class="api_metadata">
<span>Added in: v16.6.0, v14.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>val</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>This function enables or disables the <a href="https://sourcemaps.info/spec.html">Source Map v3</a> support for
stack traces.</p>
<p>It provides same features as launching Node.js process with commandline options
<code>--enable-source-maps</code>.</p>
<p>Only source maps in JavaScript files that are loaded after source maps has been
enabled will be parsed and loaded.</p>
</section><section><h3><code>process.setUncaughtExceptionCaptureCallback(fn)</code><span><a class="mark" href="#all_process_processsetuncaughtexceptioncapturecallbackfn" id="all_process_processsetuncaughtexceptioncapturecallbackfn">#</a></span><a aria-hidden="true" class="legacy" id="process_process_setuncaughtexceptioncapturecallback_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v9.3.0</span>
</div>
<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://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a></li>
</ul>
<p>The <code>process.setUncaughtExceptionCaptureCallback()</code> function sets a function
that will be invoked when an uncaught exception occurs, which will receive the
exception value itself as its first argument.</p>
<p>If such a function is set, the <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a> event will
not be emitted. If <code>--abort-on-uncaught-exception</code> was passed from the
command line or set through <a href="#all_v8_v8setflagsfromstringflags"><code>v8.setFlagsFromString()</code></a>, the process will
not abort. Actions configured to take place on exceptions such as report
generations will be affected too</p>
<p>To unset the capture function,
<code>process.setUncaughtExceptionCaptureCallback(null)</code> may be used. Calling this
method with a non-<code>null</code> argument while another capture function is set will
throw an error.</p>
<p>Using this function is mutually exclusive with using the deprecated
<a href="domain.html"><code>domain</code></a> built-in module.</p>
</section><section><h3><code>process.sourceMapsEnabled</code><span><a class="mark" href="#all_process_processsourcemapsenabled" id="all_process_processsourcemapsenabled">#</a></span><a aria-hidden="true" class="legacy" id="process_process_sourcemapsenabled"></a></h3>
<div class="api_metadata">
<span>Added in: v20.7.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_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>The <code>process.sourceMapsEnabled</code> property returns whether the
<a href="https://sourcemaps.info/spec.html">Source Map v3</a> support for stack traces is enabled.</p>
</section><section><h3><code>process.stderr</code><span><a class="mark" href="#all_process_processstderr" id="all_process_processstderr">#</a></span><a aria-hidden="true" class="legacy" id="process_process_stderr"></a></h3>
<ul>
<li><a href="#all_stream_stream" class="type"><Stream></a></li>
</ul>
<p>The <code>process.stderr</code> property returns a stream connected to
<code>stderr</code> (fd <code>2</code>). It is a <a href="#all_net_class-netsocket"><code>net.Socket</code></a> (which is a <a href="#all_stream_duplex-and-transform-streams">Duplex</a>
stream) unless fd <code>2</code> refers to a file, in which case it is
a <a href="#all_stream_writable-streams">Writable</a> stream.</p>
<p><code>process.stderr</code> differs from other Node.js streams in important ways. See
<a href="#all_process_a-note-on-process-io">note on process I/O</a> for more information.</p>
<h4><code>process.stderr.fd</code><span><a class="mark" href="#all_process_processstderrfd" id="all_process_processstderrfd">#</a></span><a aria-hidden="true" class="legacy" id="process_process_stderr_fd"></a></h4>
<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 refers to the value of underlying file descriptor of
<code>process.stderr</code>. The value is fixed at <code>2</code>. In <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads,
this field does not exist.</p>
</section><section><h3><code>process.stdin</code><span><a class="mark" href="#all_process_processstdin" id="all_process_processstdin">#</a></span><a aria-hidden="true" class="legacy" id="process_process_stdin"></a></h3>
<ul>
<li><a href="#all_stream_stream" class="type"><Stream></a></li>
</ul>
<p>The <code>process.stdin</code> property returns a stream connected to
<code>stdin</code> (fd <code>0</code>). It is a <a href="#all_net_class-netsocket"><code>net.Socket</code></a> (which is a <a href="#all_stream_duplex-and-transform-streams">Duplex</a>
stream) unless fd <code>0</code> refers to a file, in which case it is
a <a href="#all_stream_readable-streams">Readable</a> stream.</p>
<p>For details of how to read from <code>stdin</code> see <a href="#all_stream_readablereadsize"><code>readable.read()</code></a>.</p>
<p>As a <a href="#all_stream_duplex-and-transform-streams">Duplex</a> stream, <code>process.stdin</code> can also be used in "old" mode that
is compatible with scripts written for Node.js prior to v0.10.
For more information see <a href="#all_stream_compatibility-with-older-nodejs-versions">Stream compatibility</a>.</p>
<p>In "old" streams mode the <code>stdin</code> stream is paused by default, so one
must call <code>process.stdin.resume()</code> to read from it. Note also that calling
<code>process.stdin.resume()</code> itself would switch stream to "old" mode.</p>
<h4><code>process.stdin.fd</code><span><a class="mark" href="#all_process_processstdinfd" id="all_process_processstdinfd">#</a></span><a aria-hidden="true" class="legacy" id="process_process_stdin_fd"></a></h4>
<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 refers to the value of underlying file descriptor of
<code>process.stdin</code>. The value is fixed at <code>0</code>. In <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads,
this field does not exist.</p>
</section><section><h3><code>process.stdout</code><span><a class="mark" href="#all_process_processstdout" id="all_process_processstdout">#</a></span><a aria-hidden="true" class="legacy" id="process_process_stdout"></a></h3>
<ul>
<li><a href="#all_stream_stream" class="type"><Stream></a></li>
</ul>
<p>The <code>process.stdout</code> property returns a stream connected to
<code>stdout</code> (fd <code>1</code>). It is a <a href="#all_net_class-netsocket"><code>net.Socket</code></a> (which is a <a href="#all_stream_duplex-and-transform-streams">Duplex</a>
stream) unless fd <code>1</code> refers to a file, in which case it is
a <a href="#all_stream_writable-streams">Writable</a> stream.</p>
<p>For example, to copy <code>process.stdin</code> to <code>process.stdout</code>:</p>
<pre class="with-50-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> { stdin, stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
stdin.<span class="hljs-title function_">pipe</span>(stdout);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { stdin, stdout } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
stdin.<span class="hljs-title function_">pipe</span>(stdout);</code><button class="copy-button">copy</button></pre>
<p><code>process.stdout</code> differs from other Node.js streams in important ways. See
<a href="#all_process_a-note-on-process-io">note on process I/O</a> for more information.</p>
<h4><code>process.stdout.fd</code><span><a class="mark" href="#all_process_processstdoutfd" id="all_process_processstdoutfd">#</a></span><a aria-hidden="true" class="legacy" id="process_process_stdout_fd"></a></h4>
<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 refers to the value of underlying file descriptor of
<code>process.stdout</code>. The value is fixed at <code>1</code>. In <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads,
this field does not exist.</p>
<h4>A note on process I/O<span><a class="mark" href="#all_process_a-note-on-process-io" id="all_process_a-note-on-process-io">#</a></span><a aria-hidden="true" class="legacy" id="process_a_note_on_process_i_o"></a></h4>
<p><code>process.stdout</code> and <code>process.stderr</code> differ from other Node.js streams in
important ways:</p>
<ol>
<li>They are used internally by <a href="#all_console_consolelogdata-args"><code>console.log()</code></a> and <a href="#all_console_consoleerrordata-args"><code>console.error()</code></a>,
respectively.</li>
<li>Writes may be synchronous depending on what the stream is connected to
and whether the system is Windows or POSIX:
<ul>
<li>Files: <em>synchronous</em> on Windows and POSIX</li>
<li>TTYs (Terminals): <em>asynchronous</em> on Windows, <em>synchronous</em> on POSIX</li>
<li>Pipes (and sockets): <em>synchronous</em> on Windows, <em>asynchronous</em> on POSIX</li>
</ul>
</li>
</ol>
<p>These behaviors are partly for historical reasons, as changing them would
create backward incompatibility, but they are also expected by some users.</p>
<p>Synchronous writes avoid problems such as output written with <code>console.log()</code> or
<code>console.error()</code> being unexpectedly interleaved, or not written at all if
<code>process.exit()</code> is called before an asynchronous write completes. See
<a href="#all_process_processexitcode"><code>process.exit()</code></a> for more information.</p>
<p><em><strong>Warning</strong></em>: Synchronous writes block the event loop until the write has
completed. This can be near instantaneous in the case of output to a file, but
under high system load, pipes that are not being read at the receiving end, or
with slow terminals or file systems, it's possible for the event loop to be
blocked often enough and long enough to have severe negative performance
impacts. This may not be a problem when writing to an interactive terminal
session, but consider this particularly careful when doing production logging to
the process output streams.</p>
<p>To check if a stream is connected to a <a href="#all_tty_tty">TTY</a> context, check the <code>isTTY</code>
property.</p>
<p>For instance:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p <span class="hljs-string">"Boolean(process.stdin.isTTY)"</span></span>
true
<span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"foo"</span> | node -p <span class="hljs-string">"Boolean(process.stdin.isTTY)"</span></span>
false
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p <span class="hljs-string">"Boolean(process.stdout.isTTY)"</span></span>
true
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p <span class="hljs-string">"Boolean(process.stdout.isTTY)"</span> | <span class="hljs-built_in">cat</span></span>
false</code> <button class="copy-button">copy</button></pre>
<p>See the <a href="#all_tty_tty">TTY</a> documentation for more information.</p>
</section><section><h3><code>process.throwDeprecation</code><span><a class="mark" href="#all_process_processthrowdeprecation" id="all_process_processthrowdeprecation">#</a></span><a aria-hidden="true" class="legacy" id="process_process_throwdeprecation"></a></h3>
<div class="api_metadata">
<span>Added in: v0.9.12</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>The initial value of <code>process.throwDeprecation</code> indicates whether the
<code>--throw-deprecation</code> flag is set on the current Node.js process.
<code>process.throwDeprecation</code> is mutable, so whether or not deprecation
warnings result in errors may be altered at runtime. See the
documentation for the <a href="#all_process_event-warning"><code>'warning'</code> event</a> and the
<a href="#all_process_processemitwarningwarning-type-code-ctor"><code>emitWarning()</code> method</a> for more information.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --throw-deprecation -p <span class="hljs-string">"process.throwDeprecation"</span></span>
true
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p <span class="hljs-string">"process.throwDeprecation"</span></span>
undefined
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.emitWarning(<span class="hljs-string">'test'</span>, <span class="hljs-string">'DeprecationWarning'</span>);</span>
undefined
<span class="hljs-meta prompt_">> </span><span class="language-bash">(node:26598) DeprecationWarning: <span class="hljs-built_in">test</span></span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.throwDeprecation = <span class="hljs-literal">true</span>;</span>
true
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.emitWarning(<span class="hljs-string">'test'</span>, <span class="hljs-string">'DeprecationWarning'</span>);</span>
Thrown:
[DeprecationWarning: test] { name: 'DeprecationWarning' }</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>process.title</code><span><a class="mark" href="#all_process_processtitle" id="all_process_processtitle">#</a></span><a aria-hidden="true" class="legacy" id="process_process_title"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>process.title</code> property returns the current process title (i.e. returns
the current value of <code>ps</code>). Assigning a new value to <code>process.title</code> modifies
the current value of <code>ps</code>.</p>
<p>When a new value is assigned, different platforms will impose different maximum
length restrictions on the title. Usually such restrictions are quite limited.
For instance, on Linux and macOS, <code>process.title</code> is limited to the size of the
binary name plus the length of the command-line arguments because setting the
<code>process.title</code> overwrites the <code>argv</code> memory of the process. Node.js v0.8
allowed for longer process title strings by also overwriting the <code>environ</code>
memory but that was potentially insecure and confusing in some (rather obscure)
cases.</p>
<p>Assigning a value to <code>process.title</code> might not result in an accurate label
within process manager applications such as macOS Activity Monitor or Windows
Services Manager.</p>
</section><section><h3><code>process.traceDeprecation</code><span><a class="mark" href="#all_process_processtracedeprecation" id="all_process_processtracedeprecation">#</a></span><a aria-hidden="true" class="legacy" id="process_process_tracedeprecation"></a></h3>
<div class="api_metadata">
<span>Added in: v0.8.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>The <code>process.traceDeprecation</code> property indicates whether the
<code>--trace-deprecation</code> flag is set on the current Node.js process. See the
documentation for the <a href="#all_process_event-warning"><code>'warning'</code> event</a> and the
<a href="#all_process_processemitwarningwarning-type-code-ctor"><code>emitWarning()</code> method</a> for more information about this
flag's behavior.</p>
</section><section><h3><code>process.umask()</code><span><a class="mark" href="#all_process_processumask" id="all_process_processumask">#</a></span><a aria-hidden="true" class="legacy" id="process_process_umask"></a></h3>
<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, v12.19.0</td>
<td><p>Calling <code>process.umask()</code> with no arguments is deprecated.</p></td></tr>
<tr><td>v0.1.19</td>
<td><p><span>Added in: v0.1.19</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Calling <code>process.umask()</code> with no argument causes
the process-wide umask to be written twice. This introduces a race condition
between threads, and is a potential security vulnerability. There is no safe,
cross-platform alternative API.</div><p></p>
<p><code>process.umask()</code> returns the Node.js process's file mode creation mask. Child
processes inherit the mask from the parent process.</p>
</section><section><h3><code>process.umask(mask)</code><span><a class="mark" href="#all_process_processumaskmask" id="all_process_processumaskmask">#</a></span><a aria-hidden="true" class="legacy" id="process_process_umask_mask"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.19</span>
</div>
<ul>
<li><code>mask</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#Number_type" class="type"><integer></a></li>
</ul>
<p><code>process.umask(mask)</code> sets the Node.js process's file mode creation mask. Child
processes inherit the mask from the parent process. Returns the previous mask.</p>
<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> { umask } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> newmask = <span class="hljs-number">0o022</span>;
<span class="hljs-keyword">const</span> oldmask = <span class="hljs-title function_">umask</span>(newmask);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
<span class="hljs-string">`Changed umask from <span class="hljs-subst">${oldmask.toString(<span class="hljs-number">8</span>)}</span> to <span class="hljs-subst">${newmask.toString(<span class="hljs-number">8</span>)}</span>`</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { umask } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> newmask = <span class="hljs-number">0o022</span>;
<span class="hljs-keyword">const</span> oldmask = <span class="hljs-title function_">umask</span>(newmask);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
<span class="hljs-string">`Changed umask from <span class="hljs-subst">${oldmask.toString(<span class="hljs-number">8</span>)}</span> to <span class="hljs-subst">${newmask.toString(<span class="hljs-number">8</span>)}</span>`</span>,
);</code><button class="copy-button">copy</button></pre>
<p>In <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads, <code>process.umask(mask)</code> will throw an exception.</p>
</section><section><h3><code>process.uptime()</code><span><a class="mark" href="#all_process_processuptime" id="all_process_processuptime">#</a></span><a aria-hidden="true" class="legacy" id="process_process_uptime"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The <code>process.uptime()</code> method returns the number of seconds the current Node.js
process has been running.</p>
<p>The return value includes fractions of a second. Use <code>Math.floor()</code> to get whole
seconds.</p>
</section><section><h3><code>process.version</code><span><a class="mark" href="#all_process_processversion" id="all_process_processversion">#</a></span><a aria-hidden="true" class="legacy" id="process_process_version"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.3</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>process.version</code> property contains the Node.js version string.</p>
<pre class="with-44-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> { version } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Version: <span class="hljs-subst">${version}</span>`</span>);
<span class="hljs-comment">// Version: v14.8.0</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { version } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Version: <span class="hljs-subst">${version}</span>`</span>);
<span class="hljs-comment">// Version: v14.8.0</span></code><button class="copy-button">copy</button></pre>
<p>To get the version string without the prepended <em>v</em>, use
<code>process.versions.node</code>.</p>
</section><section><h3><code>process.versions</code><span><a class="mark" href="#all_process_processversions" id="all_process_processversions">#</a></span><a aria-hidden="true" class="legacy" id="process_process_versions"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>v8</code> property now includes a Node.js specific suffix.</p></td></tr>
<tr><td>v4.2.0</td>
<td><p>The <code>icu</code> property is now supported.</p></td></tr>
<tr><td>v0.2.0</td>
<td><p><span>Added in: v0.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>process.versions</code> property returns an object listing the version strings of
Node.js and its dependencies. <code>process.versions.modules</code> indicates the current
ABI version, which is increased whenever a C++ API changes. Node.js will refuse
to load modules that were compiled against a different module ABI version.</p>
<pre class="with-45-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> { versions } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(versions);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { versions } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(versions);</code><button class="copy-button">copy</button></pre>
<p>Will generate an object similar to:</p>
<pre><code class="language-console">{ node: '23.0.0',
acorn: '8.11.3',
ada: '2.7.8',
ares: '1.28.1',
base64: '0.5.2',
brotli: '1.1.0',
cjs_module_lexer: '1.2.2',
cldr: '45.0',
icu: '75.1',
llhttp: '9.2.1',
modules: '127',
napi: '9',
nghttp2: '1.61.0',
nghttp3: '0.7.0',
ngtcp2: '1.3.0',
openssl: '3.0.13+quic',
simdjson: '3.8.0',
simdutf: '5.2.4',
tz: '2024a',
undici: '6.13.0',
unicode: '15.1',
uv: '1.48.0',
uvwasi: '0.0.20',
v8: '12.4.254.14-node.11',
zlib: '1.3.0.1-motley-7d77fb7' }</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Exit codes<span><a class="mark" href="#all_process_exit-codes" id="all_process_exit-codes">#</a></span><a aria-hidden="true" class="legacy" id="process_exit_codes"></a></h3>
<p>Node.js will normally exit with a <code>0</code> status code when no more async
operations are pending. The following status codes are used in other
cases:</p>
<ul>
<li><code>1</code> <strong>Uncaught Fatal Exception</strong>: There was an uncaught exception,
and it was not handled by a domain or an <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a> event
handler.</li>
<li><code>2</code>: Unused (reserved by Bash for builtin misuse)</li>
<li><code>3</code> <strong>Internal JavaScript Parse Error</strong>: The JavaScript source code
internal in the Node.js bootstrapping process caused a parse error. This
is extremely rare, and generally can only happen during development
of Node.js itself.</li>
<li><code>4</code> <strong>Internal JavaScript Evaluation Failure</strong>: The JavaScript
source code internal in the Node.js bootstrapping process failed to
return a function value when evaluated. This is extremely rare, and
generally can only happen during development of Node.js itself.</li>
<li><code>5</code> <strong>Fatal Error</strong>: There was a fatal unrecoverable error in V8.
Typically a message will be printed to stderr with the prefix <code>FATAL ERROR</code>.</li>
<li><code>6</code> <strong>Non-function Internal Exception Handler</strong>: There was an
uncaught exception, but the internal fatal exception handler
function was somehow set to a non-function, and could not be called.</li>
<li><code>7</code> <strong>Internal Exception Handler Run-Time Failure</strong>: There was an
uncaught exception, and the internal fatal exception handler
function itself threw an error while attempting to handle it. This
can happen, for example, if an <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a> or
<code>domain.on('error')</code> handler throws an error.</li>
<li><code>8</code>: Unused. In previous versions of Node.js, exit code 8 sometimes
indicated an uncaught exception.</li>
<li><code>9</code> <strong>Invalid Argument</strong>: Either an unknown option was specified,
or an option requiring a value was provided without a value.</li>
<li><code>10</code> <strong>Internal JavaScript Run-Time Failure</strong>: The JavaScript
source code internal in the Node.js bootstrapping process threw an error
when the bootstrapping function was called. This is extremely rare,
and generally can only happen during development of Node.js itself.</li>
<li><code>12</code> <strong>Invalid Debug Argument</strong>: The <code>--inspect</code> and/or <code>--inspect-brk</code>
options were set, but the port number chosen was invalid or unavailable.</li>
<li><code>13</code> <strong>Unfinished Top-Level Await</strong>: <code>await</code> was used outside of a function
in the top-level code, but the passed <code>Promise</code> never resolved.</li>
<li><code>14</code> <strong>Snapshot Failure</strong>: Node.js was started to build a V8 startup
snapshot and it failed because certain requirements of the state of
the application were not met.</li>
<li><code>>128</code> <strong>Signal Exits</strong>: If Node.js receives a fatal signal such as
<code>SIGKILL</code> or <code>SIGHUP</code>, then its exit code will be <code>128</code> plus the
value of the signal code. This is a standard POSIX practice, since
exit codes are defined to be 7-bit integers, and signal exits set
the high-order bit, and then contain the value of the signal code.
For example, signal <code>SIGABRT</code> has value <code>6</code>, so the expected exit
code will be <code>128</code> + <code>6</code>, or <code>134</code>.</li>
</ul></section>
</section>
<section><h2>Punycode<span><a class="mark" href="#all_punycode_punycode" id="all_punycode_punycode">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode"></a></h2>
<div class="api_metadata">
<span>Deprecated since: v7.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/punycode.js">lib/punycode.js</a></p>
<p><strong>The version of the punycode module bundled in Node.js is being deprecated.</strong>
In a future major version of Node.js this module will be removed. Users
currently depending on the <code>punycode</code> module should switch to using the
userland-provided <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> module instead. For punycode-based URL
encoding, see <a href="#all_url_urldomaintoasciidomain"><code>url.domainToASCII</code></a> or, more generally, the
<a href="#all_url_the-whatwg-url-api">WHATWG URL API</a>.</p>
<p>The <code>punycode</code> module is a bundled version of the <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> module. It
can be accessed using:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> punycode = <span class="hljs-built_in">require</span>(<span class="hljs-string">'punycode'</span>);</code> <button class="copy-button">copy</button></pre>
<p><a href="https://tools.ietf.org/html/rfc3492">Punycode</a> is a character encoding scheme defined by RFC 3492 that is
primarily intended for use in Internationalized Domain Names. Because host
names in URLs are limited to ASCII characters only, Domain Names that contain
non-ASCII characters must be converted into ASCII using the Punycode scheme.
For instance, the Japanese character that translates into the English word,
<code>'example'</code> is <code>'例'</code>. The Internationalized Domain Name, <code>'例.com'</code> (equivalent
to <code>'example.com'</code>) is represented by Punycode as the ASCII string
<code>'xn--fsq.com'</code>.</p>
<p>The <code>punycode</code> module provides a simple implementation of the Punycode standard.</p>
<p>The <code>punycode</code> module is a third-party dependency used by Node.js and
made available to developers as a convenience. Fixes or other modifications to
the module must be directed to the <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> project.</p>
<section><h3><code>punycode.decode(string)</code><span><a class="mark" href="#all_punycode_punycodedecodestring" id="all_punycode_punycodedecodestring">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_decode_string"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.1</span>
</div>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>punycode.decode()</code> method converts a <a href="https://tools.ietf.org/html/rfc3492">Punycode</a> string of ASCII-only
characters to the equivalent string of Unicode codepoints.</p>
<pre><code class="language-js">punycode.<span class="hljs-title function_">decode</span>(<span class="hljs-string">'maana-pta'</span>); <span class="hljs-comment">// 'mañana'</span>
punycode.<span class="hljs-title function_">decode</span>(<span class="hljs-string">'--dqo34k'</span>); <span class="hljs-comment">// '☃-⌘'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>punycode.encode(string)</code><span><a class="mark" href="#all_punycode_punycodeencodestring" id="all_punycode_punycodeencodestring">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_encode_string"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.1</span>
</div>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>punycode.encode()</code> method converts a string of Unicode codepoints to a
<a href="https://tools.ietf.org/html/rfc3492">Punycode</a> string of ASCII-only characters.</p>
<pre><code class="language-js">punycode.<span class="hljs-title function_">encode</span>(<span class="hljs-string">'mañana'</span>); <span class="hljs-comment">// 'maana-pta'</span>
punycode.<span class="hljs-title function_">encode</span>(<span class="hljs-string">'☃-⌘'</span>); <span class="hljs-comment">// '--dqo34k'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>punycode.toASCII(domain)</code><span><a class="mark" href="#all_punycode_punycodetoasciidomain" id="all_punycode_punycodetoasciidomain">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_toascii_domain"></a></h3>
<div class="api_metadata">
<span>Added in: v0.6.1</span>
</div>
<ul>
<li><code>domain</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>punycode.toASCII()</code> method converts a Unicode string representing an
Internationalized Domain Name to <a href="https://tools.ietf.org/html/rfc3492">Punycode</a>. Only the non-ASCII parts of the
domain name will be converted. Calling <code>punycode.toASCII()</code> on a string that
already only contains ASCII characters will have no effect.</p>
<pre><code class="language-js"><span class="hljs-comment">// encode domain names</span>
punycode.<span class="hljs-title function_">toASCII</span>(<span class="hljs-string">'mañana.com'</span>); <span class="hljs-comment">// 'xn--maana-pta.com'</span>
punycode.<span class="hljs-title function_">toASCII</span>(<span class="hljs-string">'☃-⌘.com'</span>); <span class="hljs-comment">// 'xn----dqo34k.com'</span>
punycode.<span class="hljs-title function_">toASCII</span>(<span class="hljs-string">'example.com'</span>); <span class="hljs-comment">// 'example.com'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>punycode.toUnicode(domain)</code><span><a class="mark" href="#all_punycode_punycodetounicodedomain" id="all_punycode_punycodetounicodedomain">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_tounicode_domain"></a></h3>
<div class="api_metadata">
<span>Added in: v0.6.1</span>
</div>
<ul>
<li><code>domain</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>punycode.toUnicode()</code> method converts a string representing a domain name
containing <a href="https://tools.ietf.org/html/rfc3492">Punycode</a> encoded characters into Unicode. Only the <a href="https://tools.ietf.org/html/rfc3492">Punycode</a>
encoded parts of the domain name are be converted.</p>
<pre><code class="language-js"><span class="hljs-comment">// decode domain names</span>
punycode.<span class="hljs-title function_">toUnicode</span>(<span class="hljs-string">'xn--maana-pta.com'</span>); <span class="hljs-comment">// 'mañana.com'</span>
punycode.<span class="hljs-title function_">toUnicode</span>(<span class="hljs-string">'xn----dqo34k.com'</span>); <span class="hljs-comment">// '☃-⌘.com'</span>
punycode.<span class="hljs-title function_">toUnicode</span>(<span class="hljs-string">'example.com'</span>); <span class="hljs-comment">// 'example.com'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>punycode.ucs2</code><span><a class="mark" href="#all_punycode_punycodeucs2" id="all_punycode_punycodeucs2">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_ucs2"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<h4><code>punycode.ucs2.decode(string)</code><span><a class="mark" href="#all_punycode_punycodeucs2decodestring" id="all_punycode_punycodeucs2decodestring">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_ucs2_decode_string"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>punycode.ucs2.decode()</code> method returns an array containing the numeric
codepoint values of each Unicode symbol in the string.</p>
<pre><code class="language-js">punycode.<span class="hljs-property">ucs2</span>.<span class="hljs-title function_">decode</span>(<span class="hljs-string">'abc'</span>); <span class="hljs-comment">// [0x61, 0x62, 0x63]</span>
<span class="hljs-comment">// surrogate pair for U+1D306 tetragram for centre:</span>
punycode.<span class="hljs-property">ucs2</span>.<span class="hljs-title function_">decode</span>(<span class="hljs-string">'\uD834\uDF06'</span>); <span class="hljs-comment">// [0x1D306]</span></code> <button class="copy-button">copy</button></pre>
<h4><code>punycode.ucs2.encode(codePoints)</code><span><a class="mark" href="#all_punycode_punycodeucs2encodecodepoints" id="all_punycode_punycodeucs2encodecodepoints">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_ucs2_encode_codepoints"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>codePoints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a></li>
</ul>
<p>The <code>punycode.ucs2.encode()</code> method returns a string based on an array of
numeric code point values.</p>
<pre><code class="language-js">punycode.<span class="hljs-property">ucs2</span>.<span class="hljs-title function_">encode</span>([<span class="hljs-number">0x61</span>, <span class="hljs-number">0x62</span>, <span class="hljs-number">0x63</span>]); <span class="hljs-comment">// 'abc'</span>
punycode.<span class="hljs-property">ucs2</span>.<span class="hljs-title function_">encode</span>([<span class="hljs-number">0x1D306</span>]); <span class="hljs-comment">// '\uD834\uDF06'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>punycode.version</code><span><a class="mark" href="#all_punycode_punycodeversion" id="all_punycode_punycodeversion">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_version"></a></h3>
<div class="api_metadata">
<span>Added in: v0.6.1</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns a string identifying the current <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> version number.</p></section>
</section>
<section><h2>Query string<span><a class="mark" href="#all_querystring_query-string" id="all_querystring_query-string">#</a></span><a aria-hidden="true" class="legacy" id="querystring_query_string"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/querystring.js">lib/querystring.js</a></p>
<p>The <code>node:querystring</code> module provides utilities for parsing and formatting URL
query strings. It can be accessed using:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> querystring = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:querystring'</span>);</code> <button class="copy-button">copy</button></pre>
<p><code>querystring</code> is more performant than <a href="#all_url_class-urlsearchparams" class="type"><URLSearchParams></a> but is not a
standardized API. Use <a href="#all_url_class-urlsearchparams" class="type"><URLSearchParams></a> when performance is not critical or
when compatibility with browser code is desirable.</p>
<section><h3><code>querystring.decode()</code><span><a class="mark" href="#all_querystring_querystringdecode" id="all_querystring_querystringdecode">#</a></span><a aria-hidden="true" class="legacy" id="querystring_querystring_decode"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<p>The <code>querystring.decode()</code> function is an alias for <code>querystring.parse()</code>.</p>
</section><section><h3><code>querystring.encode()</code><span><a class="mark" href="#all_querystring_querystringencode" id="all_querystring_querystringencode">#</a></span><a aria-hidden="true" class="legacy" id="querystring_querystring_encode"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<p>The <code>querystring.encode()</code> function is an alias for <code>querystring.stringify()</code>.</p>
</section><section><h3><code>querystring.escape(str)</code><span><a class="mark" href="#all_querystring_querystringescapestr" id="all_querystring_querystringescapestr">#</a></span><a aria-hidden="true" class="legacy" id="querystring_querystring_escape_str"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.25</span>
</div>
<ul>
<li><code>str</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>querystring.escape()</code> method performs URL percent-encoding on the given
<code>str</code> in a manner that is optimized for the specific requirements of URL
query strings.</p>
<p>The <code>querystring.escape()</code> method is used by <code>querystring.stringify()</code> and is
generally not expected to be used directly. It is exported primarily to allow
application code to provide a replacement percent-encoding implementation if
necessary by assigning <code>querystring.escape</code> to an alternative function.</p>
</section><section><h3><code>querystring.parse(str[, sep[, eq[, options]]])</code><span><a class="mark" href="#all_querystring_querystringparsestr-sep-eq-options" id="all_querystring_querystringparsestr-sep-eq-options">#</a></span><a aria-hidden="true" class="legacy" id="querystring_querystring_parse_str_sep_eq_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Multiple empty entries are now parsed correctly (e.g. <code>&=&=</code>).</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The returned object no longer inherits from <code>Object.prototype</code>.</p></td></tr>
<tr><td>v6.0.0, v4.2.4</td>
<td><p>The <code>eq</code> parameter may now have a length of more than <code>1</code>.</p></td></tr>
<tr><td>v0.1.25</td>
<td><p><span>Added in: v0.1.25</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>str</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The URL query string to parse</li>
<li><code>sep</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The substring used to delimit key and value pairs in the
query string. <strong>Default:</strong> <code>'&'</code>.</li>
<li><code>eq</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>. The substring used to delimit keys and values in the
query string. <strong>Default:</strong> <code>'='</code>.</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>decodeURIComponent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to use when decoding
percent-encoded characters in the query string. <strong>Default:</strong>
<code>querystring.unescape()</code>.</li>
<li><code>maxKeys</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the maximum number of keys to parse.
Specify <code>0</code> to remove key counting limitations. <strong>Default:</strong> <code>1000</code>.</li>
</ul>
</li>
</ul>
<p>The <code>querystring.parse()</code> method parses a URL query string (<code>str</code>) into a
collection of key and value pairs.</p>
<p>For example, the query string <code>'foo=bar&abc=xyz&abc=123'</code> is parsed into:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"foo"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"bar"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"abc"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-string">"xyz"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"123"</span><span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The object returned by the <code>querystring.parse()</code> method <em>does not</em>
prototypically inherit from the JavaScript <code>Object</code>. This means that typical
<code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others
are not defined and <em>will not work</em>.</p>
<p>By default, percent-encoded characters within the query string will be assumed
to use UTF-8 encoding. If an alternative character encoding is used, then an
alternative <code>decodeURIComponent</code> option will need to be specified:</p>
<pre><code class="language-js"><span class="hljs-comment">// Assuming gbkDecodeURIComponent function already exists...</span>
querystring.<span class="hljs-title function_">parse</span>(<span class="hljs-string">'w=%D6%D0%CE%C4&foo=bar'</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>,
{ <span class="hljs-attr">decodeURIComponent</span>: gbkDecodeURIComponent });</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>querystring.stringify(obj[, sep[, eq[, options]]])</code><span><a class="mark" href="#all_querystring_querystringstringifyobj-sep-eq-options" id="all_querystring_querystringstringifyobj-sep-eq-options">#</a></span><a aria-hidden="true" class="legacy" id="querystring_querystring_stringify_obj_sep_eq_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.25</span>
</div>
<ul>
<li><code>obj</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The object to serialize into a URL query string</li>
<li><code>sep</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The substring used to delimit key and value pairs in the
query string. <strong>Default:</strong> <code>'&'</code>.</li>
<li><code>eq</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>. The substring used to delimit keys and values in the
query string. <strong>Default:</strong> <code>'='</code>.</li>
<li><code>options</code>
<ul>
<li><code>encodeURIComponent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to use when converting
URL-unsafe characters to percent-encoding in the query string. <strong>Default:</strong>
<code>querystring.escape()</code>.</li>
</ul>
</li>
</ul>
<p>The <code>querystring.stringify()</code> method produces a URL query string from a
given <code>obj</code> by iterating through the object's "own properties".</p>
<p>It serializes the following types of values passed in <code>obj</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#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint></a> | <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#String_type" class="type"><string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type"><bigint[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean[]></a>
The numeric values must be finite. Any other input values will be coerced to
empty strings.</p>
<pre><code class="language-js">querystring.<span class="hljs-title function_">stringify</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span>, <span class="hljs-attr">baz</span>: [<span class="hljs-string">'qux'</span>, <span class="hljs-string">'quux'</span>], <span class="hljs-attr">corge</span>: <span class="hljs-string">''</span> });
<span class="hljs-comment">// Returns 'foo=bar&baz=qux&baz=quux&corge='</span>
querystring.<span class="hljs-title function_">stringify</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span>, <span class="hljs-attr">baz</span>: <span class="hljs-string">'qux'</span> }, <span class="hljs-string">';'</span>, <span class="hljs-string">':'</span>);
<span class="hljs-comment">// Returns 'foo:bar;baz:qux'</span></code> <button class="copy-button">copy</button></pre>
<p>By default, characters requiring percent-encoding within the query string will
be encoded as UTF-8. If an alternative encoding is required, then an alternative
<code>encodeURIComponent</code> option will need to be specified:</p>
<pre><code class="language-js"><span class="hljs-comment">// Assuming gbkEncodeURIComponent function already exists,</span>
querystring.<span class="hljs-title function_">stringify</span>({ <span class="hljs-attr">w</span>: <span class="hljs-string">'中文'</span>, <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span> }, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>,
{ <span class="hljs-attr">encodeURIComponent</span>: gbkEncodeURIComponent });</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>querystring.unescape(str)</code><span><a class="mark" href="#all_querystring_querystringunescapestr" id="all_querystring_querystringunescapestr">#</a></span><a aria-hidden="true" class="legacy" id="querystring_querystring_unescape_str"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.25</span>
</div>
<ul>
<li><code>str</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>querystring.unescape()</code> method performs decoding of URL percent-encoded
characters on the given <code>str</code>.</p>
<p>The <code>querystring.unescape()</code> method is used by <code>querystring.parse()</code> and is
generally not expected to be used directly. It is exported primarily to allow
application code to provide a replacement decoding implementation if
necessary by assigning <code>querystring.unescape</code> to an alternative function.</p>
<p>By default, the <code>querystring.unescape()</code> method will attempt to use the
JavaScript built-in <code>decodeURIComponent()</code> method to decode. If that fails,
a safer equivalent that does not throw on malformed URLs will be used.</p></section>
</section>
<section><h2>Readline<span><a class="mark" href="#all_readline_readline" id="all_readline_readline">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/readline.js">lib/readline.js</a></p>
<p>The <code>node:readline</code> module provides an interface for reading data from a
<a href="#all_stream_readable-streams">Readable</a> stream (such as <a href="#all_process_processstdin"><code>process.stdin</code></a>) one line at a time.</p>
<p>To use the promise-based APIs:</p>
<pre class="with-51-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-keyword">as</span> readline <span class="hljs-keyword">from</span> <span class="hljs-string">'node:readline/promises'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> readline = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline/promises'</span>);</code><button class="copy-button">copy</button></pre>
<p>To use the callback and sync APIs:</p>
<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-keyword">as</span> readline <span class="hljs-keyword">from</span> <span class="hljs-string">'node:readline'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> readline = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);</code><button class="copy-button">copy</button></pre>
<p>The following simple example illustrates the basic use of the <code>node:readline</code>
module.</p>
<pre class="with-65-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-keyword">as</span> readline <span class="hljs-keyword">from</span> <span class="hljs-string">'node:readline/promises'</span>;
<span class="hljs-keyword">import</span> { stdin <span class="hljs-keyword">as</span> input, stdout <span class="hljs-keyword">as</span> output } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> rl = readline.<span class="hljs-title function_">createInterface</span>({ input, output });
<span class="hljs-keyword">const</span> answer = <span class="hljs-keyword">await</span> rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'What do you think of Node.js? '</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Thank you for your valuable feedback: <span class="hljs-subst">${answer}</span>`</span>);
rl.<span class="hljs-title function_">close</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> readline = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">stdin</span>: input, <span class="hljs-attr">stdout</span>: output } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> rl = readline.<span class="hljs-title function_">createInterface</span>({ input, output });
rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'What do you think of Node.js? '</span>, <span class="hljs-function">(<span class="hljs-params">answer</span>) =></span> {
<span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> Log the answer in a database</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Thank you for your valuable feedback: <span class="hljs-subst">${answer}</span>`</span>);
rl.<span class="hljs-title function_">close</span>();
});</code><button class="copy-button">copy</button></pre>
<p>Once this code is invoked, the Node.js application will not terminate until the
<code>readline.Interface</code> is closed because the interface waits for data to be
received on the <code>input</code> stream.</p>
<p><a id="readline_class_interface"></a></p>
<section><h3>Class: <code>InterfaceConstructor</code><span><a class="mark" href="#all_readline_class-interfaceconstructor" id="all_readline_class-interfaceconstructor">#</a></span><a aria-hidden="true" class="legacy" id="readline_class_interfaceconstructor"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>Instances of the <code>InterfaceConstructor</code> class are constructed using the
<code>readlinePromises.createInterface()</code> or <code>readline.createInterface()</code> method.
Every instance is associated with a single <code>input</code> <a href="#all_stream_readable-streams">Readable</a> stream and a
single <code>output</code> <a href="#all_stream_writable-streams">Writable</a> stream.
The <code>output</code> stream is used to print prompts for user input that arrives on,
and is read from, the <code>input</code> stream.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_readline_event-close" id="all_readline_event-close">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_close"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div>
<p>The <code>'close'</code> event is emitted when one of the following occur:</p>
<ul>
<li>The <code>rl.close()</code> method is called and the <code>InterfaceConstructor</code> instance has
relinquished control over the <code>input</code> and <code>output</code> streams;</li>
<li>The <code>input</code> stream receives its <code>'end'</code> event;</li>
<li>The <code>input</code> stream receives <kbd>Ctrl</kbd>+<kbd>D</kbd> to signal
end-of-transmission (EOT);</li>
<li>The <code>input</code> stream receives <kbd>Ctrl</kbd>+<kbd>C</kbd> to signal <code>SIGINT</code>
and there is no <code>'SIGINT'</code> event listener registered on the
<code>InterfaceConstructor</code> instance.</li>
</ul>
<p>The listener function is called without passing any arguments.</p>
<p>The <code>InterfaceConstructor</code> instance is finished once the <code>'close'</code> event is
emitted.</p>
<h4>Event: <code>'line'</code><span><a class="mark" href="#all_readline_event-line" id="all_readline_event-line">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_line"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div>
<p>The <code>'line'</code> event is emitted whenever the <code>input</code> stream receives an
end-of-line input (<code>\n</code>, <code>\r</code>, or <code>\r\n</code>). This usually occurs when the user
presses <kbd>Enter</kbd> or <kbd>Return</kbd>.</p>
<p>The <code>'line'</code> event is also emitted if new data has been read from a stream and
that stream ends without a final end-of-line marker.</p>
<p>The listener function is called with a string containing the single line of
received input.</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">input</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">${input}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'history'</code><span><a class="mark" href="#all_readline_event-history" id="all_readline_event-history">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_history"></a></h4>
<div class="api_metadata">
<span>Added in: v15.8.0, v14.18.0</span>
</div>
<p>The <code>'history'</code> event is emitted whenever the history array has changed.</p>
<p>The listener function is called with an array containing the history array.
It will reflect all changes, added lines and removed lines due to
<code>historySize</code> and <code>removeHistoryDuplicates</code>.</p>
<p>The primary purpose is to allow a listener to persist the history.
It is also possible for the listener to change the history object. This
could be useful to prevent certain lines to be added to the history, like
a password.</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'history'</span>, <span class="hljs-function">(<span class="hljs-params">history</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">${history}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'pause'</code><span><a class="mark" href="#all_readline_event-pause" id="all_readline_event-pause">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_pause"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div>
<p>The <code>'pause'</code> event is emitted when one of the following occur:</p>
<ul>
<li>The <code>input</code> stream is paused.</li>
<li>The <code>input</code> stream is not paused and receives the <code>'SIGCONT'</code> event. (See
events <a href="#all_readline_event-sigtstp"><code>'SIGTSTP'</code></a> and <a href="#all_readline_event-sigcont"><code>'SIGCONT'</code></a>.)</li>
</ul>
<p>The listener function is called without passing any arguments.</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'pause'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Readline paused.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'resume'</code><span><a class="mark" href="#all_readline_event-resume" id="all_readline_event-resume">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_resume"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div>
<p>The <code>'resume'</code> event is emitted whenever the <code>input</code> stream is resumed.</p>
<p>The listener function is called without passing any arguments.</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'resume'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Readline resumed.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'SIGCONT'</code><span><a class="mark" href="#all_readline_event-sigcont" id="all_readline_event-sigcont">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_sigcont"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div>
<p>The <code>'SIGCONT'</code> event is emitted when a Node.js process previously moved into
the background using <kbd>Ctrl</kbd>+<kbd>Z</kbd> (i.e. <code>SIGTSTP</code>) is then
brought back to the foreground using <a href="http://man7.org/linux/man-pages/man1/fg.1p.html"><code>fg(1p)</code></a>.</p>
<p>If the <code>input</code> stream was paused <em>before</em> the <code>SIGTSTP</code> request, this event will
not be emitted.</p>
<p>The listener function is invoked without passing any arguments.</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGCONT'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// `prompt` will automatically resume the stream</span>
rl.<span class="hljs-title function_">prompt</span>();
});</code> <button class="copy-button">copy</button></pre>
<p>The <code>'SIGCONT'</code> event is <em>not</em> supported on Windows.</p>
<h4>Event: <code>'SIGINT'</code><span><a class="mark" href="#all_readline_event-sigint" id="all_readline_event-sigint">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_sigint"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<p>The <code>'SIGINT'</code> event is emitted whenever the <code>input</code> stream receives
a <kbd>Ctrl+C</kbd> input, known typically as <code>SIGINT</code>. If there are no
<code>'SIGINT'</code> event listeners registered when the <code>input</code> stream receives a
<code>SIGINT</code>, the <code>'pause'</code> event will be emitted.</p>
<p>The listener function is invoked without passing any arguments.</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, <span class="hljs-function">() =></span> {
rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'Are you sure you want to exit? '</span>, <span class="hljs-function">(<span class="hljs-params">answer</span>) =></span> {
<span class="hljs-keyword">if</span> (answer.<span class="hljs-title function_">match</span>(<span class="hljs-regexp">/^y(es)?$/i</span>)) rl.<span class="hljs-title function_">pause</span>();
});
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'SIGTSTP'</code><span><a class="mark" href="#all_readline_event-sigtstp" id="all_readline_event-sigtstp">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_sigtstp"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div>
<p>The <code>'SIGTSTP'</code> event is emitted when the <code>input</code> stream receives
a <kbd>Ctrl</kbd>+<kbd>Z</kbd> input, typically known as <code>SIGTSTP</code>. If there are
no <code>'SIGTSTP'</code> event listeners registered when the <code>input</code> stream receives a
<code>SIGTSTP</code>, the Node.js process will be sent to the background.</p>
<p>When the program is resumed using <a href="http://man7.org/linux/man-pages/man1/fg.1p.html"><code>fg(1p)</code></a>, the <code>'pause'</code> and <code>'SIGCONT'</code> events
will be emitted. These can be used to resume the <code>input</code> stream.</p>
<p>The <code>'pause'</code> and <code>'SIGCONT'</code> events will not be emitted if the <code>input</code> was
paused before the process was sent to the background.</p>
<p>The listener function is invoked without passing any arguments.</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGTSTP'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// This will override SIGTSTP and prevent the program from going to the</span>
<span class="hljs-comment">// background.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Caught SIGTSTP.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>The <code>'SIGTSTP'</code> event is <em>not</em> supported on Windows.</p>
<h4><code>rl.close()</code><span><a class="mark" href="#all_readline_rlclose" id="all_readline_rlclose">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_close"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div>
<p>The <code>rl.close()</code> method closes the <code>InterfaceConstructor</code> instance and
relinquishes control over the <code>input</code> and <code>output</code> streams. When called,
the <code>'close'</code> event will be emitted.</p>
<p>Calling <code>rl.close()</code> does not immediately stop other events (including <code>'line'</code>)
from being emitted by the <code>InterfaceConstructor</code> instance.</p>
<h4><code>rl.pause()</code><span><a class="mark" href="#all_readline_rlpause" id="all_readline_rlpause">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_pause"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<p>The <code>rl.pause()</code> method pauses the <code>input</code> stream, allowing it to be resumed
later if necessary.</p>
<p>Calling <code>rl.pause()</code> does not immediately pause other events (including
<code>'line'</code>) from being emitted by the <code>InterfaceConstructor</code> instance.</p>
<h4><code>rl.prompt([preserveCursor])</code><span><a class="mark" href="#all_readline_rlpromptpreservecursor" id="all_readline_rlpromptpreservecursor">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_prompt_preservecursor"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div>
<ul>
<li><code>preserveCursor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, prevents the cursor placement from
being reset to <code>0</code>.</li>
</ul>
<p>The <code>rl.prompt()</code> method writes the <code>InterfaceConstructor</code> instances configured
<code>prompt</code> to a new line in <code>output</code> in order to provide a user with a new
location at which to provide input.</p>
<p>When called, <code>rl.prompt()</code> will resume the <code>input</code> stream if it has been
paused.</p>
<p>If the <code>InterfaceConstructor</code> was created with <code>output</code> set to <code>null</code> or
<code>undefined</code> the prompt is not written.</p>
<h4><code>rl.resume()</code><span><a class="mark" href="#all_readline_rlresume" id="all_readline_rlresume">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_resume"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<p>The <code>rl.resume()</code> method resumes the <code>input</code> stream if it has been paused.</p>
<h4><code>rl.setPrompt(prompt)</code><span><a class="mark" href="#all_readline_rlsetpromptprompt" id="all_readline_rlsetpromptprompt">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_setprompt_prompt"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div>
<ul>
<li><code>prompt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>rl.setPrompt()</code> method sets the prompt that will be written to <code>output</code>
whenever <code>rl.prompt()</code> is called.</p>
<h4><code>rl.getPrompt()</code><span><a class="mark" href="#all_readline_rlgetprompt" id="all_readline_rlgetprompt">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_getprompt"></a></h4>
<div class="api_metadata">
<span>Added in: v15.3.0, v14.17.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> the current prompt string</li>
</ul>
<p>The <code>rl.getPrompt()</code> method returns the current prompt used by <code>rl.prompt()</code>.</p>
<h4><code>rl.write(data[, key])</code><span><a class="mark" href="#all_readline_rlwritedata-key" id="all_readline_rlwritedata-key">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_write_data_key"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>ctrl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> to indicate the <kbd>Ctrl</kbd> key.</li>
<li><code>meta</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> to indicate the <kbd>Meta</kbd> key.</li>
<li><code>shift</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> to indicate the <kbd>Shift</kbd> key.</li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the a key.</li>
</ul>
</li>
</ul>
<p>The <code>rl.write()</code> method will write either <code>data</code> or a key sequence identified
by <code>key</code> to the <code>output</code>. The <code>key</code> argument is supported only if <code>output</code> is
a <a href="tty.html">TTY</a> text terminal. See <a href="#all_readline_tty-keybindings">TTY keybindings</a> for a list of key
combinations.</p>
<p>If <code>key</code> is specified, <code>data</code> is ignored.</p>
<p>When called, <code>rl.write()</code> will resume the <code>input</code> stream if it has been
paused.</p>
<p>If the <code>InterfaceConstructor</code> was created with <code>output</code> set to <code>null</code> or
<code>undefined</code> the <code>data</code> and <code>key</code> are not written.</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">write</span>(<span class="hljs-string">'Delete this!'</span>);
<span class="hljs-comment">// Simulate Ctrl+U to delete the line written previously</span>
rl.<span class="hljs-title function_">write</span>(<span class="hljs-literal">null</span>, { <span class="hljs-attr">ctrl</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'u'</span> });</code> <button class="copy-button">copy</button></pre>
<p>The <code>rl.write()</code> method will write the data to the <code>readline</code> <code>Interface</code>'s
<code>input</code> <em>as if it were provided by the user</em>.</p>
<h4><code>rl[Symbol.asyncIterator]()</code><span><a class="mark" href="#all_readline_rlsymbolasynciterator" id="all_readline_rlsymbolasynciterator">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_symbol_asynciterator"></a></h4>
<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, v10.17.0</td>
<td><p>Symbol.asyncIterator support is no longer experimental.</p></td></tr>
<tr><td>v11.4.0, v10.16.0</td>
<td><p><span>Added in: v11.4.0, v10.16.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></li>
</ul>
<p>Create an <code>AsyncIterator</code> object that iterates through each line in the input
stream as a string. This method allows asynchronous iteration of
<code>InterfaceConstructor</code> objects through <code>for await...of</code> loops.</p>
<p>Errors in the input stream are not forwarded.</p>
<p>If the loop is terminated with <code>break</code>, <code>throw</code>, or <code>return</code>,
<a href="#all_readline_rlclose"><code>rl.close()</code></a> will be called. In other words, iterating over a
<code>InterfaceConstructor</code> will always consume the input stream fully.</p>
<p>Performance is not on par with the traditional <code>'line'</code> event API. Use <code>'line'</code>
instead for performance-sensitive applications.</p>
<pre><code class="language-js"><span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">processLineByLine</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> rl = readline.<span class="hljs-title function_">createInterface</span>({
<span class="hljs-comment">// ...</span>
});
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> line <span class="hljs-keyword">of</span> rl) {
<span class="hljs-comment">// Each line in the readline input will be successively available here as</span>
<span class="hljs-comment">// `line`.</span>
}
}</code> <button class="copy-button">copy</button></pre>
<p><code>readline.createInterface()</code> will start to consume the input stream once
invoked. Having asynchronous operations between interface creation and
asynchronous iteration may result in missed lines.</p>
<h4><code>rl.line</code><span><a class="mark" href="#all_readline_rlline" id="all_readline_rlline">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_line"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.8.0, v14.18.0</td>
<td><p>Value will always be a string, never undefined.</p></td></tr>
<tr><td>v0.1.98</td>
<td><p><span>Added in: v0.1.98</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The current input data being processed by node.</p>
<p>This can be used when collecting input from a TTY stream to retrieve the
current value that has been processed thus far, prior to the <code>line</code> event
being emitted. Once the <code>line</code> event has been emitted, this property will
be an empty string.</p>
<p>Be aware that modifying the value during the instance runtime may have
unintended consequences if <code>rl.cursor</code> is not also controlled.</p>
<p><strong>If not using a TTY stream for input, use the <a href="#all_readline_event-line"><code>'line'</code></a> event.</strong></p>
<p>One possible use case would be as follows:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> values = [<span class="hljs-string">'lorem ipsum'</span>, <span class="hljs-string">'dolor sit amet'</span>];
<span class="hljs-keyword">const</span> rl = readline.<span class="hljs-title function_">createInterface</span>(process.<span class="hljs-property">stdin</span>);
<span class="hljs-keyword">const</span> showResults = <span class="hljs-title function_">debounce</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
<span class="hljs-string">'\n'</span>,
values.<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">val</span>) =></span> val.<span class="hljs-title function_">startsWith</span>(rl.<span class="hljs-property">line</span>)).<span class="hljs-title function_">join</span>(<span class="hljs-string">' '</span>),
);
}, <span class="hljs-number">300</span>);
process.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'keypress'</span>, <span class="hljs-function">(<span class="hljs-params">c, k</span>) =></span> {
<span class="hljs-title function_">showResults</span>();
});</code> <button class="copy-button">copy</button></pre>
<h4><code>rl.cursor</code><span><a class="mark" href="#all_readline_rlcursor" id="all_readline_rlcursor">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_cursor"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>The cursor position relative to <code>rl.line</code>.</p>
<p>This will track where the current cursor lands in the input string, when
reading input from a TTY stream. The position of cursor determines the
portion of the input string that will be modified as input is processed,
as well as the column where the terminal caret will be rendered.</p>
<h4><code>rl.getCursorPos()</code><span><a class="mark" href="#all_readline_rlgetcursorpos" id="all_readline_rlgetcursorpos">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_getcursorpos"></a></h4>
<div class="api_metadata">
<span>Added in: v13.5.0, v12.16.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>rows</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the row of the prompt the cursor currently lands on</li>
<li><code>cols</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the screen column the cursor currently lands on</li>
</ul>
</li>
</ul>
<p>Returns the real position of the cursor in relation to the input
prompt + string. Long input (wrapping) strings, as well as multiple
line prompts are included in the calculations.</p>
</section><section><h3>Promises API<span><a class="mark" href="#all_readline_promises-api" id="all_readline_promises-api">#</a></span><a aria-hidden="true" class="legacy" id="readline_promises_api"></a></h3>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<h4>Class: <code>readlinePromises.Interface</code><span><a class="mark" href="#all_readline_class-readlinepromisesinterface" id="all_readline_class-readlinepromisesinterface">#</a></span><a aria-hidden="true" class="legacy" id="readline_class_readlinepromises_interface"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Extends: <a href="#all_readline_class-interfaceconstructor" class="type"><readline.InterfaceConstructor></a></li>
</ul>
<p>Instances of the <code>readlinePromises.Interface</code> class are constructed using the
<code>readlinePromises.createInterface()</code> method. Every instance is associated with a
single <code>input</code> <a href="#all_stream_readable-streams">Readable</a> stream and a single <code>output</code> <a href="#all_stream_writable-streams">Writable</a> stream.
The <code>output</code> stream is used to print prompts for user input that arrives on,
and is read from, the <code>input</code> stream.</p>
<h5><code>rl.question(query[, options])</code><span><a class="mark" href="#all_readline_rlquestionquery-options" id="all_readline_rlquestionquery-options">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_question_query_options"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li><code>query</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A statement or query to write to <code>output</code>, prepended to the
prompt.</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="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Optionally allows the <code>question()</code> to be canceled
using an <code>AbortSignal</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> A promise that is fulfilled with the user's
input in response to the <code>query</code>.</li>
</ul>
<p>The <code>rl.question()</code> method displays the <code>query</code> by writing it to the <code>output</code>,
waits for user input to be provided on <code>input</code>, then invokes the <code>callback</code>
function passing the provided input as the first argument.</p>
<p>When called, <code>rl.question()</code> will resume the <code>input</code> stream if it has been
paused.</p>
<p>If the <code>readlinePromises.Interface</code> was created with <code>output</code> set to <code>null</code> or
<code>undefined</code> the <code>query</code> is not written.</p>
<p>If the question is called after <code>rl.close()</code>, it returns a rejected promise.</p>
<p>Example usage:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">const</span> answer = <span class="hljs-keyword">await</span> rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'What is your favorite food? '</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Oh, so your favorite food is <span class="hljs-subst">${answer}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<p>Using an <code>AbortSignal</code> to cancel a question.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">const</span> signal = <span class="hljs-title class_">AbortSignal</span>.<span class="hljs-title function_">timeout</span>(<span class="hljs-number">10_000</span>);
signal.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'abort'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The food question timed out'</span>);
}, { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span> });
<span class="hljs-keyword">const</span> answer = <span class="hljs-keyword">await</span> rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'What is your favorite food? '</span>, { signal });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Oh, so your favorite food is <span class="hljs-subst">${answer}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<h4>Class: <code>readlinePromises.Readline</code><span><a class="mark" href="#all_readline_class-readlinepromisesreadline" id="all_readline_class-readlinepromisesreadline">#</a></span><a aria-hidden="true" class="legacy" id="readline_class_readlinepromises_readline"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<h5><code>new readlinePromises.Readline(stream[, options])</code><span><a class="mark" href="#all_readline_new-readlinepromisesreadlinestream-options" id="all_readline_new-readlinepromisesreadlinestream-options">#</a></span><a aria-hidden="true" class="legacy" id="readline_new_readlinepromises_readline_stream_options"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a> A <a href="tty.html">TTY</a> 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>autoCommit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, no need to call <code>rl.commit()</code>.</li>
</ul>
</li>
</ul>
<h5><code>rl.clearLine(dir)</code><span><a class="mark" href="#all_readline_rlclearlinedir" id="all_readline_rlclearlinedir">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_clearline_dir"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a>
<ul>
<li><code>-1</code>: to the left from cursor</li>
<li><code>1</code>: to the right from cursor</li>
<li><code>0</code>: the entire line</li>
</ul>
</li>
<li>Returns: this</li>
</ul>
<p>The <code>rl.clearLine()</code> method adds to the internal list of pending action an
action that clears current line of the associated <code>stream</code> in a specified
direction identified by <code>dir</code>.
Call <code>rl.commit()</code> to see the effect of this method, unless <code>autoCommit: true</code>
was passed to the constructor.</p>
<h5><code>rl.clearScreenDown()</code><span><a class="mark" href="#all_readline_rlclearscreendown" id="all_readline_rlclearscreendown">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_clearscreendown"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Returns: this</li>
</ul>
<p>The <code>rl.clearScreenDown()</code> method adds to the internal list of pending action an
action that clears the associated stream from the current position of the
cursor down.
Call <code>rl.commit()</code> to see the effect of this method, unless <code>autoCommit: true</code>
was passed to the constructor.</p>
<h5><code>rl.commit()</code><span><a class="mark" href="#all_readline_rlcommit" id="all_readline_rlcommit">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_commit"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>The <code>rl.commit()</code> method sends all the pending actions to the associated
<code>stream</code> and clears the internal list of pending actions.</p>
<h5><code>rl.cursorTo(x[, y])</code><span><a class="mark" href="#all_readline_rlcursortox-y" id="all_readline_rlcursortox-y">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_cursorto_x_y"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li><code>x</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>y</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li>Returns: this</li>
</ul>
<p>The <code>rl.cursorTo()</code> method adds to the internal list of pending action an action
that moves cursor to the specified position in the associated <code>stream</code>.
Call <code>rl.commit()</code> to see the effect of this method, unless <code>autoCommit: true</code>
was passed to the constructor.</p>
<h5><code>rl.moveCursor(dx, dy)</code><span><a class="mark" href="#all_readline_rlmovecursordx-dy" id="all_readline_rlmovecursordx-dy">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_movecursor_dx_dy"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li><code>dx</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>dy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li>Returns: this</li>
</ul>
<p>The <code>rl.moveCursor()</code> method adds to the internal list of pending action an
action that moves the cursor <em>relative</em> to its current position in the
associated <code>stream</code>.
Call <code>rl.commit()</code> to see the effect of this method, unless <code>autoCommit: true</code>
was passed to the constructor.</p>
<h5><code>rl.rollback()</code><span><a class="mark" href="#all_readline_rlrollback" id="all_readline_rlrollback">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_rollback"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Returns: this</li>
</ul>
<p>The <code>rl.rollback</code> methods clears the internal list of pending actions without
sending it to the associated <code>stream</code>.</p>
<h4><code>readlinePromises.createInterface(options)</code><span><a class="mark" href="#all_readline_readlinepromisescreateinterfaceoptions" id="all_readline_readlinepromisescreateinterfaceoptions">#</a></span><a aria-hidden="true" class="legacy" id="readline_readlinepromises_createinterface_options"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.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>
<ul>
<li><code>input</code> <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a> The <a href="#all_stream_readable-streams">Readable</a> stream to listen to. This option
is <em>required</em>.</li>
<li><code>output</code> <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a> The <a href="#all_stream_writable-streams">Writable</a> stream to write readline data
to.</li>
<li><code>completer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> An optional function used for Tab autocompletion.</li>
<li><code>terminal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the <code>input</code> and <code>output</code> streams should be
treated like a TTY, and have ANSI/VT100 escape codes written to it.
<strong>Default:</strong> checking <code>isTTY</code> on the <code>output</code> stream upon instantiation.</li>
<li><code>history</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Initial list of history lines. This option makes sense
only if <code>terminal</code> is set to <code>true</code> by the user or by an internal <code>output</code>
check, otherwise the history caching mechanism is not initialized at all.
<strong>Default:</strong> <code>[]</code>.</li>
<li><code>historySize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Maximum number of history lines retained. To disable
the history set this value to <code>0</code>. This option makes sense only if
<code>terminal</code> is set to <code>true</code> by the user or by an internal <code>output</code> check,
otherwise the history caching mechanism is not initialized at all.
<strong>Default:</strong> <code>30</code>.</li>
<li><code>removeHistoryDuplicates</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, when a new input line added
to the history list duplicates an older one, this removes the older line
from the list. <strong>Default:</strong> <code>false</code>.</li>
<li><code>prompt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The prompt string to use. <strong>Default:</strong> <code>'> '</code>.</li>
<li><code>crlfDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If the delay between <code>\r</code> and <code>\n</code> exceeds
<code>crlfDelay</code> milliseconds, both <code>\r</code> and <code>\n</code> will be treated as separate
end-of-line input. <code>crlfDelay</code> will be coerced to a number no less than
<code>100</code>. It can be set to <code>Infinity</code>, in which case <code>\r</code> followed by <code>\n</code>
will always be considered a single newline (which may be reasonable for
<a href="#all_readline_example-read-file-stream-line-by-line">reading files</a> with <code>\r\n</code> line delimiter). <strong>Default:</strong> <code>100</code>.</li>
<li><code>escapeCodeTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The duration <code>readlinePromises</code> will wait for a
character (when reading an ambiguous key sequence in milliseconds one that
can both form a complete key sequence using the input read so far and can
take additional input to complete a longer key sequence).
<strong>Default:</strong> <code>500</code>.</li>
<li><code>tabSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of spaces a tab is equal to (minimum 1).
<strong>Default:</strong> <code>8</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_readline_class-readlinepromisesinterface" class="type"><readlinePromises.Interface></a></li>
</ul>
<p>The <code>readlinePromises.createInterface()</code> method creates a new <code>readlinePromises.Interface</code>
instance.</p>
<pre class="with-62-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> { createInterface } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:readline/promises'</span>;
<span class="hljs-keyword">import</span> { stdin, stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
<span class="hljs-attr">input</span>: stdin,
<span class="hljs-attr">output</span>: stdout,
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createInterface } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline/promises'</span>);
<span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
<span class="hljs-attr">input</span>: process.<span class="hljs-property">stdin</span>,
<span class="hljs-attr">output</span>: process.<span class="hljs-property">stdout</span>,
});</code><button class="copy-button">copy</button></pre>
<p>Once the <code>readlinePromises.Interface</code> instance is created, the most common case
is to listen for the <code>'line'</code> event:</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</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">${line}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>If <code>terminal</code> is <code>true</code> for this instance then the <code>output</code> stream will get
the best compatibility if it defines an <code>output.columns</code> property and emits
a <code>'resize'</code> event on the <code>output</code> if or when the columns ever change
(<a href="#all_process_processstdout"><code>process.stdout</code></a> does this automatically when it is a TTY).</p>
<h5>Use of the <code>completer</code> function<span><a class="mark" href="#all_readline_use-of-the-completer-function" id="all_readline_use-of-the-completer-function">#</a></span><a aria-hidden="true" class="legacy" id="readline_use_of_the_completer_function"></a></h5>
<p>The <code>completer</code> function takes the current line entered by the user
as an argument, and returns an <code>Array</code> with 2 entries:</p>
<ul>
<li>An <code>Array</code> with matching entries for the completion.</li>
<li>The substring that was used for the matching.</li>
</ul>
<p>For instance: <code>[[substr1, substr2, ...], originalsubstring]</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">completer</span>(<span class="hljs-params">line</span>) {
<span class="hljs-keyword">const</span> completions = <span class="hljs-string">'.help .error .exit .quit .q'</span>.<span class="hljs-title function_">split</span>(<span class="hljs-string">' '</span>);
<span class="hljs-keyword">const</span> hits = completions.<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">c</span>) =></span> c.<span class="hljs-title function_">startsWith</span>(line));
<span class="hljs-comment">// Show all completions if none found</span>
<span class="hljs-keyword">return</span> [hits.<span class="hljs-property">length</span> ? hits : completions, line];
}</code> <button class="copy-button">copy</button></pre>
<p>The <code>completer</code> function can also return a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a>, or be asynchronous:</p>
<pre><code class="language-js"><span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">completer</span>(<span class="hljs-params">linePartial</span>) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">someAsyncWork</span>();
<span class="hljs-keyword">return</span> [[<span class="hljs-string">'123'</span>], linePartial];
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Callback API<span><a class="mark" href="#all_readline_callback-api" id="all_readline_callback-api">#</a></span><a aria-hidden="true" class="legacy" id="readline_callback_api"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div>
<h4>Class: <code>readline.Interface</code><span><a class="mark" href="#all_readline_class-readlineinterface" id="all_readline_class-readlineinterface">#</a></span><a aria-hidden="true" class="legacy" id="readline_class_readline_interface"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0</td>
<td><p>The class <code>readline.Interface</code> now inherits from <code>Interface</code>.</p></td></tr>
<tr><td>v0.1.104</td>
<td><p><span>Added in: v0.1.104</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Extends: <a href="#all_readline_class-interfaceconstructor" class="type"><readline.InterfaceConstructor></a></li>
</ul>
<p>Instances of the <code>readline.Interface</code> class are constructed using the
<code>readline.createInterface()</code> method. Every instance is associated with a
single <code>input</code> <a href="#all_stream_readable-streams">Readable</a> stream and a single <code>output</code> <a href="#all_stream_writable-streams">Writable</a> stream.
The <code>output</code> stream is used to print prompts for user input that arrives on,
and is read from, the <code>input</code> stream.</p>
<h5><code>rl.question(query[, options], callback)</code><span><a class="mark" href="#all_readline_rlquestionquery-options-callback" id="all_readline_rlquestionquery-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_question_query_options_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div>
<ul>
<li><code>query</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A statement or query to write to <code>output</code>, prepended to the
prompt.</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="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Optionally allows the <code>question()</code> to be canceled
using an <code>AbortController</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 that is invoked with the user's
input in response to the <code>query</code>.</li>
</ul>
<p>The <code>rl.question()</code> method displays the <code>query</code> by writing it to the <code>output</code>,
waits for user input to be provided on <code>input</code>, then invokes the <code>callback</code>
function passing the provided input as the first argument.</p>
<p>When called, <code>rl.question()</code> will resume the <code>input</code> stream if it has been
paused.</p>
<p>If the <code>readline.Interface</code> was created with <code>output</code> set to <code>null</code> or
<code>undefined</code> the <code>query</code> is not written.</p>
<p>The <code>callback</code> function passed to <code>rl.question()</code> does not follow the typical
pattern of accepting an <code>Error</code> object or <code>null</code> as the first argument.
The <code>callback</code> is called with the provided answer as the only argument.</p>
<p>An error will be thrown if calling <code>rl.question()</code> after <code>rl.close()</code>.</p>
<p>Example usage:</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'What is your favorite food? '</span>, <span class="hljs-function">(<span class="hljs-params">answer</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Oh, so your favorite food is <span class="hljs-subst">${answer}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Using an <code>AbortController</code> to cancel a question.</p>
<pre><code class="language-js"><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>;
rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'What is your favorite food? '</span>, { signal }, <span class="hljs-function">(<span class="hljs-params">answer</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Oh, so your favorite food is <span class="hljs-subst">${answer}</span>`</span>);
});
signal.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'abort'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The food question timed out'</span>);
}, { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span> });
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>(), <span class="hljs-number">10000</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>readline.clearLine(stream, dir[, callback])</code><span><a class="mark" href="#all_readline_readlineclearlinestream-dir-callback" id="all_readline_readlineclearlinestream-dir-callback">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline_clearline_stream_dir_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>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>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a></li>
<li><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a>
<ul>
<li><code>-1</code>: to the left from cursor</li>
<li><code>1</code>: to the right from cursor</li>
<li><code>0</code>: the entire line</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> Invoked once the operation completes.</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 <code>stream</code> 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>readline.clearLine()</code> method clears current line of given <a href="tty.html">TTY</a> stream
in a specified direction identified by <code>dir</code>.</p>
<h4><code>readline.clearScreenDown(stream[, callback])</code><span><a class="mark" href="#all_readline_readlineclearscreendownstream-callback" id="all_readline_readlineclearscreendownstream-callback">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline_clearscreendown_stream_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>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>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Invoked once the operation completes.</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 <code>stream</code> 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>readline.clearScreenDown()</code> method clears the given <a href="tty.html">TTY</a> stream from
the current position of the cursor down.</p>
<h4><code>readline.createInterface(options)</code><span><a class="mark" href="#all_readline_readlinecreateinterfaceoptions" id="all_readline_readlinecreateinterfaceoptions">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline_createinterface_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>v15.14.0, v14.18.0</td>
<td><p>The <code>signal</code> option is supported now.</p></td></tr>
<tr><td>v15.8.0, v14.18.0</td>
<td><p>The <code>history</code> option is supported now.</p></td></tr>
<tr><td>v13.9.0</td>
<td><p>The <code>tabSize</code> option is supported now.</p></td></tr>
<tr><td>v8.3.0, v6.11.4</td>
<td><p>Remove max limit of <code>crlfDelay</code> option.</p></td></tr>
<tr><td>v6.6.0</td>
<td><p>The <code>crlfDelay</code> option is supported now.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>prompt</code> option is supported now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>historySize</code> option can be <code>0</code> now.</p></td></tr>
<tr><td>v0.1.98</td>
<td><p><span>Added in: v0.1.98</span></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>input</code> <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a> The <a href="#all_stream_readable-streams">Readable</a> stream to listen to. This option
is <em>required</em>.</li>
<li><code>output</code> <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a> The <a href="#all_stream_writable-streams">Writable</a> stream to write readline data
to.</li>
<li><code>completer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> An optional function used for Tab autocompletion.</li>
<li><code>terminal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the <code>input</code> and <code>output</code> streams should be
treated like a TTY, and have ANSI/VT100 escape codes written to it.
<strong>Default:</strong> checking <code>isTTY</code> on the <code>output</code> stream upon instantiation.</li>
<li><code>history</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Initial list of history lines. This option makes sense
only if <code>terminal</code> is set to <code>true</code> by the user or by an internal <code>output</code>
check, otherwise the history caching mechanism is not initialized at all.
<strong>Default:</strong> <code>[]</code>.</li>
<li><code>historySize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Maximum number of history lines retained. To disable
the history set this value to <code>0</code>. This option makes sense only if
<code>terminal</code> is set to <code>true</code> by the user or by an internal <code>output</code> check,
otherwise the history caching mechanism is not initialized at all.
<strong>Default:</strong> <code>30</code>.</li>
<li><code>removeHistoryDuplicates</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, when a new input line added
to the history list duplicates an older one, this removes the older line
from the list. <strong>Default:</strong> <code>false</code>.</li>
<li><code>prompt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The prompt string to use. <strong>Default:</strong> <code>'> '</code>.</li>
<li><code>crlfDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If the delay between <code>\r</code> and <code>\n</code> exceeds
<code>crlfDelay</code> milliseconds, both <code>\r</code> and <code>\n</code> will be treated as separate
end-of-line input. <code>crlfDelay</code> will be coerced to a number no less than
<code>100</code>. It can be set to <code>Infinity</code>, in which case <code>\r</code> followed by <code>\n</code>
will always be considered a single newline (which may be reasonable for
<a href="#all_readline_example-read-file-stream-line-by-line">reading files</a> with <code>\r\n</code> line delimiter). <strong>Default:</strong> <code>100</code>.</li>
<li><code>escapeCodeTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The duration <code>readline</code> will wait for a
character (when reading an ambiguous key sequence in milliseconds one that
can both form a complete key sequence using the input read so far and can
take additional input to complete a longer key sequence).
<strong>Default:</strong> <code>500</code>.</li>
<li><code>tabSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of spaces a tab is equal to (minimum 1).
<strong>Default:</strong> <code>8</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows closing the interface using an AbortSignal.
Aborting the signal will internally call <code>close</code> on the interface.</li>
</ul>
</li>
<li>Returns: <a href="#all_readline_class-readlineinterface" class="type"><readline.Interface></a></li>
</ul>
<p>The <code>readline.createInterface()</code> method creates a new <code>readline.Interface</code>
instance.</p>
<pre class="with-53-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> { createInterface } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:readline'</span>;
<span class="hljs-keyword">import</span> { stdin, stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
<span class="hljs-attr">input</span>: stdin,
<span class="hljs-attr">output</span>: stdout,
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createInterface } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);
<span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
<span class="hljs-attr">input</span>: process.<span class="hljs-property">stdin</span>,
<span class="hljs-attr">output</span>: process.<span class="hljs-property">stdout</span>,
});</code><button class="copy-button">copy</button></pre>
<p>Once the <code>readline.Interface</code> instance is created, the most common case is to
listen for the <code>'line'</code> event:</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</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">${line}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>If <code>terminal</code> is <code>true</code> for this instance then the <code>output</code> stream will get
the best compatibility if it defines an <code>output.columns</code> property and emits
a <code>'resize'</code> event on the <code>output</code> if or when the columns ever change
(<a href="#all_process_processstdout"><code>process.stdout</code></a> does this automatically when it is a TTY).</p>
<p>When creating a <code>readline.Interface</code> using <code>stdin</code> as input, the program
will not terminate until it receives an <a href="https://en.wikipedia.org/wiki/End-of-file#EOF_character">EOF character</a>. To exit without
waiting for user input, call <code>process.stdin.unref()</code>.</p>
<h5>Use of the <code>completer</code> function<span><a class="mark" href="#all_readline_use-of-the-completer-function_1" id="all_readline_use-of-the-completer-function_1">#</a></span><a aria-hidden="true" class="legacy" id="readline_use_of_the_completer_function_1"></a></h5>
<p>The <code>completer</code> function takes the current line entered by the user
as an argument, and returns an <code>Array</code> with 2 entries:</p>
<ul>
<li>An <code>Array</code> with matching entries for the completion.</li>
<li>The substring that was used for the matching.</li>
</ul>
<p>For instance: <code>[[substr1, substr2, ...], originalsubstring]</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">completer</span>(<span class="hljs-params">line</span>) {
<span class="hljs-keyword">const</span> completions = <span class="hljs-string">'.help .error .exit .quit .q'</span>.<span class="hljs-title function_">split</span>(<span class="hljs-string">' '</span>);
<span class="hljs-keyword">const</span> hits = completions.<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">c</span>) =></span> c.<span class="hljs-title function_">startsWith</span>(line));
<span class="hljs-comment">// Show all completions if none found</span>
<span class="hljs-keyword">return</span> [hits.<span class="hljs-property">length</span> ? hits : completions, line];
}</code> <button class="copy-button">copy</button></pre>
<p>The <code>completer</code> function can be called asynchronously if it accepts two
arguments:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">completer</span>(<span class="hljs-params">linePartial, callback</span>) {
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, [[<span class="hljs-string">'123'</span>], linePartial]);
}</code> <button class="copy-button">copy</button></pre>
<h4><code>readline.cursorTo(stream, x[, y][, callback])</code><span><a class="mark" href="#all_readline_readlinecursortostream-x-y-callback" id="all_readline_readlinecursortostream-x-y-callback">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline_cursorto_stream_x_y_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>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>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a></li>
<li><code>x</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>y</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Invoked once the operation completes.</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 <code>stream</code> 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>readline.cursorTo()</code> method moves cursor to the specified position in a
given <a href="tty.html">TTY</a> <code>stream</code>.</p>
<h4><code>readline.moveCursor(stream, dx, dy[, callback])</code><span><a class="mark" href="#all_readline_readlinemovecursorstream-dx-dy-callback" id="all_readline_readlinemovecursorstream-dx-dy-callback">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline_movecursor_stream_dx_dy_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>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>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a></li>
<li><code>dx</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>dy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Invoked once the operation completes.</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 <code>stream</code> 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>readline.moveCursor()</code> method moves the cursor <em>relative</em> to its current
position in a given <a href="tty.html">TTY</a> <code>stream</code>.</p>
</section><section><h3><code>readline.emitKeypressEvents(stream[, interface])</code><span><a class="mark" href="#all_readline_readlineemitkeypresseventsstream-interface" id="all_readline_readlineemitkeypresseventsstream-interface">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline_emitkeypressevents_stream_interface"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a></li>
<li><code>interface</code> <a href="#all_readline_class-interfaceconstructor" class="type"><readline.InterfaceConstructor></a></li>
</ul>
<p>The <code>readline.emitKeypressEvents()</code> method causes the given <a href="#all_stream_readable-streams">Readable</a>
stream to begin emitting <code>'keypress'</code> events corresponding to received input.</p>
<p>Optionally, <code>interface</code> specifies a <code>readline.Interface</code> instance for which
autocompletion is disabled when copy-pasted input is detected.</p>
<p>If the <code>stream</code> is a <a href="tty.html">TTY</a>, then it must be in raw mode.</p>
<p>This is automatically called by any readline instance on its <code>input</code> if the
<code>input</code> is a terminal. Closing the <code>readline</code> instance does not stop
the <code>input</code> from emitting <code>'keypress'</code> events.</p>
<pre><code class="language-js">readline.<span class="hljs-title function_">emitKeypressEvents</span>(process.<span class="hljs-property">stdin</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">stdin</span>.<span class="hljs-property">isTTY</span>)
process.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">setRawMode</span>(<span class="hljs-literal">true</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Example: Tiny CLI<span><a class="mark" href="#all_readline_example-tiny-cli" id="all_readline_example-tiny-cli">#</a></span><a aria-hidden="true" class="legacy" id="readline_example_tiny_cli"></a></h3>
<p>The following example illustrates the use of <code>readline.Interface</code> class to
implement a small command-line interface:</p>
<pre class="with-53-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> { createInterface } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:readline'</span>;
<span class="hljs-keyword">import</span> { exit, stdin, stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
<span class="hljs-attr">input</span>: stdin,
<span class="hljs-attr">output</span>: stdout,
<span class="hljs-attr">prompt</span>: <span class="hljs-string">'OHAI> '</span>,
});
rl.<span class="hljs-title function_">prompt</span>();
rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> {
<span class="hljs-keyword">switch</span> (line.<span class="hljs-title function_">trim</span>()) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'hello'</span>:
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'world!'</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-attr">default</span>:
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Say what? I might have heard '<span class="hljs-subst">${line.trim()}</span>'`</span>);
<span class="hljs-keyword">break</span>;
}
rl.<span class="hljs-title function_">prompt</span>();
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Have a great day!'</span>);
<span class="hljs-title function_">exit</span>(<span class="hljs-number">0</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createInterface } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);
<span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
<span class="hljs-attr">input</span>: process.<span class="hljs-property">stdin</span>,
<span class="hljs-attr">output</span>: process.<span class="hljs-property">stdout</span>,
<span class="hljs-attr">prompt</span>: <span class="hljs-string">'OHAI> '</span>,
});
rl.<span class="hljs-title function_">prompt</span>();
rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> {
<span class="hljs-keyword">switch</span> (line.<span class="hljs-title function_">trim</span>()) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'hello'</span>:
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'world!'</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-attr">default</span>:
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Say what? I might have heard '<span class="hljs-subst">${line.trim()}</span>'`</span>);
<span class="hljs-keyword">break</span>;
}
rl.<span class="hljs-title function_">prompt</span>();
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Have a great day!'</span>);
process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">0</span>);
});</code><button class="copy-button">copy</button></pre>
</section><section><h3>Example: Read file stream line-by-Line<span><a class="mark" href="#all_readline_example-read-file-stream-line-by-line" id="all_readline_example-read-file-stream-line-by-line">#</a></span><a aria-hidden="true" class="legacy" id="readline_example_read_file_stream_line_by_line"></a></h3>
<p>A common use case for <code>readline</code> is to consume an input file one line at a
time. The easiest way to do so is leveraging the <a href="#all_fs_class-fsreadstream"><code>fs.ReadStream</code></a> API as
well as a <code>for await...of</code> loop:</p>
<pre class="with-53-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> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { createInterface } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:readline'</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">processLineByLine</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> fileStream = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'input.txt'</span>);
<span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
<span class="hljs-attr">input</span>: fileStream,
<span class="hljs-attr">crlfDelay</span>: <span class="hljs-title class_">Infinity</span>,
});
<span class="hljs-comment">// Note: we use the crlfDelay option to recognize all instances of CR LF</span>
<span class="hljs-comment">// ('\r\n') in input.txt as a single line break.</span>
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> line <span class="hljs-keyword">of</span> rl) {
<span class="hljs-comment">// Each line in input.txt will be successively available here as `line`.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Line from file: <span class="hljs-subst">${line}</span>`</span>);
}
}
<span class="hljs-title function_">processLineByLine</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createReadStream } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { createInterface } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">processLineByLine</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> fileStream = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'input.txt'</span>);
<span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
<span class="hljs-attr">input</span>: fileStream,
<span class="hljs-attr">crlfDelay</span>: <span class="hljs-title class_">Infinity</span>,
});
<span class="hljs-comment">// Note: we use the crlfDelay option to recognize all instances of CR LF</span>
<span class="hljs-comment">// ('\r\n') in input.txt as a single line break.</span>
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> line <span class="hljs-keyword">of</span> rl) {
<span class="hljs-comment">// Each line in input.txt will be successively available here as `line`.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Line from file: <span class="hljs-subst">${line}</span>`</span>);
}
}
<span class="hljs-title function_">processLineByLine</span>();</code><button class="copy-button">copy</button></pre>
<p>Alternatively, one could use the <a href="#all_readline_event-line"><code>'line'</code></a> event:</p>
<pre class="with-53-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> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { createInterface } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:readline'</span>;
<span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
<span class="hljs-attr">input</span>: <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'sample.txt'</span>),
<span class="hljs-attr">crlfDelay</span>: <span class="hljs-title class_">Infinity</span>,
});
rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Line from file: <span class="hljs-subst">${line}</span>`</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createReadStream } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { createInterface } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);
<span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
<span class="hljs-attr">input</span>: <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'sample.txt'</span>),
<span class="hljs-attr">crlfDelay</span>: <span class="hljs-title class_">Infinity</span>,
});
rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Line from file: <span class="hljs-subst">${line}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Currently, <code>for await...of</code> loop can be a bit slower. If <code>async</code> / <code>await</code>
flow and speed are both essential, a mixed approach can be applied:</p>
<pre class="with-48-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> { once } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</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">import</span> { createInterface } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:readline'</span>;
(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">processLineByLine</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
<span class="hljs-attr">input</span>: <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'big-file.txt'</span>),
<span class="hljs-attr">crlfDelay</span>: <span class="hljs-title class_">Infinity</span>,
});
rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> {
<span class="hljs-comment">// Process the line.</span>
});
<span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(rl, <span class="hljs-string">'close'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'File processed.'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}
})();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> { createReadStream } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { createInterface } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);
(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">processLineByLine</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
<span class="hljs-attr">input</span>: <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'big-file.txt'</span>),
<span class="hljs-attr">crlfDelay</span>: <span class="hljs-title class_">Infinity</span>,
});
rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> {
<span class="hljs-comment">// Process the line.</span>
});
<span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(rl, <span class="hljs-string">'close'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'File processed.'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}
})();</code><button class="copy-button">copy</button></pre>
</section><section><h3>TTY keybindings<span><a class="mark" href="#all_readline_tty-keybindings" id="all_readline_tty-keybindings">#</a></span><a aria-hidden="true" class="legacy" id="readline_tty_keybindings"></a></h3>
<table>
<tbody><tr>
<th>Keybindings</th>
<th>Description</th>
<th>Notes</th>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Backspace</kbd></td>
<td>Delete line left</td>
<td>Doesn't work on Linux, Mac and Windows</td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Delete</kbd></td>
<td>Delete line right</td>
<td>Doesn't work on Mac</td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>C</kbd></td>
<td>Emit <code>SIGINT</code> or close the readline instance</td>
<td></td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>H</kbd></td>
<td>Delete left</td>
<td></td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>D</kbd></td>
<td>Delete right or close the readline instance in case the current line is empty / EOF</td>
<td>Doesn't work on Windows</td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>U</kbd></td>
<td>Delete from the current position to the line start</td>
<td></td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>K</kbd></td>
<td>Delete from the current position to the end of line</td>
<td></td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>Y</kbd></td>
<td>Yank (Recall) the previously deleted text</td>
<td>Only works with text deleted by <kbd>Ctrl</kbd>+<kbd>U</kbd> or <kbd>Ctrl</kbd>+<kbd>K</kbd></td>
</tr>
<tr>
<td><kbd>Meta</kbd>+<kbd>Y</kbd></td>
<td>Cycle among previously deleted texts</td>
<td>Only available when the last keystroke is <kbd>Ctrl</kbd>+<kbd>Y</kbd> or <kbd>Meta</kbd>+<kbd>Y</kbd></td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>A</kbd></td>
<td>Go to start of line</td>
<td></td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>E</kbd></td>
<td>Go to end of line</td>
<td></td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>B</kbd></td>
<td>Back one character</td>
<td></td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>F</kbd></td>
<td>Forward one character</td>
<td></td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>L</kbd></td>
<td>Clear screen</td>
<td></td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>N</kbd></td>
<td>Next history item</td>
<td></td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>P</kbd></td>
<td>Previous history item</td>
<td></td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>-</kbd></td>
<td>Undo previous change</td>
<td>Any keystroke that emits key code <code>0x1F</code> will do this action.
In many terminals, for example <code>xterm</code>,
this is bound to <kbd>Ctrl</kbd>+<kbd>-</kbd>.</td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>6</kbd></td>
<td>Redo previous change</td>
<td>Many terminals don't have a default redo keystroke.
We choose key code <code>0x1E</code> to perform redo.
In <code>xterm</code>, it is bound to <kbd>Ctrl</kbd>+<kbd>6</kbd>
by default.</td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>Z</kbd></td>
<td>Moves running process into background. Type
<code>fg</code> and press <kbd>Enter</kbd>
to return.</td>
<td>Doesn't work on Windows</td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>W</kbd> or <kbd>Ctrl</kbd>
+<kbd>Backspace</kbd></td>
<td>Delete backward to a word boundary</td>
<td><kbd>Ctrl</kbd>+<kbd>Backspace</kbd> Doesn't
work on Linux, Mac and Windows</td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>Delete</kbd></td>
<td>Delete forward to a word boundary</td>
<td>Doesn't work on Mac</td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>Left arrow</kbd> or
<kbd>Meta</kbd>+<kbd>B</kbd></td>
<td>Word left</td>
<td><kbd>Ctrl</kbd>+<kbd>Left arrow</kbd> Doesn't work
on Mac</td>
</tr>
<tr>
<td><kbd>Ctrl</kbd>+<kbd>Right arrow</kbd> or
<kbd>Meta</kbd>+<kbd>F</kbd></td>
<td>Word right</td>
<td><kbd>Ctrl</kbd>+<kbd>Right arrow</kbd> Doesn't work
on Mac</td>
</tr>
<tr>
<td><kbd>Meta</kbd>+<kbd>D</kbd> or <kbd>Meta</kbd>
+<kbd>Delete</kbd></td>
<td>Delete word right</td>
<td><kbd>Meta</kbd>+<kbd>Delete</kbd> Doesn't work
on windows</td>
</tr>
<tr>
<td><kbd>Meta</kbd>+<kbd>Backspace</kbd></td>
<td>Delete word left</td>
<td>Doesn't work on Mac</td>
</tr>
</tbody></table></section>
</section>
<section><h2>REPL<span><a class="mark" href="#all_repl_repl" id="all_repl_repl">#</a></span><a aria-hidden="true" class="legacy" id="repl_repl"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/repl.js">lib/repl.js</a></p>
<p>The <code>node:repl</code> module provides a Read-Eval-Print-Loop (REPL) implementation
that is available both as a standalone program or includible in other
applications. It can be accessed using:</p>
<pre class="with-34-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> repl <span class="hljs-keyword">from</span> <span class="hljs-string">'node:repl'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>Design and features<span><a class="mark" href="#all_repl_design-and-features" id="all_repl_design-and-features">#</a></span><a aria-hidden="true" class="legacy" id="repl_design_and_features"></a></h3>
<p>The <code>node:repl</code> module exports the <a href="#all_repl_class-replserver"><code>repl.REPLServer</code></a> class. While running,
instances of <a href="#all_repl_class-replserver"><code>repl.REPLServer</code></a> will accept individual lines of user input,
evaluate those according to a user-defined evaluation function, then output the
result. Input and output may be from <code>stdin</code> and <code>stdout</code>, respectively, or may
be connected to any Node.js <a href="stream.html">stream</a>.</p>
<p>Instances of <a href="#all_repl_class-replserver"><code>repl.REPLServer</code></a> support automatic completion of inputs,
completion preview, simplistic Emacs-style line editing, multi-line inputs,
<a href="https://en.wikipedia.org/wiki/Z_shell">ZSH</a>-like reverse-i-search, <a href="https://en.wikipedia.org/wiki/Z_shell">ZSH</a>-like substring-based history search,
ANSI-styled output, saving and restoring current REPL session state, error
recovery, and customizable evaluation functions. Terminals that do not support
ANSI styles and Emacs-style line editing automatically fall back to a limited
feature set.</p>
<h4>Commands and special keys<span><a class="mark" href="#all_repl_commands-and-special-keys" id="all_repl_commands-and-special-keys">#</a></span><a aria-hidden="true" class="legacy" id="repl_commands_and_special_keys"></a></h4>
<p>The following special commands are supported by all REPL instances:</p>
<ul>
<li><code>.break</code>: When in the process of inputting a multi-line expression, enter
the <code>.break</code> command (or press <kbd>Ctrl</kbd>+<kbd>C</kbd>) to abort
further input or processing of that expression.</li>
<li><code>.clear</code>: Resets the REPL <code>context</code> to an empty object and clears any
multi-line expression being input.</li>
<li><code>.exit</code>: Close the I/O stream, causing the REPL to exit.</li>
<li><code>.help</code>: Show this list of special commands.</li>
<li><code>.save</code>: Save the current REPL session to a file:
<code>> .save ./file/to/save.js</code></li>
<li><code>.load</code>: Load a file into the current REPL session.
<code>> .load ./file/to/load.js</code></li>
<li><code>.editor</code>: Enter editor mode (<kbd>Ctrl</kbd>+<kbd>D</kbd> to
finish, <kbd>Ctrl</kbd>+<kbd>C</kbd> to cancel).</li>
</ul>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">.editor</span>
// Entering editor mode (^D to finish, ^C to cancel)
function welcome(name) {
return `Hello ${name}!`;
}
welcome('Node.js User');
// ^D
'Hello Node.js User!'
<span class="hljs-meta prompt_">></span></code> <button class="copy-button">copy</button></pre>
<p>The following key combinations in the REPL have these special effects:</p>
<ul>
<li><kbd>Ctrl</kbd>+<kbd>C</kbd>: When pressed once, has the same effect as the
<code>.break</code> command.
When pressed twice on a blank line, has the same effect as the <code>.exit</code>
command.</li>
<li><kbd>Ctrl</kbd>+<kbd>D</kbd>: Has the same effect as the <code>.exit</code> command.</li>
<li><kbd>Tab</kbd>: When pressed on a blank line, displays global and local
(scope) variables. When pressed while entering other input, displays relevant
autocompletion options.</li>
</ul>
<p>For key bindings related to the reverse-i-search, see <a href="#all_repl_reverse-i-search"><code>reverse-i-search</code></a>.
For all other key bindings, see <a href="#all_readline_tty-keybindings">TTY keybindings</a>.</p>
<h4>Default evaluation<span><a class="mark" href="#all_repl_default-evaluation" id="all_repl_default-evaluation">#</a></span><a aria-hidden="true" class="legacy" id="repl_default_evaluation"></a></h4>
<p>By default, all instances of <a href="#all_repl_class-replserver"><code>repl.REPLServer</code></a> use an evaluation function
that evaluates JavaScript expressions and provides access to Node.js built-in
modules. This default behavior can be overridden by passing in an alternative
evaluation function when the <a href="#all_repl_class-replserver"><code>repl.REPLServer</code></a> instance is created.</p>
<h5>JavaScript expressions<span><a class="mark" href="#all_repl_javascript-expressions" id="all_repl_javascript-expressions">#</a></span><a aria-hidden="true" class="legacy" id="repl_javascript_expressions"></a></h5>
<p>The default evaluator supports direct evaluation of JavaScript expressions:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">1 + 1</span>
2
<span class="hljs-meta prompt_">> </span><span class="language-bash">const m = 2</span>
undefined
<span class="hljs-meta prompt_">> </span><span class="language-bash">m + 1</span>
3</code> <button class="copy-button">copy</button></pre>
<p>Unless otherwise scoped within blocks or functions, variables declared
either implicitly or using the <code>const</code>, <code>let</code>, or <code>var</code> keywords
are declared at the global scope.</p>
<h5>Global and local scope<span><a class="mark" href="#all_repl_global-and-local-scope" id="all_repl_global-and-local-scope">#</a></span><a aria-hidden="true" class="legacy" id="repl_global_and_local_scope"></a></h5>
<p>The default evaluator provides access to any variables that exist in the global
scope. It is possible to expose a variable to the REPL explicitly by assigning
it to the <code>context</code> object associated with each <code>REPLServer</code>:</p>
<pre class="with-34-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> repl <span class="hljs-keyword">from</span> <span class="hljs-string">'node:repl'</span>;
<span class="hljs-keyword">const</span> msg = <span class="hljs-string">'message'</span>;
repl.<span class="hljs-title function_">start</span>(<span class="hljs-string">'> '</span>).<span class="hljs-property">context</span>.<span class="hljs-property">m</span> = msg;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-keyword">const</span> msg = <span class="hljs-string">'message'</span>;
repl.<span class="hljs-title function_">start</span>(<span class="hljs-string">'> '</span>).<span class="hljs-property">context</span>.<span class="hljs-property">m</span> = msg;</code><button class="copy-button">copy</button></pre>
<p>Properties in the <code>context</code> object appear as local within the REPL:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node repl_test.js</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">m</span>
'message'</code> <button class="copy-button">copy</button></pre>
<p>Context properties are not read-only by default. To specify read-only globals,
context properties must be defined using <code>Object.defineProperty()</code>:</p>
<pre class="with-34-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> repl <span class="hljs-keyword">from</span> <span class="hljs-string">'node:repl'</span>;
<span class="hljs-keyword">const</span> msg = <span class="hljs-string">'message'</span>;
<span class="hljs-keyword">const</span> r = repl.<span class="hljs-title function_">start</span>(<span class="hljs-string">'> '</span>);
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(r.<span class="hljs-property">context</span>, <span class="hljs-string">'m'</span>, {
<span class="hljs-attr">configurable</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">value</span>: msg,
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-keyword">const</span> msg = <span class="hljs-string">'message'</span>;
<span class="hljs-keyword">const</span> r = repl.<span class="hljs-title function_">start</span>(<span class="hljs-string">'> '</span>);
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(r.<span class="hljs-property">context</span>, <span class="hljs-string">'m'</span>, {
<span class="hljs-attr">configurable</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">value</span>: msg,
});</code><button class="copy-button">copy</button></pre>
<h5>Accessing core Node.js modules<span><a class="mark" href="#all_repl_accessing-core-nodejs-modules" id="all_repl_accessing-core-nodejs-modules">#</a></span><a aria-hidden="true" class="legacy" id="repl_accessing_core_node_js_modules"></a></h5>
<p>The default evaluator will automatically load Node.js core modules into the
REPL environment when used. For instance, unless otherwise declared as a
global or scoped variable, the input <code>fs</code> will be evaluated on-demand as
<code>global.fs = require('node:fs')</code>.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">fs.createReadStream(<span class="hljs-string">'./some/file'</span>);</span></code> <button class="copy-button">copy</button></pre>
<h5>Global uncaught exceptions<span><a class="mark" href="#all_repl_global-uncaught-exceptions" id="all_repl_global-uncaught-exceptions">#</a></span><a aria-hidden="true" class="legacy" id="repl_global_uncaught_exceptions"></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.3.0</td>
<td><p>The <code>'uncaughtException'</code> event is from now on triggered if the repl is used as standalone program.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The REPL uses the <a href="domain.html"><code>domain</code></a> module to catch all uncaught exceptions for that
REPL session.</p>
<p>This use of the <a href="domain.html"><code>domain</code></a> module in the REPL has these side effects:</p>
<ul>
<li>
<p>Uncaught exceptions only emit the <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a> event in the
standalone REPL. Adding a listener for this event in a REPL within
another Node.js program results in <a href="#all_errors_err_invalid_repl_input"><code>ERR_INVALID_REPL_INPUT</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> r = repl.<span class="hljs-title function_">start</span>();
r.<span class="hljs-title function_">write</span>(<span class="hljs-string">'process.on("uncaughtException", () => console.log("Foobar"));\n'</span>);
<span class="hljs-comment">// Output stream includes:</span>
<span class="hljs-comment">// TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`</span>
<span class="hljs-comment">// cannot be used in the REPL</span>
r.<span class="hljs-title function_">close</span>();</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Trying to use <a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> throws
an <a href="#all_errors_err_domain_cannot_set_uncaught_exception_capture"><code>ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE</code></a> error.</p>
</li>
</ul>
<h5>Assignment of the <code>_</code> (underscore) variable<span><a class="mark" href="#all_repl_assignment-of-the-_-underscore-variable" id="all_repl_assignment-of-the-_-underscore-variable">#</a></span><a aria-hidden="true" class="legacy" id="repl_assignment_of_the_underscore_variable"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.8.0</td>
<td><p>Added <code>_error</code> support.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The default evaluator will, by default, assign the result of the most recently
evaluated expression to the special variable <code>_</code> (underscore).
Explicitly setting <code>_</code> to a value will disable this behavior.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">[ <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span> ]</span>
[ 'a', 'b', 'c' ]
<span class="hljs-meta prompt_">> </span><span class="language-bash">_.length</span>
3
<span class="hljs-meta prompt_">> </span><span class="language-bash">_ += 1</span>
Expression assignment to _ now disabled.
4
<span class="hljs-meta prompt_">> </span><span class="language-bash">1 + 1</span>
2
<span class="hljs-meta prompt_">> </span><span class="language-bash">_</span>
4</code> <button class="copy-button">copy</button></pre>
<p>Similarly, <code>_error</code> will refer to the last seen error, if there was any.
Explicitly setting <code>_error</code> to a value will disable this behavior.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">throw new Error(<span class="hljs-string">'foo'</span>);</span>
Uncaught Error: foo
<span class="hljs-meta prompt_">> </span><span class="language-bash">_error.message</span>
'foo'</code> <button class="copy-button">copy</button></pre>
<h5><code>await</code> keyword<span><a class="mark" href="#all_repl_await-keyword" id="all_repl_await-keyword">#</a></span><a aria-hidden="true" class="legacy" id="repl_await_keyword"></a></h5>
<p>Support for the <code>await</code> keyword is enabled at the top level.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">await Promise.resolve(123)</span>
123
<span class="hljs-meta prompt_">> </span><span class="language-bash">await Promise.reject(new Error(<span class="hljs-string">'REPL await'</span>))</span>
Uncaught Error: REPL await
at REPL2:1:54
<span class="hljs-meta prompt_">> </span><span class="language-bash">const <span class="hljs-built_in">timeout</span> = util.promisify(setTimeout);</span>
undefined
<span class="hljs-meta prompt_">> </span><span class="language-bash">const old = Date.now(); await <span class="hljs-built_in">timeout</span>(1000); console.log(Date.now() - old);</span>
1002
undefined</code> <button class="copy-button">copy</button></pre>
<p>One known limitation of using the <code>await</code> keyword in the REPL is that
it will invalidate the lexical scoping of the <code>const</code> and <code>let</code>
keywords.</p>
<p>For example:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">const m = await Promise.resolve(123)</span>
undefined
<span class="hljs-meta prompt_">> </span><span class="language-bash">m</span>
123
<span class="hljs-meta prompt_">> </span><span class="language-bash">const m = await Promise.resolve(234)</span>
undefined
<span class="hljs-meta prompt_">> </span><span class="language-bash">m</span>
234</code> <button class="copy-button">copy</button></pre>
<p><a href="#all_cli_--no-experimental-repl-await"><code>--no-experimental-repl-await</code></a> shall disable top-level await in REPL.</p>
<h4>Reverse-i-search<span><a class="mark" href="#all_repl_reverse-i-search" id="all_repl_reverse-i-search">#</a></span><a aria-hidden="true" class="legacy" id="repl_reverse_i_search"></a></h4>
<div class="api_metadata">
<span>Added in: v13.6.0, v12.17.0</span>
</div>
<p>The REPL supports bi-directional reverse-i-search similar to <a href="https://en.wikipedia.org/wiki/Z_shell">ZSH</a>. It is
triggered with <kbd>Ctrl</kbd>+<kbd>R</kbd> to search backward
and <kbd>Ctrl</kbd>+<kbd>S</kbd> to search forwards.</p>
<p>Duplicated history entries will be skipped.</p>
<p>Entries are accepted as soon as any key is pressed that doesn't correspond
with the reverse search. Cancelling is possible by pressing <kbd>Esc</kbd>
or <kbd>Ctrl</kbd>+<kbd>C</kbd>.</p>
<p>Changing the direction immediately searches for the next entry in the expected
direction from the current position on.</p>
<h4>Custom evaluation functions<span><a class="mark" href="#all_repl_custom-evaluation-functions" id="all_repl_custom-evaluation-functions">#</a></span><a aria-hidden="true" class="legacy" id="repl_custom_evaluation_functions"></a></h4>
<p>When a new <a href="#all_repl_class-replserver"><code>repl.REPLServer</code></a> is created, a custom evaluation function may be
provided. This can be used, for instance, to implement fully customized REPL
applications.</p>
<p>The following illustrates an example of a REPL that squares a given number:</p>
<pre class="with-34-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> repl <span class="hljs-keyword">from</span> <span class="hljs-string">'node:repl'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">byThePowerOfTwo</span>(<span class="hljs-params">number</span>) {
<span class="hljs-keyword">return</span> number * number;
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">myEval</span>(<span class="hljs-params">cmd, context, filename, callback</span>) {
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-title function_">byThePowerOfTwo</span>(cmd));
}
repl.<span class="hljs-title function_">start</span>({ <span class="hljs-attr">prompt</span>: <span class="hljs-string">'Enter a number: '</span>, <span class="hljs-attr">eval</span>: myEval });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">byThePowerOfTwo</span>(<span class="hljs-params">number</span>) {
<span class="hljs-keyword">return</span> number * number;
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">myEval</span>(<span class="hljs-params">cmd, context, filename, callback</span>) {
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-title function_">byThePowerOfTwo</span>(cmd));
}
repl.<span class="hljs-title function_">start</span>({ <span class="hljs-attr">prompt</span>: <span class="hljs-string">'Enter a number: '</span>, <span class="hljs-attr">eval</span>: myEval });</code><button class="copy-button">copy</button></pre>
<h5>Recoverable errors<span><a class="mark" href="#all_repl_recoverable-errors" id="all_repl_recoverable-errors">#</a></span><a aria-hidden="true" class="legacy" id="repl_recoverable_errors"></a></h5>
<p>At the REPL prompt, pressing <kbd>Enter</kbd> sends the current line of input to
the <code>eval</code> function. In order to support multi-line input, the <code>eval</code> function
can return an instance of <code>repl.Recoverable</code> to the provided callback function:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">myEval</span>(<span class="hljs-params">cmd, context, filename, callback</span>) {
<span class="hljs-keyword">let</span> result;
<span class="hljs-keyword">try</span> {
result = vm.<span class="hljs-title function_">runInThisContext</span>(cmd);
} <span class="hljs-keyword">catch</span> (e) {
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">isRecoverableError</span>(e)) {
<span class="hljs-keyword">return</span> <span class="hljs-title function_">callback</span>(<span class="hljs-keyword">new</span> repl.<span class="hljs-title class_">Recoverable</span>(e));
}
}
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, result);
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">isRecoverableError</span>(<span class="hljs-params">error</span>) {
<span class="hljs-keyword">if</span> (error.<span class="hljs-property">name</span> === <span class="hljs-string">'SyntaxError'</span>) {
<span class="hljs-keyword">return</span> <span class="hljs-regexp">/^(Unexpected end of input|Unexpected token)/</span>.<span class="hljs-title function_">test</span>(error.<span class="hljs-property">message</span>);
}
<span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
}</code> <button class="copy-button">copy</button></pre>
<h4>Customizing REPL output<span><a class="mark" href="#all_repl_customizing-repl-output" id="all_repl_customizing-repl-output">#</a></span><a aria-hidden="true" class="legacy" id="repl_customizing_repl_output"></a></h4>
<p>By default, <a href="#all_repl_class-replserver"><code>repl.REPLServer</code></a> instances format output using the
<a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> method before writing the output to the provided <code>Writable</code>
stream (<code>process.stdout</code> by default). The <code>showProxy</code> inspection option is set
to true by default and the <code>colors</code> option is set to true depending on the
REPL's <code>useColors</code> option.</p>
<p>The <code>useColors</code> boolean option can be specified at construction to instruct the
default writer to use ANSI style codes to colorize the output from the
<code>util.inspect()</code> method.</p>
<p>If the REPL is run as standalone program, it is also possible to change the
REPL's <a href="#all_util_utilinspectobject-options">inspection defaults</a> from inside the REPL by using the
<code>inspect.replDefaults</code> property which mirrors the <code>defaultOptions</code> from
<a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a>.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">util.inspect.replDefaults.compact = <span class="hljs-literal">false</span>;</span>
false
<span class="hljs-meta prompt_">> </span><span class="language-bash">[1]</span>
[
1
]
<span class="hljs-meta prompt_">></span></code> <button class="copy-button">copy</button></pre>
<p>To fully customize the output of a <a href="#all_repl_class-replserver"><code>repl.REPLServer</code></a> instance pass in a new
function for the <code>writer</code> option on construction. The following example, for
instance, simply converts any input text to upper case:</p>
<pre class="with-34-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> repl <span class="hljs-keyword">from</span> <span class="hljs-string">'node:repl'</span>;
<span class="hljs-keyword">const</span> r = repl.<span class="hljs-title function_">start</span>({ <span class="hljs-attr">prompt</span>: <span class="hljs-string">'> '</span>, <span class="hljs-attr">eval</span>: myEval, <span class="hljs-attr">writer</span>: myWriter });
<span class="hljs-keyword">function</span> <span class="hljs-title function_">myEval</span>(<span class="hljs-params">cmd, context, filename, callback</span>) {
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, cmd);
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">myWriter</span>(<span class="hljs-params">output</span>) {
<span class="hljs-keyword">return</span> output.<span class="hljs-title function_">toUpperCase</span>();
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-keyword">const</span> r = repl.<span class="hljs-title function_">start</span>({ <span class="hljs-attr">prompt</span>: <span class="hljs-string">'> '</span>, <span class="hljs-attr">eval</span>: myEval, <span class="hljs-attr">writer</span>: myWriter });
<span class="hljs-keyword">function</span> <span class="hljs-title function_">myEval</span>(<span class="hljs-params">cmd, context, filename, callback</span>) {
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, cmd);
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">myWriter</span>(<span class="hljs-params">output</span>) {
<span class="hljs-keyword">return</span> output.<span class="hljs-title function_">toUpperCase</span>();
}</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>REPLServer</code><span><a class="mark" href="#all_repl_class-replserver" id="all_repl_class-replserver">#</a></span><a aria-hidden="true" class="legacy" id="repl_class_replserver"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.91</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 href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#all_repl_replstartoptions"><code>repl.start()</code></a></li>
<li>Extends: <a href="#all_readline_class-readlineinterface" class="type"><readline.Interface></a></li>
</ul>
<p>Instances of <code>repl.REPLServer</code> are created using the <a href="#all_repl_replstartoptions"><code>repl.start()</code></a> method
or directly using the JavaScript <code>new</code> keyword.</p>
<pre class="with-34-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> repl <span class="hljs-keyword">from</span> <span class="hljs-string">'node:repl'</span>;
<span class="hljs-keyword">const</span> options = { <span class="hljs-attr">useColors</span>: <span class="hljs-literal">true</span> };
<span class="hljs-keyword">const</span> firstInstance = repl.<span class="hljs-title function_">start</span>(options);
<span class="hljs-keyword">const</span> secondInstance = <span class="hljs-keyword">new</span> repl.<span class="hljs-title class_">REPLServer</span>(options);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-keyword">const</span> options = { <span class="hljs-attr">useColors</span>: <span class="hljs-literal">true</span> };
<span class="hljs-keyword">const</span> firstInstance = repl.<span class="hljs-title function_">start</span>(options);
<span class="hljs-keyword">const</span> secondInstance = <span class="hljs-keyword">new</span> repl.<span class="hljs-title class_">REPLServer</span>(options);</code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'exit'</code><span><a class="mark" href="#all_repl_event-exit" id="all_repl_event-exit">#</a></span><a aria-hidden="true" class="legacy" id="repl_event_exit"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<p>The <code>'exit'</code> event is emitted when the REPL is exited either by receiving the
<code>.exit</code> command as input, the user pressing <kbd>Ctrl</kbd>+<kbd>C</kbd> twice
to signal <code>SIGINT</code>,
or by pressing <kbd>Ctrl</kbd>+<kbd>D</kbd> to signal <code>'end'</code> on the input
stream. The listener
callback is invoked without any arguments.</p>
<pre><code class="language-js">replServer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Received "exit" event from repl!'</span>);
process.<span class="hljs-title function_">exit</span>();
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'reset'</code><span><a class="mark" href="#all_repl_event-reset" id="all_repl_event-reset">#</a></span><a aria-hidden="true" class="legacy" id="repl_event_reset"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.0</span>
</div>
<p>The <code>'reset'</code> event is emitted when the REPL's context is reset. This occurs
whenever the <code>.clear</code> command is received as input <em>unless</em> the REPL is using
the default evaluator and the <code>repl.REPLServer</code> instance was created with the
<code>useGlobal</code> option set to <code>true</code>. The listener callback will be called with a
reference to the <code>context</code> object as the only argument.</p>
<p>This can be used primarily to re-initialize REPL context to some pre-defined
state:</p>
<pre class="with-34-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> repl <span class="hljs-keyword">from</span> <span class="hljs-string">'node:repl'</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">initializeContext</span>(<span class="hljs-params">context</span>) {
context.<span class="hljs-property">m</span> = <span class="hljs-string">'test'</span>;
}
<span class="hljs-keyword">const</span> r = repl.<span class="hljs-title function_">start</span>({ <span class="hljs-attr">prompt</span>: <span class="hljs-string">'> '</span> });
<span class="hljs-title function_">initializeContext</span>(r.<span class="hljs-property">context</span>);
r.<span class="hljs-title function_">on</span>(<span class="hljs-string">'reset'</span>, initializeContext);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">initializeContext</span>(<span class="hljs-params">context</span>) {
context.<span class="hljs-property">m</span> = <span class="hljs-string">'test'</span>;
}
<span class="hljs-keyword">const</span> r = repl.<span class="hljs-title function_">start</span>({ <span class="hljs-attr">prompt</span>: <span class="hljs-string">'> '</span> });
<span class="hljs-title function_">initializeContext</span>(r.<span class="hljs-property">context</span>);
r.<span class="hljs-title function_">on</span>(<span class="hljs-string">'reset'</span>, initializeContext);</code><button class="copy-button">copy</button></pre>
<p>When this code is executed, the global <code>'m'</code> variable can be modified but then
reset to its initial value using the <code>.clear</code> command:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">./node example.js</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">m</span>
'test'
<span class="hljs-meta prompt_">> </span><span class="language-bash">m = 1</span>
1
<span class="hljs-meta prompt_">> </span><span class="language-bash">m</span>
1
<span class="hljs-meta prompt_">> </span><span class="language-bash">.clear</span>
Clearing context...
<span class="hljs-meta prompt_">> </span><span class="language-bash">m</span>
'test'
<span class="hljs-meta prompt_">></span></code> <button class="copy-button">copy</button></pre>
<h4><code>replServer.defineCommand(keyword, cmd)</code><span><a class="mark" href="#all_repl_replserverdefinecommandkeyword-cmd" id="all_repl_replserverdefinecommandkeyword-cmd">#</a></span><a aria-hidden="true" class="legacy" id="repl_replserver_definecommand_keyword_cmd"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>keyword</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The command keyword (<em>without</em> a leading <code>.</code> character).</li>
<li><code>cmd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to invoke when the command is processed.</li>
</ul>
<p>The <code>replServer.defineCommand()</code> method is used to add new <code>.</code>-prefixed commands
to the REPL instance. Such commands are invoked by typing a <code>.</code> followed by the
<code>keyword</code>. The <code>cmd</code> is either a <code>Function</code> or an <code>Object</code> with the following
properties:</p>
<ul>
<li><code>help</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Help text to be displayed when <code>.help</code> is entered (Optional).</li>
<li><code>action</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to execute, optionally accepting a single
string argument.</li>
</ul>
<p>The following example shows two new commands added to the REPL instance:</p>
<pre class="with-34-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> repl <span class="hljs-keyword">from</span> <span class="hljs-string">'node:repl'</span>;
<span class="hljs-keyword">const</span> replServer = repl.<span class="hljs-title function_">start</span>({ <span class="hljs-attr">prompt</span>: <span class="hljs-string">'> '</span> });
replServer.<span class="hljs-title function_">defineCommand</span>(<span class="hljs-string">'sayhello'</span>, {
<span class="hljs-attr">help</span>: <span class="hljs-string">'Say hello'</span>,
<span class="hljs-title function_">action</span>(<span class="hljs-params">name</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">clearBufferedCommand</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">displayPrompt</span>();
},
});
replServer.<span class="hljs-title function_">defineCommand</span>(<span class="hljs-string">'saybye'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">saybye</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Goodbye!'</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">close</span>();
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-keyword">const</span> replServer = repl.<span class="hljs-title function_">start</span>({ <span class="hljs-attr">prompt</span>: <span class="hljs-string">'> '</span> });
replServer.<span class="hljs-title function_">defineCommand</span>(<span class="hljs-string">'sayhello'</span>, {
<span class="hljs-attr">help</span>: <span class="hljs-string">'Say hello'</span>,
<span class="hljs-title function_">action</span>(<span class="hljs-params">name</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">clearBufferedCommand</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">displayPrompt</span>();
},
});
replServer.<span class="hljs-title function_">defineCommand</span>(<span class="hljs-string">'saybye'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">saybye</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Goodbye!'</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">close</span>();
});</code><button class="copy-button">copy</button></pre>
<p>The new commands can then be used from within the REPL instance:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">.sayhello Node.js User</span>
Hello, Node.js User!
<span class="hljs-meta prompt_">> </span><span class="language-bash">.saybye</span>
Goodbye!</code> <button class="copy-button">copy</button></pre>
<h4><code>replServer.displayPrompt([preserveCursor])</code><span><a class="mark" href="#all_repl_replserverdisplaypromptpreservecursor" id="all_repl_replserverdisplaypromptpreservecursor">#</a></span><a aria-hidden="true" class="legacy" id="repl_replserver_displayprompt_preservecursor"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.91</span>
</div>
<ul>
<li><code>preserveCursor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>The <code>replServer.displayPrompt()</code> method readies the REPL instance for input
from the user, printing the configured <code>prompt</code> to a new line in the <code>output</code>
and resuming the <code>input</code> to accept new input.</p>
<p>When multi-line input is being entered, an ellipsis is printed rather than the
'prompt'.</p>
<p>When <code>preserveCursor</code> is <code>true</code>, the cursor placement will not be reset to <code>0</code>.</p>
<p>The <code>replServer.displayPrompt</code> method is primarily intended to be called from
within the action function for commands registered using the
<code>replServer.defineCommand()</code> method.</p>
<h4><code>replServer.clearBufferedCommand()</code><span><a class="mark" href="#all_repl_replserverclearbufferedcommand" id="all_repl_replserverclearbufferedcommand">#</a></span><a aria-hidden="true" class="legacy" id="repl_replserver_clearbufferedcommand"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span>
</div>
<p>The <code>replServer.clearBufferedCommand()</code> method clears any command that has been
buffered but not yet executed. This method is primarily intended to be
called from within the action function for commands registered using the
<code>replServer.defineCommand()</code> method.</p>
<h4><code>replServer.setupHistory(historyPath, callback)</code><span><a class="mark" href="#all_repl_replserversetuphistoryhistorypath-callback" id="all_repl_replserversetuphistoryhistorypath-callback">#</a></span><a aria-hidden="true" class="legacy" id="repl_replserver_setuphistory_historypath_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><code>historyPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> the path to the history file</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 history writes are ready or upon error
<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>repl</code> <a href="#all_repl_class-replserver" class="type"><repl.REPLServer></a></li>
</ul>
</li>
</ul>
<p>Initializes a history log file for the REPL instance. When executing the
Node.js binary and using the command-line REPL, a history file is initialized
by default. However, this is not the case when creating a REPL
programmatically. Use this method to initialize a history log file when working
with REPL instances programmatically.</p>
</section><section><h3><code>repl.builtinModules</code><span><a class="mark" href="#all_repl_replbuiltinmodules" id="all_repl_replbuiltinmodules">#</a></span><a aria-hidden="true" class="legacy" id="repl_repl_builtinmodules"></a></h3>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>A list of the names of all Node.js modules, e.g., <code>'http'</code>.</p>
</section><section><h3><code>repl.start([options])</code><span><a class="mark" href="#all_repl_replstartoptions" id="all_repl_replstartoptions">#</a></span><a aria-hidden="true" class="legacy" id="repl_repl_start_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.4.0, v12.17.0</td>
<td><p>The <code>preview</code> option is now available.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>The <code>terminal</code> option now follows the default description in all cases and <code>useColors</code> checks <code>hasColors()</code> if available.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>REPL_MAGIC_MODE</code> <code>replMode</code> was removed.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakEvalOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v5.8.0</td>
<td><p>The <code>options</code> parameter is optional now.</p></td></tr>
<tr><td>v0.1.91</td>
<td><p><span>Added in: v0.1.91</span></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>
<ul>
<li><code>prompt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The input prompt to display. <strong>Default:</strong> <code>'> '</code>
(with a trailing space).</li>
<li><code>input</code> <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a> The <code>Readable</code> stream from which REPL input will
be read. <strong>Default:</strong> <code>process.stdin</code>.</li>
<li><code>output</code> <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a> The <code>Writable</code> stream to which REPL output will
be written. <strong>Default:</strong> <code>process.stdout</code>.</li>
<li><code>terminal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, specifies that the <code>output</code> should be
treated as a TTY terminal.
<strong>Default:</strong> checking the value of the <code>isTTY</code> property on the <code>output</code>
stream upon instantiation.</li>
<li><code>eval</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to be used when evaluating each given line
of input. <strong>Default:</strong> an async wrapper for the JavaScript <code>eval()</code>
function. An <code>eval</code> function can error with <code>repl.Recoverable</code> to indicate
the input was incomplete and prompt for additional lines.</li>
<li><code>useColors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, specifies that the default <code>writer</code>
function should include ANSI color styling to REPL output. If a custom
<code>writer</code> function is provided then this has no effect. <strong>Default:</strong> checking
color support on the <code>output</code> stream if the REPL instance's <code>terminal</code> value
is <code>true</code>.</li>
<li><code>useGlobal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, specifies that the default evaluation
function will use the JavaScript <code>global</code> as the context as opposed to
creating a new separate context for the REPL instance. The node CLI REPL
sets this value to <code>true</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>ignoreUndefined</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, specifies that the default writer
will not output the return value of a command if it evaluates to
<code>undefined</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>writer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to invoke to format the output of each
command before writing to <code>output</code>. <strong>Default:</strong> <a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a>.</li>
<li><code>completer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> An optional function used for custom Tab auto
completion. See <a href="#all_readline_use-of-the-completer-function"><code>readline.InterfaceCompleter</code></a> for an example.</li>
<li><code>replMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> A flag that specifies whether the default evaluator
executes all JavaScript commands in strict mode or default (sloppy) mode.
Acceptable values are:
<ul>
<li><code>repl.REPL_MODE_SLOPPY</code> to evaluate expressions in sloppy mode.</li>
<li><code>repl.REPL_MODE_STRICT</code> to evaluate expressions in strict mode. This is
equivalent to prefacing every repl statement with <code>'use strict'</code>.</li>
</ul>
</li>
<li><code>breakEvalOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Stop evaluating the current piece of code when
<code>SIGINT</code> is received, such as when <kbd>Ctrl</kbd>+<kbd>C</kbd> is pressed.
This cannot be used
together with a custom <code>eval</code> function. <strong>Default:</strong> <code>false</code>.</li>
<li><code>preview</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Defines if the repl prints autocomplete and output
previews or not. <strong>Default:</strong> <code>true</code> with the default eval function and
<code>false</code> in case a custom eval function is used. If <code>terminal</code> is falsy, then
there are no previews and the value of <code>preview</code> has no effect.</li>
</ul>
</li>
<li>Returns: <a href="#all_repl_class-replserver" class="type"><repl.REPLServer></a></li>
</ul>
<p>The <code>repl.start()</code> method creates and starts a <a href="#all_repl_class-replserver"><code>repl.REPLServer</code></a> instance.</p>
<p>If <code>options</code> is a string, then it specifies the input prompt:</p>
<pre class="with-34-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> repl <span class="hljs-keyword">from</span> <span class="hljs-string">'node:repl'</span>;
<span class="hljs-comment">// a Unix style prompt</span>
repl.<span class="hljs-title function_">start</span>(<span class="hljs-string">'$ '</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-comment">// a Unix style prompt</span>
repl.<span class="hljs-title function_">start</span>(<span class="hljs-string">'$ '</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3>The Node.js REPL<span><a class="mark" href="#all_repl_the-nodejs-repl" id="all_repl_the-nodejs-repl">#</a></span><a aria-hidden="true" class="legacy" id="repl_the_node_js_repl"></a></h3>
<p>Node.js itself uses the <code>node:repl</code> module to provide its own interactive
interface for executing JavaScript. This can be used by executing the Node.js
binary without passing any arguments (or by passing the <code>-i</code> argument):</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">const a = [1, 2, 3];</span>
undefined
<span class="hljs-meta prompt_">> </span><span class="language-bash">a</span>
[ 1, 2, 3 ]
<span class="hljs-meta prompt_">> </span><span class="language-bash">a.forEach((v) => {</span>
... console.log(v);
... });
1
2
3</code> <button class="copy-button">copy</button></pre>
<h4>Environment variable options<span><a class="mark" href="#all_repl_environment-variable-options" id="all_repl_environment-variable-options">#</a></span><a aria-hidden="true" class="legacy" id="repl_environment_variable_options"></a></h4>
<p>Various behaviors of the Node.js REPL can be customized using the following
environment variables:</p>
<ul>
<li><code>NODE_REPL_HISTORY</code>: When a valid path is given, persistent REPL history
will be saved to the specified file rather than <code>.node_repl_history</code> in the
user's home directory. Setting this value to <code>''</code> (an empty string) will
disable persistent REPL history. Whitespace will be trimmed from the value.
On Windows platforms environment variables with empty values are invalid so
set this variable to one or more spaces to disable persistent REPL history.</li>
<li><code>NODE_REPL_HISTORY_SIZE</code>: Controls how many lines of history will be
persisted if history is available. Must be a positive number.
<strong>Default:</strong> <code>1000</code>.</li>
<li><code>NODE_REPL_MODE</code>: May be either <code>'sloppy'</code> or <code>'strict'</code>. <strong>Default:</strong>
<code>'sloppy'</code>, which will allow non-strict mode code to be run.</li>
</ul>
<h4>Persistent history<span><a class="mark" href="#all_repl_persistent-history" id="all_repl_persistent-history">#</a></span><a aria-hidden="true" class="legacy" id="repl_persistent_history"></a></h4>
<p>By default, the Node.js REPL will persist history between <code>node</code> REPL sessions
by saving inputs to a <code>.node_repl_history</code> file located in the user's home
directory. This can be disabled by setting the environment variable
<code>NODE_REPL_HISTORY=''</code>.</p>
<h4>Using the Node.js REPL with advanced line-editors<span><a class="mark" href="#all_repl_using-the-nodejs-repl-with-advanced-line-editors" id="all_repl_using-the-nodejs-repl-with-advanced-line-editors">#</a></span><a aria-hidden="true" class="legacy" id="repl_using_the_node_js_repl_with_advanced_line_editors"></a></h4>
<p>For advanced line-editors, start Node.js with the environment variable
<code>NODE_NO_READLINE=1</code>. This will start the main and debugger REPL in canonical
terminal settings, which will allow use with <code>rlwrap</code>.</p>
<p>For example, the following can be added to a <code>.bashrc</code> file:</p>
<pre><code class="language-bash"><span class="hljs-built_in">alias</span> node=<span class="hljs-string">"env NODE_NO_READLINE=1 rlwrap node"</span></code> <button class="copy-button">copy</button></pre>
<h4>Starting multiple REPL instances against a single running instance<span><a class="mark" href="#all_repl_starting-multiple-repl-instances-against-a-single-running-instance" id="all_repl_starting-multiple-repl-instances-against-a-single-running-instance">#</a></span><a aria-hidden="true" class="legacy" id="repl_starting_multiple_repl_instances_against_a_single_running_instance"></a></h4>
<p>It is possible to create and run multiple REPL instances against a single
running instance of Node.js that share a single <code>global</code> object but have
separate I/O interfaces.</p>
<p>The following example, for instance, provides separate REPLs on <code>stdin</code>, a Unix
socket, and a TCP socket:</p>
<pre class="with-34-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> net <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">import</span> repl <span class="hljs-keyword">from</span> <span class="hljs-string">'node:repl'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">let</span> connections = <span class="hljs-number">0</span>;
repl.<span class="hljs-title function_">start</span>({
<span class="hljs-attr">prompt</span>: <span class="hljs-string">'Node.js via stdin> '</span>,
<span class="hljs-attr">input</span>: process.<span class="hljs-property">stdin</span>,
<span class="hljs-attr">output</span>: process.<span class="hljs-property">stdout</span>,
});
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
connections += <span class="hljs-number">1</span>;
repl.<span class="hljs-title function_">start</span>({
<span class="hljs-attr">prompt</span>: <span class="hljs-string">'Node.js via Unix socket> '</span>,
<span class="hljs-attr">input</span>: socket,
<span class="hljs-attr">output</span>: socket,
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
socket.<span class="hljs-title function_">end</span>();
});
}).<span class="hljs-title function_">listen</span>(<span class="hljs-string">'/tmp/node-repl-sock'</span>);
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
connections += <span class="hljs-number">1</span>;
repl.<span class="hljs-title function_">start</span>({
<span class="hljs-attr">prompt</span>: <span class="hljs-string">'Node.js via TCP socket> '</span>,
<span class="hljs-attr">input</span>: socket,
<span class="hljs-attr">output</span>: socket,
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
socket.<span class="hljs-title function_">end</span>();
});
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">5001</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-keyword">let</span> connections = <span class="hljs-number">0</span>;
repl.<span class="hljs-title function_">start</span>({
<span class="hljs-attr">prompt</span>: <span class="hljs-string">'Node.js via stdin> '</span>,
<span class="hljs-attr">input</span>: process.<span class="hljs-property">stdin</span>,
<span class="hljs-attr">output</span>: process.<span class="hljs-property">stdout</span>,
});
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
connections += <span class="hljs-number">1</span>;
repl.<span class="hljs-title function_">start</span>({
<span class="hljs-attr">prompt</span>: <span class="hljs-string">'Node.js via Unix socket> '</span>,
<span class="hljs-attr">input</span>: socket,
<span class="hljs-attr">output</span>: socket,
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
socket.<span class="hljs-title function_">end</span>();
});
}).<span class="hljs-title function_">listen</span>(<span class="hljs-string">'/tmp/node-repl-sock'</span>);
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
connections += <span class="hljs-number">1</span>;
repl.<span class="hljs-title function_">start</span>({
<span class="hljs-attr">prompt</span>: <span class="hljs-string">'Node.js via TCP socket> '</span>,
<span class="hljs-attr">input</span>: socket,
<span class="hljs-attr">output</span>: socket,
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
socket.<span class="hljs-title function_">end</span>();
});
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">5001</span>);</code><button class="copy-button">copy</button></pre>
<p>Running this application from the command line will start a REPL on stdin.
Other REPL clients may connect through the Unix socket or TCP socket. <code>telnet</code>,
for instance, is useful for connecting to TCP sockets, while <code>socat</code> can be used
to connect to both Unix and TCP sockets.</p>
<p>By starting a REPL from a Unix socket-based server instead of stdin, it is
possible to connect to a long-running Node.js process without restarting it.</p>
<p>For an example of running a "full-featured" (<code>terminal</code>) REPL over
a <code>net.Server</code> and <code>net.Socket</code> instance, see:
<a href="https://gist.github.com/TooTallNate/2209310">https://gist.github.com/TooTallNate/2209310</a>.</p>
<p>For an example of running a REPL instance over <a href="https://curl.haxx.se/docs/manpage.html"><code>curl(1)</code></a>, see:
<a href="https://gist.github.com/TooTallNate/2053342">https://gist.github.com/TooTallNate/2053342</a>.</p>
<p>This example is intended purely for educational purposes to demonstrate how
Node.js REPLs can be started using different I/O streams.
It should <strong>not</strong> be used in production environments or any context where security
is a concern without additional protective measures.
If you need to implement REPLs in a real-world application, consider alternative
approaches that mitigate these risks, such as using secure input mechanisms and
avoiding open network interfaces.</p></section>
</section>
<section><h2>Diagnostic report<span><a class="mark" href="#all_report_diagnostic-report" id="all_report_diagnostic-report">#</a></span><a aria-hidden="true" class="legacy" id="report_diagnostic_report"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Added <code>--report-exclude-network</code> option for excluding networking operations that can slow down report generation in some cases.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Delivers a JSON-formatted diagnostic summary, written to a file.</p>
<p>The report is intended for development, test, and production use, to capture
and preserve information for problem determination. It includes JavaScript
and native stack traces, heap statistics, platform information, resource
usage etc. With the report option enabled, diagnostic reports can be triggered
on unhandled exceptions, fatal errors and user signals, in addition to
triggering programmatically through API calls.</p>
<p>A complete example report that was generated on an uncaught exception
is provided below for reference.</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"header"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"reportVersion"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"event"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"exception"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"trigger"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Exception"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"filename"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"report.20181221.005011.8974.0.001.json"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"dumpEventTime"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"2018-12-21T00:50:11Z"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"dumpEventTimeStamp"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1545371411331"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"processId"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">8974</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"cwd"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/home/nodeuser/project/node"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"commandLine"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-string">"/home/nodeuser/project/node/out/Release/node"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"--report-uncaught-exception"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"/home/nodeuser/project/node/test/report/test-exception.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"child"</span>
<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"nodejsVersion"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"v12.0.0-pre"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"glibcVersionRuntime"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"2.17"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"glibcVersionCompiler"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"2.17"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"wordSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"64 bit"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"arch"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"x64"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"platform"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"linux"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"componentVersions"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"node"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"12.0.0-pre"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"v8"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"7.1.302.28-node.5"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"uv"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1.24.1"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"zlib"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1.2.11"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"ares"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1.15.0"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"modules"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"68"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"nghttp2"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1.34.0"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"napi"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"3"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"llhttp"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1.0.1"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"openssl"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1.1.0j"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"release"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"node"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"osName"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Linux"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"osRelease"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"3.10.0-862.el7.x86_64"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"osVersion"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"#1 SMP Wed Mar 21 18:14:51 EDT 2018"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"osMachine"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"x86_64"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"cpus"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"model"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"speed"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2700</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"user"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">88902660</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"nice"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"sys"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">50902570</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"idle"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">241732220</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"irq"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"model"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"speed"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2700</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"user"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">88902660</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"nice"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"sys"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">50902570</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"idle"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">241732220</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"irq"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"networkInterfaces"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"en0"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"internal"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"mac"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"13:10:de:ad:be:ef"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"10.0.0.37"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"netmask"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"255.255.255.0"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"family"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"IPv4"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"host"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"test_machine"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"javascriptStack"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"message"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Error: *** test-exception.js: throwing uncaught Error"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"stack"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-string">"at myException (/home/nodeuser/project/node/test/report/test-exception.js:9:11)"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"at Object.<anonymous> (/home/nodeuser/project/node/test/report/test-exception.js:12:3)"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"at Module._compile (internal/modules/cjs/loader.js:718:30)"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"at Object.Module._extensions..js (internal/modules/cjs/loader.js:729:10)"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"at Module.load (internal/modules/cjs/loader.js:617:32)"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"at tryModuleLoad (internal/modules/cjs/loader.js:560:12)"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"at Function.Module._load (internal/modules/cjs/loader.js:552:3)"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"at Function.Module.runMain (internal/modules/cjs/loader.js:771:12)"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"at executeUserCode (internal/bootstrap/node.js:332:15)"</span>
<span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"nativeStack"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"pc"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b57f07a9ef"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"symbol"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"report::GetNodeReport(v8::Isolate*, node::Environment*, char const*, char const*, v8::Local<v8::String>, std::ostream&) [./node]"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"pc"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b57f07cf03"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"symbol"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"report::GetReport(v8::FunctionCallbackInfo<v8::Value> const&) [./node]"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"pc"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b57f1bccfd"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"symbol"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">" [./node]"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"pc"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b57f1be048"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"symbol"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [./node]"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"pc"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b57feeda0e"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"symbol"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">" [./node]"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"javascriptHeap"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"totalMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5660672</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"executableMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">524288</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"totalCommittedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5488640</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"availableMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4341379928</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"totalGlobalHandlesMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">8192</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"usedGlobalHandlesMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3136</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"usedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4816432</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"memoryLimit"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4345298944</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"mallocedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">254128</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"externalMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">315644</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"peakMallocedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">98752</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"nativeContextCount"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"detachedContextCount"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"doesZapGarbage"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"heapSpaces"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"read_only_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">524288</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">39208</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">515584</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">30504</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">485080</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"new_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2097152</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2019312</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1031168</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">985496</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">45672</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"old_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2273280</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1769008</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1974640</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1725488</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">249152</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"code_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">696320</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">184896</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">152128</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">152128</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"map_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">536576</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">344928</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">327520</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">327520</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"large_object_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1520590336</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1520590336</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"new_large_object_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"resourceUsage"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"rss"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"35766272"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"free_memory"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1598337024"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"total_memory"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"17179869184"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"available_memory"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1598337024"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"maxRss"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"36624662528"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"constrained_memory"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"36624662528"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"userCpuSeconds"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0.040072</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"kernelCpuSeconds"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0.016029</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"cpuConsumptionPercent"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5.6101</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"userCpuConsumptionPercent"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4.0072</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"kernelCpuConsumptionPercent"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1.6029</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"pageFaults"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"IORequired"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"IONotRequired"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4610</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"fsActivity"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"reads"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"writes"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"uvthreadResourceUsage"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"userCpuSeconds"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0.039843</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"kernelCpuSeconds"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0.015937</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"cpuConsumptionPercent"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5.578</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"userCpuConsumptionPercent"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3.9843</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"kernelCpuConsumptionPercent"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1.5937</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"fsActivity"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"reads"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"writes"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"libuv"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"async"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x0000000102910900"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"details"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">""</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"timer"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x00007fff5fbfeab0"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"repeat"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"firesInMsFromNow"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">94403548320796</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"expired"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"check"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x00007fff5fbfeb48"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"idle"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x00007fff5fbfebc0"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"prepare"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x00007fff5fbfec38"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"check"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x00007fff5fbfecb0"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"async"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000000010188f2e0"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"tty"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b581db0e18"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"width"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">204</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"height"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">55</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"fd"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">17</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"writeQueueSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"readable"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"writable"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"signal"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b581d80010"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"signum"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">28</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"signal"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"SIGWINCH"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"tty"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b581df59f8"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"width"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">204</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"height"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">55</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"fd"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">19</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"writeQueueSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"readable"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"writable"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"loop"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055fc7b2cb180"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"loopIdleTimeSeconds"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">22644.8</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"tcp"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055e70fcb85d8"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"localEndpoint"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"host"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"localhost"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"ip4"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"127.0.0.1"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"port"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">48986</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"remoteEndpoint"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"host"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"localhost"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"ip4"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"127.0.0.1"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"port"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">38573</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"sendBufferSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2626560</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"recvBufferSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">131072</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"fd"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">24</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"writeQueueSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"readable"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"writable"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"tcp"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055e70fcd68c8"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"localEndpoint"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"host"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"ip6-localhost"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"ip6"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"::1"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"port"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">52266</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"remoteEndpoint"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"host"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"ip6-localhost"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"ip6"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"::1"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"port"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">38573</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"sendBufferSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2626560</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"recvBufferSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">131072</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"fd"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">25</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"writeQueueSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"readable"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"writable"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"workers"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"environmentVariables"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"REMOTEHOST"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"REMOVED"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"MANPATH"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/usr/share/man:"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"XDG_SESSION_ID"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"66126"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"HOSTNAME"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"test_machine"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"HOST"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"test_machine"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"TERM"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"xterm-256color"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"SHELL"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/bin/csh"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"SSH_CLIENT"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"REMOVED"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"PERL5LIB"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root//usr/lib64/perl5/vendor_perl:/opt/rh/devtoolset-3/root/usr/lib/perl5:/opt/rh/devtoolset-3/root//usr/share/perl5/vendor_perl"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"OLDPWD"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/home/nodeuser/project/node/src"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"JAVACONFDIRS"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/etc/java:/etc/java"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"SSH_TTY"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/dev/pts/0"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"PCP_DIR"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"GROUP"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"normaluser"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"USER"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"nodeuser"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"LD_LIBRARY_PATH"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/usr/lib64:/opt/rh/devtoolset-3/root/usr/lib"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"HOSTTYPE"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"x86_64-linux"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"XDG_CONFIG_DIRS"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/etc/xdg:/etc/xdg"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"MAIL"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/var/spool/mail/nodeuser"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"PATH"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/home/nodeuser/project/node:/opt/rh/devtoolset-3/root/usr/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"PWD"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/home/nodeuser/project/node"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"LANG"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"en_US.UTF-8"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"PS1"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"\\u@\\h : \\[\\e[31m\\]\\w\\[\\e[m\\] > "</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"SHLVL"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"2"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"HOME"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/home/nodeuser"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"OSTYPE"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"linux"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"VENDOR"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unknown"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"PYTHONPATH"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/usr/lib64/python2.7/site-packages:/opt/rh/devtoolset-3/root/usr/lib/python2.7/site-packages"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"MACHTYPE"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"x86_64"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"LOGNAME"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"nodeuser"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"XDG_DATA_DIRS"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/usr/share:/usr/local/share:/usr/share"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"LESSOPEN"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"||/usr/bin/lesspipe.sh %s"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"INFOPATH"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/usr/share/info"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"XDG_RUNTIME_DIR"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/run/user/50141"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"_"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./node"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"userLimits"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"core_file_size_blocks"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">""</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"data_seg_size_kbytes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"file_size_blocks"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"max_locked_memory_bytes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">65536</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"max_memory_size_kbytes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"open_files"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4096</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"stack_size_bytes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"cpu_time_seconds"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"max_user_processes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4127290</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"virtual_memory_kbytes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"sharedObjects"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-string">"/lib64/libdl.so.2"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"/lib64/librt.so.1"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"/lib64/libstdc++.so.6"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"/lib64/libm.so.6"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"/lib64/libgcc_s.so.1"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"/lib64/libpthread.so.0"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"/lib64/libc.so.6"</span><span class="hljs-punctuation">,</span>
<span class="hljs-string">"/lib64/ld-linux-x86-64.so.2"</span>
<span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<section><h3>Usage<span><a class="mark" href="#all_report_usage" id="all_report_usage">#</a></span><a aria-hidden="true" class="legacy" id="report_usage"></a></h3>
<pre><code class="language-bash">node --report-uncaught-exception --report-on-signal \
--report-on-fatalerror app.js</code> <button class="copy-button">copy</button></pre>
<ul>
<li>
<p><code>--report-uncaught-exception</code> Enables report to be generated on
un-caught exceptions. Useful when inspecting JavaScript stack in conjunction
with native stack and other runtime environment data.</p>
</li>
<li>
<p><code>--report-on-signal</code> Enables report to be generated upon receiving
the specified (or predefined) signal to the running Node.js process. (See
below on how to modify the signal that triggers the report.) Default signal is
<code>SIGUSR2</code>. Useful when a report needs to be triggered from another program.
Application monitors may leverage this feature to collect report at regular
intervals and plot rich set of internal runtime data to their views.</p>
</li>
</ul>
<p>Signal based report generation is not supported in Windows.</p>
<p>Under normal circumstances, there is no need to modify the report triggering
signal. However, if <code>SIGUSR2</code> is already used for other purposes, then this
flag helps to change the signal for report generation and preserve the original
meaning of <code>SIGUSR2</code> for the said purposes.</p>
<ul>
<li>
<p><code>--report-on-fatalerror</code> Enables the report to be triggered on fatal errors
(internal errors within the Node.js runtime, such as out of memory)
that leads to termination of the application. Useful to inspect various
diagnostic data elements such as heap, stack, event loop state, resource
consumption etc. to reason about the fatal error.</p>
</li>
<li>
<p><code>--report-compact</code> Write reports in a compact format, single-line JSON, more
easily consumable by log processing systems than the default multi-line format
designed for human consumption.</p>
</li>
<li>
<p><code>--report-directory</code> Location at which the report will be
generated.</p>
</li>
<li>
<p><code>--report-filename</code> Name of the file to which the report will be
written.</p>
</li>
<li>
<p><code>--report-signal</code> Sets or resets the signal for report generation
(not supported on Windows). Default signal is <code>SIGUSR2</code>.</p>
</li>
<li>
<p><code>--report-exclude-network</code> Exclude <code>header.networkInterfaces</code> and disable the reverse DNS queries
in <code>libuv.*.(remote|local)Endpoint.host</code> from the diagnostic report.
By default this is not set and the network interfaces are included.</p>
</li>
</ul>
<p>A report can also be triggered via an API call from a JavaScript application:</p>
<pre><code class="language-js">process.<span class="hljs-property">report</span>.<span class="hljs-title function_">writeReport</span>();</code> <button class="copy-button">copy</button></pre>
<p>This function takes an optional additional argument <code>filename</code>, which is
the name of a file into which the report is written.</p>
<pre><code class="language-js">process.<span class="hljs-property">report</span>.<span class="hljs-title function_">writeReport</span>(<span class="hljs-string">'./foo.json'</span>);</code> <button class="copy-button">copy</button></pre>
<p>This function takes an optional additional argument <code>err</code> which is an <code>Error</code>
object that will be used as the context for the JavaScript stack printed in the
report. When using report to handle errors in a callback or an exception
handler, this allows the report to include the location of the original error as
well as where it was handled.</p>
<pre><code class="language-js"><span class="hljs-keyword">try</span> {
process.<span class="hljs-title function_">chdir</span>(<span class="hljs-string">'/non-existent-path'</span>);
} <span class="hljs-keyword">catch</span> (err) {
process.<span class="hljs-property">report</span>.<span class="hljs-title function_">writeReport</span>(err);
}
<span class="hljs-comment">// Any other code</span></code> <button class="copy-button">copy</button></pre>
<p>If both filename and error object are passed to <code>writeReport()</code> the
error object must be the second parameter.</p>
<pre><code class="language-js"><span class="hljs-keyword">try</span> {
process.<span class="hljs-title function_">chdir</span>(<span class="hljs-string">'/non-existent-path'</span>);
} <span class="hljs-keyword">catch</span> (err) {
process.<span class="hljs-property">report</span>.<span class="hljs-title function_">writeReport</span>(filename, err);
}
<span class="hljs-comment">// Any other code</span></code> <button class="copy-button">copy</button></pre>
<p>The content of the diagnostic report can be returned as a JavaScript Object
via an API call from a JavaScript application:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> report = process.<span class="hljs-property">report</span>.<span class="hljs-title function_">getReport</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">typeof</span> report === <span class="hljs-string">'object'</span>); <span class="hljs-comment">// true</span>
<span class="hljs-comment">// Similar to process.report.writeReport() output</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(report, <span class="hljs-literal">null</span>, <span class="hljs-number">2</span>));</code> <button class="copy-button">copy</button></pre>
<p>This function takes an optional additional argument <code>err</code>, which is an <code>Error</code>
object that will be used as the context for the JavaScript stack printed in the
report.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> report = process.<span class="hljs-property">report</span>.<span class="hljs-title function_">getReport</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'custom error'</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">typeof</span> report === <span class="hljs-string">'object'</span>); <span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></pre>
<p>The API versions are useful when inspecting the runtime state from within
the application, in expectation of self-adjusting the resource consumption,
load balancing, monitoring etc.</p>
<p>The content of the report consists of a header section containing the event
type, date, time, PID, and Node.js version, sections containing JavaScript and
native stack traces, a section containing V8 heap information, a section
containing <code>libuv</code> handle information, and an OS platform information section
showing CPU and memory usage and system limits. An example report can be
triggered using the Node.js REPL:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.report.writeReport();</span>
Writing Node.js report to file: report.20181126.091102.8480.0.001.json
Node.js report completed
<span class="hljs-meta prompt_">></span></code> <button class="copy-button">copy</button></pre>
<p>When a report is written, start and end messages are issued to stderr
and the filename of the report is returned to the caller. The default filename
includes the date, time, PID, and a sequence number. The sequence number helps
in associating the report dump with the runtime state if generated multiple
times for the same Node.js process.</p>
<p>Diagnostic report has an associated single-digit version number (<code>report.header.reportVersion</code>),
uniquely representing the report format. The version number is bumped
when new key is added or removed, or the data type of a value is changed.
Report version definitions are consistent across LTS releases.</p>
</section><section><h3>Configuration<span><a class="mark" href="#all_report_configuration" id="all_report_configuration">#</a></span><a aria-hidden="true" class="legacy" id="report_configuration"></a></h3>
<p>Additional runtime configuration of report generation is available via
the following properties of <code>process.report</code>:</p>
<p><code>reportOnFatalError</code> triggers diagnostic reporting on fatal errors when <code>true</code>.
Defaults to <code>false</code>.</p>
<p><code>reportOnSignal</code> triggers diagnostic reporting on signal when <code>true</code>. This is
not supported on Windows. Defaults to <code>false</code>.</p>
<p><code>reportOnUncaughtException</code> triggers diagnostic reporting on uncaught exception
when <code>true</code>. Defaults to <code>false</code>.</p>
<p><code>signal</code> specifies the POSIX signal identifier that will be used
to intercept external triggers for report generation. Defaults to
<code>'SIGUSR2'</code>.</p>
<p><code>filename</code> specifies the name of the output file in the file system.
Special meaning is attached to <code>stdout</code> and <code>stderr</code>. Usage of these
will result in report being written to the associated standard streams.
In cases where standard streams are used, the value in <code>directory</code> is ignored.
URLs are not supported. Defaults to a composite filename that contains
timestamp, PID, and sequence number.</p>
<p><code>directory</code> specifies the file system directory where the report will be
written. URLs are not supported. Defaults to the current working directory of
the Node.js process.</p>
<p><code>excludeNetwork</code> excludes <code>header.networkInterfaces</code> from the diagnostic report.</p>
<pre><code class="language-js"><span class="hljs-comment">// Trigger report only on uncaught exceptions.</span>
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnFatalError</span> = <span class="hljs-literal">false</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnSignal</span> = <span class="hljs-literal">false</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnUncaughtException</span> = <span class="hljs-literal">true</span>;
<span class="hljs-comment">// Trigger report for both internal errors as well as external signal.</span>
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnFatalError</span> = <span class="hljs-literal">true</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnSignal</span> = <span class="hljs-literal">true</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnUncaughtException</span> = <span class="hljs-literal">false</span>;
<span class="hljs-comment">// Change the default signal to 'SIGQUIT' and enable it.</span>
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnFatalError</span> = <span class="hljs-literal">false</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnUncaughtException</span> = <span class="hljs-literal">false</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnSignal</span> = <span class="hljs-literal">true</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">signal</span> = <span class="hljs-string">'SIGQUIT'</span>;
<span class="hljs-comment">// Disable network interfaces reporting</span>
process.<span class="hljs-property">report</span>.<span class="hljs-property">excludeNetwork</span> = <span class="hljs-literal">true</span>;</code> <button class="copy-button">copy</button></pre>
<p>Configuration on module initialization is also available via
environment variables:</p>
<pre><code class="language-bash">NODE_OPTIONS=<span class="hljs-string">"--report-uncaught-exception \
--report-on-fatalerror --report-on-signal \
--report-signal=SIGUSR2 --report-filename=./report.json \
--report-directory=/home/nodeuser"</span></code> <button class="copy-button">copy</button></pre>
<p>Specific API documentation can be found under
<a href="process.html"><code>process API documentation</code></a> section.</p>
</section><section><h3>Interaction with workers<span><a class="mark" href="#all_report_interaction-with-workers" id="all_report_interaction-with-workers">#</a></span><a aria-hidden="true" class="legacy" id="report_interaction_with_workers"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.9.0, v12.16.2</td>
<td><p>Workers are now included in the report.</p></td></tr>
</tbody></table>
</details>
</div>
<p><a href="worker_threads.html"><code>Worker</code></a> threads can create reports in the same way that the main thread
does.</p>
<p>Reports will include information on any Workers that are children of the current
thread as part of the <code>workers</code> section, with each Worker generating a report
in the standard report format.</p>
<p>The thread which is generating the report will wait for the reports from Worker
threads to finish. However, the latency for this will usually be low, as both
running JavaScript and the event loop are interrupted to generate the report.</p></section>
</section>
<section><h2>Single executable applications<span><a class="mark" href="#all_single-executable-applications_single-executable-applications" id="all_single-executable-applications_single-executable-applications">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_single_executable_applications"></a></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>Added support for "useSnapshot".</p></td></tr>
<tr><td>v20.6.0</td>
<td><p>Added support for "useCodeCache".</p></td></tr>
<tr><td>v19.7.0, v18.16.0</td>
<td><p><span>Added in: v19.7.0, v18.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/src/node_sea.cc">src/node_sea.cc</a></p>
<p>This feature allows the distribution of a Node.js application conveniently to a
system that does not have Node.js installed.</p>
<p>Node.js supports the creation of <a href="https://github.com/nodejs/single-executable">single executable applications</a> by allowing
the injection of a blob prepared by Node.js, which can contain a bundled script,
into the <code>node</code> binary. During start up, the program checks if anything has been
injected. If the blob is found, it executes the script in the blob. Otherwise
Node.js operates as it normally does.</p>
<p>The single executable application feature currently only supports running a
single embedded script using the <a href="#all_modules_modules-commonjs-modules">CommonJS</a> module system.</p>
<p>Users can create a single executable application from their bundled script
with the <code>node</code> binary itself and any tool which can inject resources into the
binary.</p>
<p>Here are the steps for creating a single executable application using one such
tool, <a href="https://github.com/nodejs/postject">postject</a>:</p>
<ol>
<li>
<p>Create a JavaScript file:</p>
<pre><code class="language-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">'console.log(`Hello, ${process.argv[2]}!`);'</span> > hello.js</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Create a configuration file building a blob that can be injected into the
single executable application (see
<a href="#all_single-executable-applications_generating-single-executable-preparation-blobs">Generating single executable preparation blobs</a> for details):</p>
<pre><code class="language-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">'{ "main": "hello.js", "output": "sea-prep.blob" }'</span> > sea-config.json</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Generate the blob to be injected:</p>
<pre><code class="language-bash">node --experimental-sea-config sea-config.json</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Create a copy of the <code>node</code> executable and name it according to your needs:</p>
<ul>
<li>On systems other than Windows:</li>
</ul>
<pre><code class="language-bash"><span class="hljs-built_in">cp</span> $(<span class="hljs-built_in">command</span> -v node) hello</code> <button class="copy-button">copy</button></pre>
<ul>
<li>On Windows:</li>
</ul>
<pre><code class="language-text">node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')"</code> <button class="copy-button">copy</button></pre>
<p>The <code>.exe</code> extension is necessary.</p>
</li>
<li>
<p>Remove the signature of the binary (macOS and Windows only):</p>
<ul>
<li>On macOS:</li>
</ul>
<pre><code class="language-bash">codesign --remove-signature hello</code> <button class="copy-button">copy</button></pre>
<ul>
<li>On Windows (optional):</li>
</ul>
<p><a href="https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool">signtool</a> can be used from the installed <a href="https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/">Windows SDK</a>. If this step is
skipped, ignore any signature-related warning from postject.</p>
<pre><code class="language-powershell">signtool remove /s hello.exe</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Inject the blob into the copied binary by running <code>postject</code> with
the following options:</p>
<ul>
<li><code>hello</code> / <code>hello.exe</code> - The name of the copy of the <code>node</code> executable
created in step 4.</li>
<li><code>NODE_SEA_BLOB</code> - The name of the resource / note / section in the binary
where the contents of the blob will be stored.</li>
<li><code>sea-prep.blob</code> - The name of the blob created in step 1.</li>
<li><code>--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2</code> - The
<a href="https://www.electronjs.org/docs/latest/tutorial/fuses">fuse</a> used by the Node.js project to detect if a file has been injected.</li>
<li><code>--macho-segment-name NODE_SEA</code> (only needed on macOS) - The name of the
segment in the binary where the contents of the blob will be
stored.</li>
</ul>
<p>To summarize, here is the required command for each platform:</p>
<ul>
<li>
<p>On Linux:</p>
<pre><code class="language-bash">npx postject hello NODE_SEA_BLOB sea-prep.blob \
--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>On Windows - PowerShell:</p>
<pre><code class="language-powershell">npx postject hello.exe NODE_SEA_BLOB sea<span class="hljs-literal">-prep</span>.blob `
<span class="hljs-literal">--sentinel-fuse</span> NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>On Windows - Command Prompt:</p>
<pre><code class="language-text">npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^
--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>On macOS:</p>
<pre><code class="language-bash">npx postject hello NODE_SEA_BLOB sea-prep.blob \
--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \
--macho-segment-name NODE_SEA</code> <button class="copy-button">copy</button></pre>
</li>
</ul>
</li>
<li>
<p>Sign the binary (macOS and Windows only):</p>
<ul>
<li>On macOS:</li>
</ul>
<pre><code class="language-bash">codesign --sign - hello</code> <button class="copy-button">copy</button></pre>
<ul>
<li>On Windows (optional):</li>
</ul>
<p>A certificate needs to be present for this to work. However, the unsigned
binary would still be runnable.</p>
<pre><code class="language-powershell">signtool sign /fd SHA256 hello.exe</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Run the binary:</p>
<ul>
<li>On systems other than Windows</li>
</ul>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">./hello world</span>
Hello, world!</code> <button class="copy-button">copy</button></pre>
<ul>
<li>On Windows</li>
</ul>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">.\hello.exe world</span>
Hello, world!</code> <button class="copy-button">copy</button></pre>
</li>
</ol>
<section><h3>Generating single executable preparation blobs<span><a class="mark" href="#all_single-executable-applications_generating-single-executable-preparation-blobs" id="all_single-executable-applications_generating-single-executable-preparation-blobs">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_generating_single_executable_preparation_blobs"></a></h3>
<p>Single executable preparation blobs that are injected into the application can
be generated using the <code>--experimental-sea-config</code> flag of the Node.js binary
that will be used to build the single executable. It takes a path to a
configuration file in JSON format. If the path passed to it isn't absolute,
Node.js will use the path relative to the current working directory.</p>
<p>The configuration currently reads the following top-level fields:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"main"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/bundled/script.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"output"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/write/the/generated/blob.blob"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"disableExperimentalSEAWarning"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span> <span class="hljs-comment">// Default: false</span>
<span class="hljs-attr">"useSnapshot"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span> <span class="hljs-comment">// Default: false</span>
<span class="hljs-attr">"useCodeCache"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span> <span class="hljs-comment">// Default: false</span>
<span class="hljs-attr">"assets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span> <span class="hljs-comment">// Optional</span>
<span class="hljs-attr">"a.dat"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/a.dat"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"b.txt"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/b.txt"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>If the paths are not absolute, Node.js will use the path relative to the
current working directory. The version of the Node.js binary used to produce
the blob must be the same as the one to which the blob will be injected.</p>
<p>Note: When generating cross-platform SEAs (e.g., generating a SEA
for <code>linux-x64</code> on <code>darwin-arm64</code>), <code>useCodeCache</code> and <code>useSnapshot</code>
must be set to false to avoid generating incompatible executables.
Since code cache and snapshots can only be loaded on the same platform
where they are compiled, the generated executable might crash on startup when
trying to load code cache or snapshots built on a different platform.</p>
<h4>Assets<span><a class="mark" href="#all_single-executable-applications_assets" id="all_single-executable-applications_assets">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_assets"></a></h4>
<p>Users can include assets by adding a key-path dictionary to the configuration
as the <code>assets</code> field. At build time, Node.js would read the assets from the
specified paths and bundle them into the preparation blob. In the generated
executable, users can retrieve the assets using the <a href="#all_single-executable-applications_seagetassetkey-encoding"><code>sea.getAsset()</code></a> and
<a href="#all_single-executable-applications_seagetassetasblobkey-options"><code>sea.getAssetAsBlob()</code></a> APIs.</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"main"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/bundled/script.js"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"output"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/write/the/generated/blob.blob"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"assets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"a.jpg"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/a.jpg"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"b.txt"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/b.txt"</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The single-executable application can access the assets as follows:</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { getAsset, getAssetAsBlob, getRawAsset } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:sea'</span>);
<span class="hljs-comment">// Returns a copy of the data in an ArrayBuffer.</span>
<span class="hljs-keyword">const</span> image = <span class="hljs-title function_">getAsset</span>(<span class="hljs-string">'a.jpg'</span>);
<span class="hljs-comment">// Returns a string decoded from the asset as UTF8.</span>
<span class="hljs-keyword">const</span> text = <span class="hljs-title function_">getAsset</span>(<span class="hljs-string">'b.txt'</span>, <span class="hljs-string">'utf8'</span>);
<span class="hljs-comment">// Returns a Blob containing the asset.</span>
<span class="hljs-keyword">const</span> blob = <span class="hljs-title function_">getAssetAsBlob</span>(<span class="hljs-string">'a.jpg'</span>);
<span class="hljs-comment">// Returns an ArrayBuffer containing the raw asset without copying.</span>
<span class="hljs-keyword">const</span> raw = <span class="hljs-title function_">getRawAsset</span>(<span class="hljs-string">'a.jpg'</span>);</code> <button class="copy-button">copy</button></pre>
<p>See documentation of the <a href="#all_single-executable-applications_seagetassetkey-encoding"><code>sea.getAsset()</code></a>, <a href="#all_single-executable-applications_seagetassetasblobkey-options"><code>sea.getAssetAsBlob()</code></a> and <a href="#all_single-executable-applications_seagetrawassetkey"><code>sea.getRawAsset()</code></a>
APIs for more information.</p>
<h4>Startup snapshot support<span><a class="mark" href="#all_single-executable-applications_startup-snapshot-support" id="all_single-executable-applications_startup-snapshot-support">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_startup_snapshot_support"></a></h4>
<p>The <code>useSnapshot</code> field can be used to enable startup snapshot support. In this
case the <code>main</code> script would not be when the final executable is launched.
Instead, it would be run when the single executable application preparation
blob is generated on the building machine. The generated preparation blob would
then include a snapshot capturing the states initialized by the <code>main</code> script.
The final executable with the preparation blob injected would deserialize
the snapshot at run time.</p>
<p>When <code>useSnapshot</code> is true, the main script must invoke the
<a href="#all_v8_v8startupsnapshotsetdeserializemainfunctioncallback-data"><code>v8.startupSnapshot.setDeserializeMainFunction()</code></a> API to configure code
that needs to be run when the final executable is launched by the users.</p>
<p>The typical pattern for an application to use snapshot in a single executable
application is:</p>
<ol>
<li>At build time, on the building machine, the main script is run to
initialize the heap to a state that's ready to take user input. The script
should also configure a main function with
<a href="#all_v8_v8startupsnapshotsetdeserializemainfunctioncallback-data"><code>v8.startupSnapshot.setDeserializeMainFunction()</code></a>. This function will be
compiled and serialized into the snapshot, but not invoked at build time.</li>
<li>At run time, the main function will be run on top of the deserialized heap
on the user machine to process user input and generate output.</li>
</ol>
<p>The general constraints of the startup snapshot scripts also apply to the main
script when it's used to build snapshot for the single executable application,
and the main script can use the <a href="#all_v8_startup-snapshot-api"><code>v8.startupSnapshot</code> API</a> to adapt to
these constraints. See
<a href="#all_cli_--build-snapshot">documentation about startup snapshot support in Node.js</a>.</p>
<h4>V8 code cache support<span><a class="mark" href="#all_single-executable-applications_v8-code-cache-support" id="all_single-executable-applications_v8-code-cache-support">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_v8_code_cache_support"></a></h4>
<p>When <code>useCodeCache</code> is set to <code>true</code> in the configuration, during the generation
of the single executable preparation blob, Node.js will compile the <code>main</code>
script to generate the V8 code cache. The generated code cache would be part of
the preparation blob and get injected into the final executable. When the single
executable application is launched, instead of compiling the <code>main</code> script from
scratch, Node.js would use the code cache to speed up the compilation, then
execute the script, which would improve the startup performance.</p>
<p><strong>Note:</strong> <code>import()</code> does not work when <code>useCodeCache</code> is <code>true</code>.</p>
</section><section><h3>In the injected main script<span><a class="mark" href="#all_single-executable-applications_in-the-injected-main-script" id="all_single-executable-applications_in-the-injected-main-script">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_in_the_injected_main_script"></a></h3>
<h4>Single-executable application API<span><a class="mark" href="#all_single-executable-applications_single-executable-application-api" id="all_single-executable-applications_single-executable-application-api">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_single_executable_application_api"></a></h4>
<p>The <code>node:sea</code> builtin allows interaction with the single-executable application
from the JavaScript main script embedded into the executable.</p>
<h5><code>sea.isSea()</code><span><a class="mark" href="#all_single-executable-applications_seaissea" id="all_single-executable-applications_seaissea">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_sea_issea"></a></h5>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether this script is running inside a single-executable
application.</li>
</ul>
<h4><code>sea.getAsset(key[, encoding])</code><span><a class="mark" href="#all_single-executable-applications_seagetassetkey-encoding" id="all_single-executable-applications_seagetassetkey-encoding">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_sea_getasset_key_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p>This method can be used to retrieve the assets configured to be bundled into the
single-executable application at build time.
An error is thrown when no matching asset can be found.</p>
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> the key for the asset in the dictionary specified by the
<code>assets</code> field in the single-executable application configuration.</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, the asset will be decoded as
a string. Any encoding supported by the <code>TextDecoder</code> is accepted.
If unspecified, an <code>ArrayBuffer</code> containing a copy of the asset would be
returned instead.</li>
<li>Returns: <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/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a></li>
</ul>
<h4><code>sea.getAssetAsBlob(key[, options])</code><span><a class="mark" href="#all_single-executable-applications_seagetassetasblobkey-options" id="all_single-executable-applications_seagetassetasblobkey-options">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_sea_getassetasblob_key_options"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p>Similar to <a href="#all_single-executable-applications_seagetassetkey-encoding"><code>sea.getAsset()</code></a>, but returns the result in a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob"><code>Blob</code></a>.
An error is thrown when no matching asset can be found.</p>
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> the key for the asset in the dictionary specified by the
<code>assets</code> field in the single-executable application configuration.</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>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> An optional mime type for the blob.</li>
</ul>
</li>
<li>Returns: <a href="#all_buffer_class-blob" class="type"><Blob></a></li>
</ul>
<h4><code>sea.getRawAsset(key)</code><span><a class="mark" href="#all_single-executable-applications_seagetrawassetkey" id="all_single-executable-applications_seagetrawassetkey">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_sea_getrawasset_key"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p>This method can be used to retrieve the assets configured to be bundled into the
single-executable application at build time.
An error is thrown when no matching asset can be found.</p>
<p>Unlike <code>sea.getAsset()</code> or <code>sea.getAssetAsBlob()</code>, this method does not
return a copy. Instead, it returns the raw asset bundled inside the executable.</p>
<p>For now, users should avoid writing to the returned array buffer. If the
injected section is not marked as writable or not aligned properly,
writes to the returned array buffer is likely to result in a crash.</p>
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> the key for the asset in the dictionary specified by the
<code>assets</code> field in the single-executable application configuration.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a></li>
</ul>
<h4><code>require(id)</code> in the injected main script is not file based<span><a class="mark" href="#all_single-executable-applications_requireid-in-the-injected-main-script-is-not-file-based" id="all_single-executable-applications_requireid-in-the-injected-main-script-is-not-file-based">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_require_id_in_the_injected_main_script_is_not_file_based"></a></h4>
<p><code>require()</code> in the injected main script is not the same as the <a href="#all_modules_requireid"><code>require()</code></a>
available to modules that are not injected. It also does not have any of the
properties that non-injected <a href="#all_modules_requireid"><code>require()</code></a> has except <a href="#all_modules_accessing-the-main-module"><code>require.main</code></a>. It
can only be used to load built-in modules. Attempting to load a module that can
only be found in the file system will throw an error.</p>
<p>Instead of relying on a file based <code>require()</code>, users can bundle their
application into a standalone JavaScript file to inject into the executable.
This also ensures a more deterministic dependency graph.</p>
<p>However, if a file based <code>require()</code> is still needed, that can also be achieved:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { createRequire } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-built_in">require</span> = <span class="hljs-title function_">createRequire</span>(__filename);</code> <button class="copy-button">copy</button></pre>
<h4><code>__filename</code> and <code>module.filename</code> in the injected main script<span><a class="mark" href="#all_single-executable-applications___filename-and-modulefilename-in-the-injected-main-script" id="all_single-executable-applications___filename-and-modulefilename-in-the-injected-main-script">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_filename_and_module_filename_in_the_injected_main_script"></a></h4>
<p>The values of <code>__filename</code> and <code>module.filename</code> in the injected main script
are equal to <a href="#all_process_processexecpath"><code>process.execPath</code></a>.</p>
<h4><code>__dirname</code> in the injected main script<span><a class="mark" href="#all_single-executable-applications___dirname-in-the-injected-main-script" id="all_single-executable-applications___dirname-in-the-injected-main-script">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_dirname_in_the_injected_main_script"></a></h4>
<p>The value of <code>__dirname</code> in the injected main script is equal to the directory
name of <a href="#all_process_processexecpath"><code>process.execPath</code></a>.</p>
</section><section><h3>Notes<span><a class="mark" href="#all_single-executable-applications_notes" id="all_single-executable-applications_notes">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_notes"></a></h3>
<h4>Single executable application creation process<span><a class="mark" href="#all_single-executable-applications_single-executable-application-creation-process" id="all_single-executable-applications_single-executable-application-creation-process">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_single_executable_application_creation_process"></a></h4>
<p>A tool aiming to create a single executable Node.js application must
inject the contents of the blob prepared with <code>--experimental-sea-config"</code>
into:</p>
<ul>
<li>a resource named <code>NODE_SEA_BLOB</code> if the <code>node</code> binary is a <a href="https://en.wikipedia.org/wiki/Portable_Executable">PE</a> file</li>
<li>a section named <code>NODE_SEA_BLOB</code> in the <code>NODE_SEA</code> segment if the <code>node</code> binary
is a <a href="https://en.wikipedia.org/wiki/Mach-O">Mach-O</a> file</li>
<li>a note named <code>NODE_SEA_BLOB</code> if the <code>node</code> binary is an <a href="https://en.wikipedia.org/wiki/Executable_and_Linkable_Format">ELF</a> file</li>
</ul>
<p>Search the binary for the
<code>NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2:0</code> <a href="https://www.electronjs.org/docs/latest/tutorial/fuses">fuse</a> string and flip the
last character to <code>1</code> to indicate that a resource has been injected.</p>
<h4>Platform support<span><a class="mark" href="#all_single-executable-applications_platform-support" id="all_single-executable-applications_platform-support">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_platform_support"></a></h4>
<p>Single-executable support is tested regularly on CI only on the following
platforms:</p>
<ul>
<li>Windows</li>
<li>macOS</li>
<li>Linux (all distributions <a href="https://github.com/nodejs/node/blob/main/BUILDING.md#platform-list">supported by Node.js</a> except Alpine and all
architectures <a href="https://github.com/nodejs/node/blob/main/BUILDING.md#platform-list">supported by Node.js</a> except s390x)</li>
</ul>
<p>This is due to a lack of better tools to generate single-executables that can be
used to test this feature on other platforms.</p>
<p>Suggestions for other resource injection tools/workflows are welcomed. Please
start a discussion at <a href="https://github.com/nodejs/single-executable/discussions">https://github.com/nodejs/single-executable/discussions</a>
to help us document them.</p></section>
</section>
<section><h2>Stream<a class="srclink" href="https://github.com/nodejs/node/blob/10eb2fb02ca31ee6ba14961921aae404ca57a1b5/lib/stream.js#L55">[src]</a><span><a class="mark" href="#all_stream_stream" id="all_stream_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="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/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="#all_http_class-httpincomingmessage">request to an HTTP server</a> and <a href="#all_process_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="#all_events_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="#all_stream_organization-of-this-document" id="all_stream_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="#all_stream_types-of-streams" id="all_stream_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="#all_stream_class-streamwritable"><code>Writable</code></a>: streams to which data can be written (for example,
<a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a>).</li>
<li><a href="#all_stream_class-streamreadable"><code>Readable</code></a>: streams from which data can be read (for example,
<a href="#all_fs_fscreatereadstreampath-options"><code>fs.createReadStream()</code></a>).</li>
<li><a href="#all_stream_class-streamduplex"><code>Duplex</code></a>: streams that are both <code>Readable</code> and <code>Writable</code> (for example,
<a href="#all_net_class-netsocket"><code>net.Socket</code></a>).</li>
<li><a href="#all_stream_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="#all_zlib_zlibcreatedeflateoptions"><code>zlib.createDeflate()</code></a>).</li>
</ul>
<p>Additionally, this module includes the utility functions
<a href="#all_stream_streamduplexpairoptions"><code>stream.duplexPair()</code></a>,
<a href="#all_stream_streampipelinesource-transforms-destination-callback"><code>stream.pipeline()</code></a>,
<a href="#all_stream_streamfinishedstream-options-callback"><code>stream.finished()</code></a>
<a href="#all_stream_streamreadablefromiterable-options"><code>stream.Readable.from()</code></a>, and
<a href="#all_stream_streamaddabortsignalsignal-stream"><code>stream.addAbortSignal()</code></a>.</p>
<h4>Streams Promises API<span><a class="mark" href="#all_stream_streams-promises-api" id="all_stream_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="#all_stream_streampipelinesource-transforms-destination-options" id="all_stream_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="#all_stream_streampipelinestreams-options" id="all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_globals_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="#all_stream_streampipelinesource-transforms-destination-callback">callback version</a>:</p>
<h4><code>stream.finished(stream[, options])</code><span><a class="mark" href="#all_stream_streamfinishedstream-options" id="all_stream_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>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="#all_stream_stream" class="type"><Stream></a> | <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> | <a href="#all_webstreams_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="#all_globals_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>
</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="#all_stream_streamfinishedstream-options-callback">callback version</a>.</p>
<h4>Object mode<span><a class="mark" href="#all_stream_object-mode" id="all_stream_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="#all_buffer_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="#all_stream_buffering" id="all_stream_buffering">#</a></span><a aria-hidden="true" class="legacy" id="stream_buffering"></a></h4>
<p>Both <a href="#all_stream_class-streamwritable"><code>Writable</code></a> and <a href="#all_stream_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="#all_stream_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="#all_stream_readablepushchunk-encoding"><code>stream.push(chunk)</code></a>. If the consumer of the Stream does not
call <a href="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_class-streamduplex"><code>Duplex</code></a> and <a href="#all_stream_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="#all_net_class-netsocket"><code>net.Socket</code></a> instances are <a href="#all_stream_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="#all_stream_api-for-stream-consumers" id="all_stream_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="#all_stream_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="#all_stream_class-streamreadable"><code>Readable</code></a> streams use the <a href="#all_events_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="#all_stream_class-streamwritable"><code>Writable</code></a> and <a href="#all_stream_class-streamreadable"><code>Readable</code></a> streams use the <a href="#all_events_class-eventemitter"><code>EventEmitter</code></a> API in
various ways to communicate the current state of the stream.</p>
<p><a href="#all_stream_class-streamduplex"><code>Duplex</code></a> and <a href="#all_stream_class-streamtransform"><code>Transform</code></a> streams are both <a href="#all_stream_class-streamwritable"><code>Writable</code></a> and
<a href="#all_stream_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="#all_stream_api-for-stream-implementers">API for stream implementers</a>.</p>
<h4>Writable streams<span><a class="mark" href="#all_stream_writable-streams" id="all_stream_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="#all_stream_class-streamwritable"><code>Writable</code></a> streams include:</p>
<ul>
<li><a href="#all_http_class-httpclientrequest">HTTP requests, on the client</a></li>
<li><a href="#all_http_class-httpserverresponse">HTTP responses, on the server</a></li>
<li><a href="#all_fs_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="#all_net_class-netsocket">TCP sockets</a></li>
<li><a href="#all_child_process_subprocessstdin">child process stdin</a></li>
<li><a href="#all_process_processstdout"><code>process.stdout</code></a>, <a href="#all_process_processstderr"><code>process.stderr</code></a></li>
</ul>
<p>Some of these examples are actually <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> streams that implement the
<a href="#all_stream_class-streamwritable"><code>Writable</code></a> interface.</p>
<p>All <a href="#all_stream_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="#all_stream_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="#all_stream_class-streamwritable" id="all_stream_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="#all_stream_event-close" id="all_stream_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="#all_stream_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="#all_stream_event-drain" id="all_stream_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="#all_stream_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="#all_stream_event-error" id="all_stream_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="#all_stream_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="#all_stream_event-finish" id="all_stream_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="#all_stream_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="#all_stream_event-pipe" id="all_stream_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="#all_stream_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="#all_stream_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="#all_stream_event-unpipe" id="all_stream_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="#all_stream_class-streamreadable" class="type"><stream.Readable></a> The source stream that
<a href="#all_stream_readableunpipedestination">unpiped</a> this writable</li>
</ul>
<p>The <code>'unpipe'</code> event is emitted when the <a href="#all_stream_readableunpipedestination"><code>stream.unpipe()</code></a> method is called
on a <a href="#all_stream_class-streamreadable"><code>Readable</code></a> stream, removing this <a href="#all_stream_class-streamwritable"><code>Writable</code></a> from its set of
destinations.</p>
<p>This is also emitted in case this <a href="#all_stream_class-streamwritable"><code>Writable</code></a> stream emits an error when a
<a href="#all_stream_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="#all_stream_writablecork" id="all_stream_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="#all_stream_writableuncork"><code>stream.uncork()</code></a> or
<a href="#all_stream_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="#all_stream_writableuncork"><code>writable.uncork()</code></a>, <a href="#all_stream_writable_writevchunks-callback"><code>writable._writev()</code></a>.</p>
<h6><code>writable.destroy([error])</code><span><a class="mark" href="#all_stream_writabledestroyerror" id="all_stream_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="#all_stream_writable_destroyerr-callback"><code>writable._destroy()</code></a>.</p>
<h6><code>writable.closed</code><span><a class="mark" href="#all_stream_writableclosed" id="all_stream_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="#all_stream_writabledestroyed" id="all_stream_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="#all_stream_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="#all_stream_writableendchunk-encoding-callback" id="all_stream_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>v20.13.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="#all_buffer_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="#all_buffer_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="#all_stream_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="#all_stream_writablewritechunk-encoding-callback"><code>stream.write()</code></a> method after calling
<a href="#all_stream_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="#all_stream_writablesetdefaultencodingencoding" id="all_stream_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="#all_stream_class-streamwritable"><code>Writable</code></a> stream.</p>
<h6><code>writable.uncork()</code><span><a class="mark" href="#all_stream_writableuncork" id="all_stream_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="#all_stream_writablecork"><code>stream.cork()</code></a> was called.</p>
<p>When using <a href="#all_stream_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="#all_stream_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="#all_stream_writablecork"><code>writable.cork()</code></a>.</p>
<h6><code>writable.writable</code><span><a class="mark" href="#all_stream_writablewritable" id="all_stream_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="#all_stream_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="#all_stream_writablewritableaborted" id="all_stream_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="#all_documentation_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="#all_stream_writablewritableended" id="all_stream_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="#all_stream_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="#all_stream_writablewritablefinished"><code>writable.writableFinished</code></a> instead.</p>
<h6><code>writable.writableCorked</code><span><a class="mark" href="#all_stream_writablewritablecorked" id="all_stream_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="#all_stream_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="#all_stream_writableerrored" id="all_stream_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="#all_stream_writablewritablefinished" id="all_stream_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="#all_stream_event-finish"><code>'finish'</code></a> event is emitted.</p>
<h6><code>writable.writableHighWaterMark</code><span><a class="mark" href="#all_stream_writablewritablehighwatermark" id="all_stream_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="#all_stream_writablewritablelength" id="all_stream_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="#all_stream_writablewritableneeddrain" id="all_stream_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="#all_stream_writablewritableobjectmode" id="all_stream_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="#all_stream_writablesymbolasyncdispose" id="all_stream_writablesymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_symbol_asyncdispose"></a></h6>
<div class="api_metadata">
<span>Added in: v20.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_stream_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="#all_stream_writablewritechunk-encoding-callback" id="all_stream_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>v20.13.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="#all_buffer_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="#all_buffer_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="#all_stream_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="#all_stream_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="#all_stream_class-streamreadable"><code>Readable</code></a> and use
<a href="#all_stream_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="#all_stream_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="#all_stream_readable-streams" id="all_stream_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="#all_http_class-httpincomingmessage">HTTP responses, on the client</a></li>
<li><a href="#all_http_class-httpincomingmessage">HTTP requests, on the server</a></li>
<li><a href="#all_fs_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="#all_net_class-netsocket">TCP sockets</a></li>
<li><a href="#all_child_process_subprocessstdout">child process stdout and stderr</a></li>
<li><a href="#all_process_processstdin"><code>process.stdin</code></a></li>
</ul>
<p>All <a href="#all_stream_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="#all_stream_two-reading-modes" id="all_stream_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="#all_stream_object-mode">object mode</a>.
A <a href="#all_stream_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="#all_events_class-eventemitter"><code>EventEmitter</code></a> interface.</p>
</li>
<li>
<p>In paused mode, the <a href="#all_stream_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="#all_stream_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="#all_stream_event-data"><code>'data'</code></a> event handler.</li>
<li>Calling the <a href="#all_stream_readableresume"><code>stream.resume()</code></a> method.</li>
<li>Calling the <a href="#all_stream_readablepipedestination-options"><code>stream.pipe()</code></a> method to send the data to a <a href="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_event-readable"><code>'readable'</code></a> event handler automatically makes the stream
stop flowing, and the data has to be consumed via
<a href="#all_stream_readablereadsize"><code>readable.read()</code></a>. If the <a href="#all_stream_event-readable"><code>'readable'</code></a> event handler is
removed, then the stream will start flowing again if there is a
<a href="#all_stream_event-data"><code>'data'</code></a> event handler.</p>
<h5>Three states<span><a class="mark" href="#all_stream_three-states" id="all_stream_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="#all_stream_choose-one-api-style" id="all_stream_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="#all_stream_class-streamreadable" id="all_stream_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="#all_stream_event-close_1" id="all_stream_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="#all_stream_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="#all_stream_event-data" id="all_stream_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="#all_buffer_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="#all_stream_event-end" id="all_stream_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="#all_stream_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="#all_stream_event-error_1" id="all_stream_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="#all_stream_event-pause" id="all_stream_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="#all_stream_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="#all_stream_event-readable" id="all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_event-resume" id="all_stream_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="#all_stream_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="#all_stream_readabledestroyerror" id="all_stream_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="#all_stream_readable_destroyerr-callback"><code>readable._destroy()</code></a>.</p>
<h6><code>readable.closed</code><span><a class="mark" href="#all_stream_readableclosed" id="all_stream_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="#all_stream_readabledestroyed" id="all_stream_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="#all_stream_readabledestroyerror"><code>readable.destroy()</code></a> has been called.</p>
<h6><code>readable.isPaused()</code><span><a class="mark" href="#all_stream_readableispaused" id="all_stream_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="#all_stream_readablepause" id="all_stream_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="#all_stream_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="#all_stream_readablepipedestination-options" id="all_stream_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="#all_stream_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="#all_stream_class-streamwritable" class="type"><stream.Writable></a> The <em>destination</em>, allowing for a chain of pipes if
it is a <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> or a <a href="#all_stream_class-streamtransform"><code>Transform</code></a> stream</li>
</ul>
<p>The <code>readable.pipe()</code> method attaches a <a href="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_process_processstderr"><code>process.stderr</code></a> and <a href="#all_process_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="#all_stream_readablereadsize" id="all_stream_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="#all_buffer_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="#all_stream_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="#all_stream_readablereadsize"><code>stream.read([size])</code></a> after the <a href="#all_stream_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="#all_stream_readablereadable" id="all_stream_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="#all_stream_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="#all_stream_readablereadableaborted" id="all_stream_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="#all_documentation_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="#all_stream_readablereadabledidread" id="all_stream_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="#all_documentation_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="#all_stream_readablereadableencoding" id="all_stream_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="#all_stream_readablesetencodingencoding"><code>readable.setEncoding()</code></a> method.</p>
<h6><code>readable.readableEnded</code><span><a class="mark" href="#all_stream_readablereadableended" id="all_stream_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="#all_stream_event-end"><code>'end'</code></a> event is emitted.</p>
<h6><code>readable.errored</code><span><a class="mark" href="#all_stream_readableerrored" id="all_stream_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="#all_stream_readablereadableflowing" id="all_stream_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="#all_stream_three-states">Three states</a> section.</p>
<h6><code>readable.readableHighWaterMark</code><span><a class="mark" href="#all_stream_readablereadablehighwatermark" id="all_stream_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="#all_stream_readablereadablelength" id="all_stream_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="#all_stream_readablereadableobjectmode" id="all_stream_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="#all_stream_readableresume" id="all_stream_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="#all_stream_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="#all_stream_readablesetencodingencoding" id="all_stream_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="#all_stream_readableunpipedestination" id="all_stream_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="#all_stream_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="#all_stream_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="#all_stream_readableunshiftchunk-encoding" id="all_stream_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>v20.13.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="#all_buffer_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="#all_buffer_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="#all_stream_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="#all_stream_class-streamtransform"><code>Transform</code></a> stream instead. See the <a href="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_readablewrapstream" id="all_stream_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="#all_stream_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="#all_stream_compatibility-with-older-nodejs-versions">Compatibility</a> for more
information.)</p>
<p>When using an older Node.js library that emits <a href="#all_stream_event-data"><code>'data'</code></a> events and has a
<a href="#all_stream_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="#all_stream_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="#all_stream_readablesymbolasynciterator" id="all_stream_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="#all_fs_fscreatereadstreampath-options"><code>fs.createReadStream()</code></a>.</p>
<h6><code>readable[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_stream_readablesymbolasyncdispose" id="all_stream_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</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_stream_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="#all_stream_readablecomposestream-options" id="all_stream_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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>stream</code> <a href="#all_stream_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="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_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="#all_stream_streamcomposestreams"><code>stream.compose</code></a> for more information.</p>
<h6><code>readable.iterator([options])</code><span><a class="mark" href="#all_stream_readableiteratoroptions" id="all_stream_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="#all_documentation_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="#all_stream_readablemapfn-options" id="all_stream_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</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="#all_documentation_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="#all_globals_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="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_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="#all_stream_readablefilterfn-options" id="all_stream_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</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="#all_documentation_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="#all_globals_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="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_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="#all_stream_readableforeachfn-options" id="all_stream_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="#all_documentation_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="#all_globals_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="#all_globals_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="#all_stream_event-data"><code>'data'</code></a> event in that it
uses the <a href="#all_stream_class-streamreadable"><code>readable</code></a> event in the underlying machinary 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="#all_stream_readabletoarrayoptions" id="all_stream_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="#all_documentation_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="#all_globals_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="#all_stream_readablesomefn-options" id="all_stream_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="#all_documentation_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="#all_globals_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="#all_globals_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="#all_stream_readablefindfn-options" id="all_stream_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="#all_documentation_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="#all_globals_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="#all_globals_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="#all_stream_readableeveryfn-options" id="all_stream_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="#all_documentation_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="#all_globals_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="#all_globals_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="#all_stream_readableflatmapfn-options" id="all_stream_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="#all_documentation_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="#all_globals_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="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_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="#all_stream_readabledroplimit-options" id="all_stream_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="#all_documentation_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="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_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="#all_stream_readabletakelimit-options" id="all_stream_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="#all_documentation_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="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_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.asIndexedPairs([options])</code><span><a class="mark" href="#all_stream_readableasindexedpairsoptions" id="all_stream_readableasindexedpairsoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_asindexedpairs_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.3.0</td>
<td><p>Using the <code>asIndexedPairs</code> method emits a runtime warning that it will be removed in a future version.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p><span>Added in: v17.5.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_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="#all_globals_class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamreadable" class="type"><Readable></a> a stream of indexed pairs.</li>
</ul>
<p>This method returns a new stream with chunks of the underlying stream paired
with a counter in the form <code>[index, chunk]</code>. The first index value is 0 and it
increases by 1 for each chunk produced.</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">const</span> pairs = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>]).<span class="hljs-title function_">asIndexedPairs</span>().<span class="hljs-title function_">toArray</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(pairs); <span class="hljs-comment">// [[0, 'a'], [1, 'b'], [2, 'c']]</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.reduce(fn[, initial[, options]])</code><span><a class="mark" href="#all_stream_readablereducefn-initial-options" id="all_stream_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="#all_documentation_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="#all_globals_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="#all_globals_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="#all_stream_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="#all_stream_duplex-and-transform-streams" id="all_stream_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="#all_stream_class-streamduplex" id="all_stream_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="#all_stream_class-streamreadable"><code>Readable</code></a> and
<a href="#all_stream_class-streamwritable"><code>Writable</code></a> interfaces.</p>
<p>Examples of <code>Duplex</code> streams include:</p>
<ul>
<li><a href="#all_net_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="#all_stream_duplexallowhalfopen" id="all_stream_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="#all_stream_class-streamtransform" id="all_stream_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="#all_stream_class-streamduplex"><code>Duplex</code></a> streams where the output is in some way
related to the input. Like all <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> streams, <code>Transform</code> streams
implement both the <a href="#all_stream_class-streamreadable"><code>Readable</code></a> and <a href="#all_stream_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="#all_stream_transformdestroyerror" id="all_stream_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="#all_stream_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="#all_stream_streamduplexpairoptions" id="all_stream_streamduplexpairoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_duplexpair_options"></a></h5>
<div class="api_metadata">
<span>Added in: v20.17.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="#all_stream_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="#all_stream_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="#all_stream_streamfinishedstream-options-callback" id="all_stream_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="#all_stream_stream" class="type"><Stream></a> | <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> | <a href="#all_webstreams_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="#all_globals_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>
<li><code>cleanup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> remove all registered stream listeners.
<strong>Default:</strong> <code>false</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 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="#all_stream_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="#all_stream_streampipelinesource-transforms-destination-callback" id="all_stream_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="#all_stream_streampipelinestreams-callback" id="all_stream_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</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="#all_stream_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="#all_webstreams_class-readablestream" class="type"><ReadableStream[]></a> | <a href="#all_webstreams_class-writablestream" class="type"><WritableStream[]></a> | <a href="#all_webstreams_class-transformstream" class="type"><TransformStream[]></a></li>
<li><code>source</code> <a href="#all_stream_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="#all_webstreams_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="#all_stream_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="#all_webstreams_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="#all_stream_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="#all_webstreams_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="#all_stream_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="#all_stream_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="#all_stream_streamcomposestreams" id="all_stream_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>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="#all_documentation_stability-index">Stability: 1</a> - <code>stream.compose</code> is experimental.</div><p></p>
<ul>
<li><code>streams</code> <a href="#all_stream_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="#all_webstreams_class-readablestream" class="type"><ReadableStream[]></a> | <a href="#all_webstreams_class-writablestream" class="type"><WritableStream[]></a> | <a href="#all_webstreams_class-transformstream" class="type"><TransformStream[]></a> | <a href="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_streamreadablefromiterable-options" id="all_stream_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="#all_stream_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="#all_stream_streamreadablefromwebreadablestream-options" id="all_stream_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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>readableStream</code> <a href="#all_webstreams_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="#all_globals_class-abortsignal" class="type"><AbortSignal></a></li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a></li>
</ul>
<h4><code>stream.Readable.isDisturbed(stream)</code><span><a class="mark" href="#all_stream_streamreadableisdisturbedstream" id="all_stream_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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a> | <a href="#all_webstreams_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="#all_stream_streamiserroredstream" id="all_stream_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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamreadable" class="type"><Readable></a> | <a href="#all_stream_class-streamwritable" class="type"><Writable></a> | <a href="#all_stream_class-streamduplex" class="type"><Duplex></a> | <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a> | <a href="#all_webstreams_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="#all_stream_streamisreadablestream" id="all_stream_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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamreadable" class="type"><Readable></a> | <a href="#all_stream_class-streamduplex" class="type"><Duplex></a> | <a href="#all_webstreams_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="#all_stream_streamreadabletowebstreamreadable-options" id="all_stream_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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>streamReadable</code> <a href="#all_stream_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="#all_webstreams_class-readablestream" class="type"><ReadableStream></a></li>
</ul>
<h4><code>stream.Writable.fromWeb(writableStream[, options])</code><span><a class="mark" href="#all_stream_streamwritablefromwebwritablestream-options" id="all_stream_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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>writableStream</code> <a href="#all_webstreams_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="#all_globals_class-abortsignal" class="type"><AbortSignal></a></li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a></li>
</ul>
<h4><code>stream.Writable.toWeb(streamWritable)</code><span><a class="mark" href="#all_stream_streamwritabletowebstreamwritable" id="all_stream_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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>streamWritable</code> <a href="#all_stream_class-streamwritable" class="type"><stream.Writable></a></li>
<li>Returns: <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a></li>
</ul>
<h4><code>stream.Duplex.from(src)</code><span><a class="mark" href="#all_stream_streamduplexfromsrc" id="all_stream_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</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="#all_stream_stream" class="type"><Stream></a> | <a href="#all_buffer_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="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> | <a href="#all_webstreams_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="#all_stream_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="#all_stream_streamduplexfromwebpair-options" id="all_stream_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="#all_documentation_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="#all_webstreams_class-readablestream" class="type"><ReadableStream></a></li>
<li><code>writable</code> <a href="#all_webstreams_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="#all_globals_class-abortsignal" class="type"><AbortSignal></a></li>
</ul>
</li>
<li>Returns: <a href="#all_stream_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="#all_stream_streamduplextowebstreamduplex" id="all_stream_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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>streamDuplex</code> <a href="#all_stream_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="#all_webstreams_class-readablestream" class="type"><ReadableStream></a></li>
<li><code>writable</code> <a href="#all_webstreams_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="#all_stream_streamaddabortsignalsignal-stream" id="all_stream_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</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="#all_globals_class-abortsignal" class="type"><AbortSignal></a> A signal representing possible cancellation</li>
<li><code>stream</code> <a href="#all_stream_stream" class="type"><Stream></a> | <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> | <a href="#all_webstreams_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="#all_stream_streamgetdefaulthighwatermarkobjectmode" id="all_stream_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</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="#all_stream_streamsetdefaulthighwatermarkobjectmode-value" id="all_stream_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</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="#all_stream_api-for-stream-implementers" id="all_stream_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="#all_stream_class-streamreadable"><code>Readable</code></a></td><td><a href="#all_stream_readable_readsize"><code>_read()</code></a></td></tr><tr><td>Writing only</td><td><a href="#all_stream_class-streamwritable"><code>Writable</code></a></td><td><a href="#all_stream_writable_writechunk-encoding-callback"><code>_write()</code></a>, <a href="#all_stream_writable_writevchunks-callback"><code>_writev()</code></a>, <a href="#all_stream_writable_finalcallback"><code>_final()</code></a></td></tr><tr><td>Reading and writing</td><td><a href="#all_stream_class-streamduplex"><code>Duplex</code></a></td><td><a href="#all_stream_readable_readsize"><code>_read()</code></a>, <a href="#all_stream_writable_writechunk-encoding-callback"><code>_write()</code></a>, <a href="#all_stream_writable_writevchunks-callback"><code>_writev()</code></a>, <a href="#all_stream_writable_finalcallback"><code>_final()</code></a></td></tr><tr><td>Operate on written data, then read the result</td><td><a href="#all_stream_class-streamtransform"><code>Transform</code></a></td><td><a href="#all_stream_transform_transformchunk-encoding-callback"><code>_transform()</code></a>, <a href="#all_stream_transform_flushcallback"><code>_flush()</code></a>, <a href="#all_stream_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="#all_stream_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="#all_stream_simplified-construction" id="all_stream_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="#all_stream_implementing-a-writable-stream" id="all_stream_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="#all_stream_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="#all_stream_new-streamwritableoptions" id="all_stream_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>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="#all_stream_writablewritechunk-encoding-callback"><code>stream.write()</code></a> starts returning <code>false</code>. <strong>Default:</strong>
<code>16384</code> (16 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="#all_stream_writablewritechunk-encoding-callback"><code>stream.write()</code></a> to <code>Buffer</code>s (with the encoding
specified in the <a href="#all_stream_writablewritechunk-encoding-callback"><code>stream.write()</code></a> call) before passing
them to <a href="#all_stream_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="#all_stream_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="#all_stream_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="#all_buffer_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_globals_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="#all_stream_writable_constructcallback" id="all_stream_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="#all_stream_writable_writechunk-encoding-callback" id="all_stream_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="#all_buffer_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="#all_stream_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="#all_stream_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="#all_stream_writable_writechunk-encoding-callback"><code>writable._write()</code></a> and/or
<a href="#all_stream_writable_writevchunks-callback"><code>writable._writev()</code></a> method to send data to the underlying
resource.</p>
<p><a href="#all_stream_class-streamtransform"><code>Transform</code></a> streams provide their own implementation of the
<a href="#all_stream_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="#all_stream_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="#all_stream_writable_writevchunks-callback" id="all_stream_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="#all_buffer_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="#all_stream_writable_destroyerr-callback" id="all_stream_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="#all_stream_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="#all_stream_writable_finalcallback" id="all_stream_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="#all_stream_errors-while-writing" id="all_stream_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="#all_stream_writable_writechunk-encoding-callback"><code>writable._write()</code></a>,
<a href="#all_stream_writable_writevchunks-callback"><code>writable._writev()</code></a> and <a href="#all_stream_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="#all_stream_an-example-writable-stream" id="all_stream_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="#all_stream_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="#all_stream_decoding-buffers-in-a-writable-stream" id="all_stream_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="#all_stream_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 && 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="#all_stream_implementing-a-readable-stream" id="all_stream_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="#all_stream_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="#all_stream_readable_readsize"><code>readable._read()</code></a> method.</p>
<h5><code>new stream.Readable([options])</code><span><a class="mark" href="#all_stream_new-streamreadableoptions" id="all_stream_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>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="#all_stream_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>16384</code> (16 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="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_globals_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="#all_stream_readable_constructcallback" id="all_stream_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="#all_stream_readable_readsize" id="all_stream_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="#all_stream_readable_readsize"><code>readable._read()</code></a> method to fetch data from the underlying resource.</p>
<p>When <a href="#all_stream_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="#all_stream_readablepushchunk-encoding"><code>this.push(dataChunk)</code></a> method. <code>_read()</code> will be called again
after each call to <a href="#all_stream_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="#all_stream_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="#all_stream_readablepushchunk-encoding"><code>readable.push()</code></a>
method. Empty data such as empty buffers and strings will not cause
<a href="#all_stream_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="#all_stream_readablepushchunk-encoding"><code>stream.push(chunk)</code></a>.</p>
<p>The <a href="#all_stream_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="#all_stream_readable_destroyerr-callback" id="all_stream_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="#all_stream_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="#all_stream_readablepushchunk-encoding" id="all_stream_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>v20.13.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="#all_buffer_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="#all_buffer_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="#all_buffer_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="#all_stream_readablereadsize"><code>readable.read()</code></a> method when the <a href="#all_stream_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="#all_stream_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="#all_stream_readablepush"><code>readable.push('')</code></a> for more information.</p>
<h5>Errors while reading<span><a class="mark" href="#all_stream_errors-while-reading" id="all_stream_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="#all_stream_readable_readsize"><code>readable._read()</code></a> must be
propagated through the <a href="#all_stream_readable_destroyerr-callback"><code>readable.destroy(err)</code></a> method.
Throwing an <code>Error</code> from within <a href="#all_stream_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="#all_stream_an-example-counting-stream" id="all_stream_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="#all_stream_implementing-a-duplex-stream" id="all_stream_implementing-a-duplex-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_duplex_stream"></a></h4>
<p>A <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> stream is one that implements both <a href="#all_stream_class-streamreadable"><code>Readable</code></a> and
<a href="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_new-streamduplexoptions" id="all_stream_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="#all_stream_an-example-duplex-stream" id="all_stream_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="#all_stream_class-streamwritable"><code>Writable</code></a> interface that is read back out
via the <a href="#all_stream_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="#all_stream_object-mode-duplex-streams" id="all_stream_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="#all_stream_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="#all_stream_implementing-a-transform-stream" id="all_stream_implementing-a-transform-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_transform_stream"></a></h4>
<p>A <a href="#all_stream_class-streamtransform"><code>Transform</code></a> stream is a <a href="#all_stream_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="#all_stream_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="#all_stream_readable_readsize"><code>readable._read()</code></a> methods. Custom <code>Transform</code> implementations <em>must</em>
implement the <a href="#all_stream_transform_transformchunk-encoding-callback"><code>transform._transform()</code></a> method and <em>may</em>
also implement the <a href="#all_stream_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="#all_stream_new-streamtransformoptions" id="all_stream_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="#all_stream_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="#all_stream_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="#all_stream_event-end_1" id="all_stream_event-end_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_end_1"></a></h5>
<p>The <a href="#all_stream_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="#all_stream_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="#all_stream_event-finish_1" id="all_stream_event-finish_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_finish_1"></a></h5>
<p>The <a href="#all_stream_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="#all_stream_writableendchunk-encoding-callback"><code>stream.end()</code></a> is called and all chunks
have been processed by <a href="#all_stream_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="#all_stream_transform_flushcallback" id="all_stream_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="#all_stream_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="#all_stream_event-end"><code>'end'</code></a> event is emitted signaling the end of the
<a href="#all_stream_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="#all_stream_transform_transformchunk-encoding-callback" id="all_stream_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="#all_buffer_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="#all_stream_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="#all_stream_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="#all_stream_class-streampassthrough" id="all_stream_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="#all_stream_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="#all_stream_additional-notes" id="all_stream_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="#all_stream_streams-compatibility-with-async-generators-and-async-iterators" id="all_stream_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="#all_stream_consuming-readable-streams-with-async-iterators" id="all_stream_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="#all_stream_creating-readable-streams-with-async-generators" id="all_stream_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="#all_stream_piping-to-writable-streams-from-async-iterators" id="all_stream_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="#all_stream_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="#all_stream_compatibility-with-older-nodejs-versions" id="all_stream_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="#all_stream_readablereadsize"><code>stream.read()</code></a> method,
<a href="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_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="#all_stream_event-data"><code>'data'</code></a> event handler is added, or when the
<a href="#all_stream_readableresume"><code>stream.resume()</code></a> method is called. The effect is that, even
when not using the new <a href="#all_stream_readablereadsize"><code>stream.read()</code></a> method and
<a href="#all_stream_event-readable"><code>'readable'</code></a> event, it is no longer necessary to worry about losing
<a href="#all_stream_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="#all_stream_event-data"><code>'data'</code></a> event listener is added.</li>
<li>The <a href="#all_stream_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="#all_stream_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="#all_stream_readablewrapstream"><code>readable.wrap()</code></a> method.</p>
<h4><code>readable.read(0)</code><span><a class="mark" href="#all_stream_readableread0" id="all_stream_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="#all_stream_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="#all_stream_readablepush" id="all_stream_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="#all_buffer_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="#all_stream_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="#all_stream_highwatermark-discrepancy-after-calling-readablesetencoding" id="all_stream_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>
</section>
<section><h2>String decoder<span><a class="mark" href="#all_string_decoder_string-decoder" id="all_string_decoder_string-decoder">#</a></span><a aria-hidden="true" class="legacy" id="string_decoder_string_decoder"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/string_decoder.js">lib/string_decoder.js</a></p>
<p>The <code>node:string_decoder</code> module provides an API for decoding <code>Buffer</code> objects
into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
characters. It can be accessed using:</p>
<pre class="with-57-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_">StringDecoder</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:string_decoder'</span>;</code><code class="language-js cjs"><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>);</code><button class="copy-button">copy</button></pre>
<p>The following example shows the basic use of the <code>StringDecoder</code> class.</p>
<pre class="with-57-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_">StringDecoder</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:string_decoder'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<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">const</span> cent = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0xC2</span>, <span class="hljs-number">0xA2</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decoder.<span class="hljs-title function_">write</span>(cent)); <span class="hljs-comment">// Prints: ¢</span>
<span class="hljs-keyword">const</span> euro = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0xE2</span>, <span class="hljs-number">0x82</span>, <span class="hljs-number">0xAC</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decoder.<span class="hljs-title function_">write</span>(euro)); <span class="hljs-comment">// Prints: €</span></code><code class="language-js cjs"><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">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">const</span> cent = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0xC2</span>, <span class="hljs-number">0xA2</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decoder.<span class="hljs-title function_">write</span>(cent)); <span class="hljs-comment">// Prints: ¢</span>
<span class="hljs-keyword">const</span> euro = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0xE2</span>, <span class="hljs-number">0x82</span>, <span class="hljs-number">0xAC</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decoder.<span class="hljs-title function_">write</span>(euro)); <span class="hljs-comment">// Prints: €</span></code><button class="copy-button">copy</button></pre>
<p>When a <code>Buffer</code> instance is written to the <code>StringDecoder</code> instance, an
internal buffer is used to ensure that the decoded string does not contain
any incomplete multibyte characters. These are held in the buffer until the
next call to <code>stringDecoder.write()</code> or until <code>stringDecoder.end()</code> is called.</p>
<p>In the following example, the three UTF-8 encoded bytes of the European Euro
symbol (<code>€</code>) are written over three separate operations:</p>
<pre class="with-57-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_">StringDecoder</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:string_decoder'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<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>);
decoder.<span class="hljs-title function_">write</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0xE2</span>]));
decoder.<span class="hljs-title function_">write</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x82</span>]));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decoder.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0xAC</span>]))); <span class="hljs-comment">// Prints: €</span></code><code class="language-js cjs"><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">const</span> decoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringDecoder</span>(<span class="hljs-string">'utf8'</span>);
decoder.<span class="hljs-title function_">write</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0xE2</span>]));
decoder.<span class="hljs-title function_">write</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x82</span>]));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decoder.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0xAC</span>]))); <span class="hljs-comment">// Prints: €</span></code><button class="copy-button">copy</button></pre>
<section><h3>Class: <code>StringDecoder</code><span><a class="mark" href="#all_string_decoder_class-stringdecoder" id="all_string_decoder_class-stringdecoder">#</a></span><a aria-hidden="true" class="legacy" id="string_decoder_class_stringdecoder"></a></h3>
<h4><code>new StringDecoder([encoding])</code><span><a class="mark" href="#all_string_decoder_new-stringdecoderencoding" id="all_string_decoder_new-stringdecoderencoding">#</a></span><a aria-hidden="true" class="legacy" id="string_decoder_new_stringdecoder_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.99</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 character <a href="#all_buffer_buffers-and-character-encodings">encoding</a> the <code>StringDecoder</code> will use.
<strong>Default:</strong> <code>'utf8'</code>.</li>
</ul>
<p>Creates a new <code>StringDecoder</code> instance.</p>
<h4><code>stringDecoder.end([buffer])</code><span><a class="mark" href="#all_string_decoder_stringdecoderendbuffer" id="all_string_decoder_stringdecoderendbuffer">#</a></span><a aria-hidden="true" class="legacy" id="string_decoder_stringdecoder_end_buffer"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div>
<ul>
<li><code>buffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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> The bytes to decode.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns any remaining input stored in the internal buffer as a string. Bytes
representing incomplete UTF-8 and UTF-16 characters will be replaced with
substitution characters appropriate for the character encoding.</p>
<p>If the <code>buffer</code> argument is provided, one final call to <code>stringDecoder.write()</code>
is performed before returning the remaining input.
After <code>end()</code> is called, the <code>stringDecoder</code> object can be reused for new input.</p>
<h4><code>stringDecoder.write(buffer)</code><span><a class="mark" href="#all_string_decoder_stringdecoderwritebuffer" id="all_string_decoder_stringdecoderwritebuffer">#</a></span><a aria-hidden="true" class="legacy" id="string_decoder_stringdecoder_write_buffer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Each invalid character is now replaced by a single replacement character instead of one for each individual byte.</p></td></tr>
<tr><td>v0.1.99</td>
<td><p><span>Added in: v0.1.99</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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> The bytes to decode.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns a decoded string, ensuring that any incomplete multibyte characters at
the end of the <code>Buffer</code>, or <code>TypedArray</code>, or <code>DataView</code> are omitted from the
returned string and stored in an internal buffer for the next call to
<code>stringDecoder.write()</code> or <code>stringDecoder.end()</code>.</p></section>
</section>
<section><h2>Test runner<span><a class="mark" href="#all_test_test-runner" id="all_test_test-runner">#</a></span><a aria-hidden="true" class="legacy" id="test_test_runner"></a></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The test runner is now stable.</p></td></tr>
<tr><td>v18.0.0, v16.17.0</td>
<td><p><span>Added in: v18.0.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/test.js">lib/test.js</a></p>
<p>The <code>node:test</code> module facilitates the creation of JavaScript tests.
To access it:</p>
<pre class="with-34-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> test <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> test = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);</code><button class="copy-button">copy</button></pre>
<p>This module is only available under the <code>node:</code> scheme. The following will not
work:</p>
<pre class="with-29-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> test <span class="hljs-keyword">from</span> <span class="hljs-string">'test'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> test = <span class="hljs-built_in">require</span>(<span class="hljs-string">'test'</span>);</code><button class="copy-button">copy</button></pre>
<p>Tests created via the <code>test</code> module consist of a single function that is
processed in one of three ways:</p>
<ol>
<li>A synchronous function that is considered failing if it throws an exception,
and is considered passing otherwise.</li>
<li>A function that returns a <code>Promise</code> that is considered failing if the
<code>Promise</code> rejects, and is considered passing if the <code>Promise</code> fulfills.</li>
<li>A function that receives a callback function. If the callback receives any
truthy value as its first argument, the test is considered failing. If a
falsy value is passed as the first argument to the callback, the test is
considered passing. If the test function receives a callback function and
also returns a <code>Promise</code>, the test will fail.</li>
</ol>
<p>The following example illustrates how tests are written using the
<code>test</code> module.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'synchronous passing test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-comment">// This test passes because it does not throw an exception.</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
});
<span class="hljs-title function_">test</span>(<span class="hljs-string">'synchronous failing test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-comment">// This test fails because it throws an exception.</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
});
<span class="hljs-title function_">test</span>(<span class="hljs-string">'asynchronous passing test'</span>, <span class="hljs-title function_">async</span> (t) => {
<span class="hljs-comment">// This test passes because the Promise returned by the async</span>
<span class="hljs-comment">// function is settled and not rejected.</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
});
<span class="hljs-title function_">test</span>(<span class="hljs-string">'asynchronous failing test'</span>, <span class="hljs-title function_">async</span> (t) => {
<span class="hljs-comment">// This test fails because the Promise returned by the async</span>
<span class="hljs-comment">// function is rejected.</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
});
<span class="hljs-title function_">test</span>(<span class="hljs-string">'failing test using Promises'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-comment">// Promises can be used directly as well.</span>
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></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">'this will cause the test to fail'</span>));
});
});
});
<span class="hljs-title function_">test</span>(<span class="hljs-string">'callback passing test'</span>, <span class="hljs-function">(<span class="hljs-params">t, done</span>) =></span> {
<span class="hljs-comment">// done() is the callback function. When the setImmediate() runs, it invokes</span>
<span class="hljs-comment">// done() with no arguments.</span>
<span class="hljs-title function_">setImmediate</span>(done);
});
<span class="hljs-title function_">test</span>(<span class="hljs-string">'callback failing test'</span>, <span class="hljs-function">(<span class="hljs-params">t, done</span>) =></span> {
<span class="hljs-comment">// When the setImmediate() runs, done() is invoked with an Error object and</span>
<span class="hljs-comment">// the test fails.</span>
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
<span class="hljs-title function_">done</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'callback failure'</span>));
});
});</code> <button class="copy-button">copy</button></pre>
<p>If any tests fail, the process exit code is set to <code>1</code>.</p>
<section><h3>Subtests<span><a class="mark" href="#all_test_subtests" id="all_test_subtests">#</a></span><a aria-hidden="true" class="legacy" id="test_subtests"></a></h3>
<p>The test context's <code>test()</code> method allows subtests to be created.
It allows you to structure your tests in a hierarchical manner,
where you can create nested tests within a larger test.
This method behaves identically to the top level <code>test()</code> function.
The following example demonstrates the creation of a
top level test with two subtests.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-title function_">async</span> (t) => {
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'subtest 1'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
});
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'subtest 2'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>);
});
});</code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Note:</strong> <code>beforeEach</code> and <code>afterEach</code> hooks are triggered
between each subtest execution.</p>
</blockquote>
<p>In this example, <code>await</code> is used to ensure that both subtests have completed.
This is necessary because tests do not wait for their subtests to
complete, unlike tests created within suites.
Any subtests that are still outstanding when their parent finishes
are cancelled and treated as failures. Any subtest failures cause the parent
test to fail.</p>
</section><section><h3>Skipping tests<span><a class="mark" href="#all_test_skipping-tests" id="all_test_skipping-tests">#</a></span><a aria-hidden="true" class="legacy" id="test_skipping_tests"></a></h3>
<p>Individual tests can be skipped by passing the <code>skip</code> option to the test, or by
calling the test context's <code>skip()</code> method as shown in the
following example.</p>
<pre><code class="language-js"><span class="hljs-comment">// The skip option is used, but no message is provided.</span>
<span class="hljs-title function_">test</span>(<span class="hljs-string">'skip option'</span>, { <span class="hljs-attr">skip</span>: <span class="hljs-literal">true</span> }, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-comment">// This code is never executed.</span>
});
<span class="hljs-comment">// The skip option is used, and a message is provided.</span>
<span class="hljs-title function_">test</span>(<span class="hljs-string">'skip option with message'</span>, { <span class="hljs-attr">skip</span>: <span class="hljs-string">'this is skipped'</span> }, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-comment">// This code is never executed.</span>
});
<span class="hljs-title function_">test</span>(<span class="hljs-string">'skip() method'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-comment">// Make sure to return here as well if the test contains additional logic.</span>
t.<span class="hljs-title function_">skip</span>();
});
<span class="hljs-title function_">test</span>(<span class="hljs-string">'skip() method with message'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-comment">// Make sure to return here as well if the test contains additional logic.</span>
t.<span class="hljs-title function_">skip</span>(<span class="hljs-string">'this is skipped'</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>TODO tests<span><a class="mark" href="#all_test_todo-tests" id="all_test_todo-tests">#</a></span><a aria-hidden="true" class="legacy" id="test_todo_tests"></a></h3>
<p>Individual tests can be marked as flaky or incomplete by passing the <code>todo</code>
option to the test, or by calling the test context's <code>todo()</code> method, as shown
in the following example. These tests represent a pending implementation or bug
that needs to be fixed. TODO tests are executed, but are not treated as test
failures, and therefore do not affect the process exit code. If a test is marked
as both TODO and skipped, the TODO option is ignored.</p>
<pre><code class="language-js"><span class="hljs-comment">// The todo option is used, but no message is provided.</span>
<span class="hljs-title function_">test</span>(<span class="hljs-string">'todo option'</span>, { <span class="hljs-attr">todo</span>: <span class="hljs-literal">true</span> }, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-comment">// This code is executed, but not treated as a failure.</span>
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'this does not fail the test'</span>);
});
<span class="hljs-comment">// The todo option is used, and a message is provided.</span>
<span class="hljs-title function_">test</span>(<span class="hljs-string">'todo option with message'</span>, { <span class="hljs-attr">todo</span>: <span class="hljs-string">'this is a todo test'</span> }, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-comment">// This code is executed.</span>
});
<span class="hljs-title function_">test</span>(<span class="hljs-string">'todo() method'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
t.<span class="hljs-title function_">todo</span>();
});
<span class="hljs-title function_">test</span>(<span class="hljs-string">'todo() method with message'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
t.<span class="hljs-title function_">todo</span>(<span class="hljs-string">'this is a todo test and is not treated as a failure'</span>);
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'this does not fail the test'</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>describe()</code> and <code>it()</code> aliases<span><a class="mark" href="#all_test_describe-and-it-aliases" id="all_test_describe-and-it-aliases">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_and_it_aliases"></a></h3>
<p>Suites and tests can also be written using the <code>describe()</code> and <code>it()</code>
functions. <a href="#all_test_describename-options-fn"><code>describe()</code></a> is an alias for <a href="#all_test_suitename-options-fn"><code>suite()</code></a>, and <a href="#all_test_itname-options-fn"><code>it()</code></a> is an
alias for <a href="#all_test_testname-options-fn"><code>test()</code></a>.</p>
<pre><code class="language-js"><span class="hljs-title function_">describe</span>(<span class="hljs-string">'A thing'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-title function_">it</span>(<span class="hljs-string">'should work'</span>, <span class="hljs-function">() =></span> {
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
});
<span class="hljs-title function_">it</span>(<span class="hljs-string">'should be ok'</span>, <span class="hljs-function">() =></span> {
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>);
});
<span class="hljs-title function_">describe</span>(<span class="hljs-string">'a nested thing'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-title function_">it</span>(<span class="hljs-string">'should work'</span>, <span class="hljs-function">() =></span> {
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">3</span>, <span class="hljs-number">3</span>);
});
});
});</code> <button class="copy-button">copy</button></pre>
<p><code>describe()</code> and <code>it()</code> are imported from the <code>node:test</code> module.</p>
<pre class="with-46-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> { describe, it } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { describe, it } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>only</code> tests<span><a class="mark" href="#all_test_only-tests" id="all_test_only-tests">#</a></span><a aria-hidden="true" class="legacy" id="test_only_tests"></a></h3>
<p>If Node.js is started with the <a href="#all_cli_--test-only"><code>--test-only</code></a> command-line option, it is
possible to skip all top level tests except for a selected subset by passing
the <code>only</code> option to the tests that should be run. When a test with the <code>only</code>
option set is run, all subtests are also run. The test context's <code>runOnly()</code>
method can be used to implement the same behavior at the subtest level.</p>
<pre><code class="language-js"><span class="hljs-comment">// Assume Node.js is run with the --test-only command-line option.</span>
<span class="hljs-comment">// The 'only' option is set, so this test is run.</span>
<span class="hljs-title function_">test</span>(<span class="hljs-string">'this test is run'</span>, { <span class="hljs-attr">only</span>: <span class="hljs-literal">true</span> }, <span class="hljs-title function_">async</span> (t) => {
<span class="hljs-comment">// Within this test, all subtests are run by default.</span>
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'running subtest'</span>);
<span class="hljs-comment">// The test context can be updated to run subtests with the 'only' option.</span>
t.<span class="hljs-title function_">runOnly</span>(<span class="hljs-literal">true</span>);
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'this subtest is now skipped'</span>);
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'this subtest is run'</span>, { <span class="hljs-attr">only</span>: <span class="hljs-literal">true</span> });
<span class="hljs-comment">// Switch the context back to execute all tests.</span>
t.<span class="hljs-title function_">runOnly</span>(<span class="hljs-literal">false</span>);
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'this subtest is now run'</span>);
<span class="hljs-comment">// Explicitly do not run these tests.</span>
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'skipped subtest 3'</span>, { <span class="hljs-attr">only</span>: <span class="hljs-literal">false</span> });
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'skipped subtest 4'</span>, { <span class="hljs-attr">skip</span>: <span class="hljs-literal">true</span> });
});
<span class="hljs-comment">// The 'only' option is not set, so this test is skipped.</span>
<span class="hljs-title function_">test</span>(<span class="hljs-string">'this test is not run'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// This code is not run.</span>
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'fail'</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Filtering tests by name<span><a class="mark" href="#all_test_filtering-tests-by-name" id="all_test_filtering-tests-by-name">#</a></span><a aria-hidden="true" class="legacy" id="test_filtering_tests_by_name"></a></h3>
<p>The <a href="#all_cli_--test-name-pattern"><code>--test-name-pattern</code></a> command-line option can be used to only run tests
whose name matches the provided pattern. Test name patterns are interpreted as
JavaScript regular expressions. The <code>--test-name-pattern</code> option can be
specified multiple times in order to run nested tests. For each test that is
executed, any corresponding test hooks, such as <code>beforeEach()</code>, are also
run.</p>
<p>Given the following test file, starting Node.js with the
<code>--test-name-pattern="test [1-3]"</code> option would cause the test runner to execute
<code>test 1</code>, <code>test 2</code>, and <code>test 3</code>. If <code>test 1</code> did not match the test name
pattern, then its subtests would not execute, despite matching the pattern. The
same set of tests could also be executed by passing <code>--test-name-pattern</code>
multiple times (e.g. <code>--test-name-pattern="test 1"</code>,
<code>--test-name-pattern="test 2"</code>, etc.).</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'test 1'</span>, <span class="hljs-title function_">async</span> (t) => {
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'test 2'</span>);
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'test 3'</span>);
});
<span class="hljs-title function_">test</span>(<span class="hljs-string">'Test 4'</span>, <span class="hljs-title function_">async</span> (t) => {
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'Test 5'</span>);
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'test 6'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Test name patterns can also be specified using regular expression literals. This
allows regular expression flags to be used. In the previous example, starting
Node.js with <code>--test-name-pattern="/test [4-5]/i"</code> would match <code>Test 4</code> and
<code>Test 5</code> because the pattern is case-insensitive.</p>
<p>Test name patterns do not change the set of files that the test runner executes.</p>
</section><section><h3>Extraneous asynchronous activity<span><a class="mark" href="#all_test_extraneous-asynchronous-activity" id="all_test_extraneous-asynchronous-activity">#</a></span><a aria-hidden="true" class="legacy" id="test_extraneous_asynchronous_activity"></a></h3>
<p>Once a test function finishes executing, the results are reported as quickly
as possible while maintaining the order of the tests. However, it is possible
for the test function to generate asynchronous activity that outlives the test
itself. The test runner handles this type of activity, but does not delay the
reporting of test results in order to accommodate it.</p>
<p>In the following example, a test completes with two <code>setImmediate()</code>
operations still outstanding. The first <code>setImmediate()</code> attempts to create a
new subtest. Because the parent test has already finished and output its
results, the new subtest is immediately marked as failed, and reported later
to the <a href="#all_test_class-testsstream" class="type"><TestsStream></a>.</p>
<p>The second <code>setImmediate()</code> creates an <code>uncaughtException</code> event.
<code>uncaughtException</code> and <code>unhandledRejection</code> events originating from a completed
test are marked as failed by the <code>test</code> module and reported as diagnostic
warnings at the top level by the <a href="#all_test_class-testsstream" class="type"><TestsStream></a>.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'a test that creates asynchronous activity'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'subtest that is created too late'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'error1'</span>);
});
});
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'error2'</span>);
});
<span class="hljs-comment">// The test finishes after this line.</span>
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Watch mode<span><a class="mark" href="#all_test_watch-mode" id="all_test_watch-mode">#</a></span><a aria-hidden="true" class="legacy" id="test_watch_mode"></a></h3>
<div class="api_metadata">
<span>Added in: v19.2.0, v18.13.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>The Node.js test runner supports running in watch mode by passing the <code>--watch</code> flag:</p>
<pre><code class="language-bash">node --<span class="hljs-built_in">test</span> --watch</code> <button class="copy-button">copy</button></pre>
<p>In watch mode, the test runner will watch for changes to test files and
their dependencies. When a change is detected, the test runner will
rerun the tests affected by the change.
The test runner will continue to run until the process is terminated.</p>
</section><section><h3>Running tests from the command line<span><a class="mark" href="#all_test_running-tests-from-the-command-line" id="all_test_running-tests-from-the-command-line">#</a></span><a aria-hidden="true" class="legacy" id="test_running_tests_from_the_command_line"></a></h3>
<p>The Node.js test runner can be invoked from the command line by passing the
<a href="#all_cli_--test"><code>--test</code></a> flag:</p>
<pre><code class="language-bash">node --<span class="hljs-built_in">test</span></code> <button class="copy-button">copy</button></pre>
<p>By default, Node.js will recursively search the current directory for
JavaScript source files matching a specific naming convention. Matching files
are executed as test files. More information on the expected test file naming
convention and behavior can be found in the <a href="#all_test_test-runner-execution-model">test runner execution model</a>
section.</p>
<p>Alternatively, one or more paths can be provided as the final argument(s) to
the Node.js command, as shown below.</p>
<pre><code class="language-bash">node --<span class="hljs-built_in">test</span> test1.js test2.mjs custom_test_dir/</code> <button class="copy-button">copy</button></pre>
<p>In this example, the test runner will execute the files <code>test1.js</code> and
<code>test2.mjs</code>. The test runner will also recursively search the
<code>custom_test_dir/</code> directory for test files to execute.</p>
<h4>Test runner execution model<span><a class="mark" href="#all_test_test-runner-execution-model" id="all_test_test-runner-execution-model">#</a></span><a aria-hidden="true" class="legacy" id="test_test_runner_execution_model"></a></h4>
<p>When searching for test files to execute, the test runner behaves as follows:</p>
<ul>
<li>Any files explicitly provided by the user are executed.</li>
<li>If the user did not explicitly specify any paths, the current working
directory is recursively searched for files as specified in the following
steps.</li>
<li><code>node_modules</code> directories are skipped unless explicitly provided by the
user.</li>
<li>If a directory named <code>test</code> is encountered, the test runner will search it
recursively for all all <code>.js</code>, <code>.cjs</code>, and <code>.mjs</code> files. All of these files
are treated as test files, and do not need to match the specific naming
convention detailed below. This is to accommodate projects that place all of
their tests in a single <code>test</code> directory.</li>
<li>In all other directories, <code>.js</code>, <code>.cjs</code>, and <code>.mjs</code> files matching the
following patterns are treated as test files:
<ul>
<li><code>^test$</code> - Files whose basename is the string <code>'test'</code>. Examples:
<code>test.js</code>, <code>test.cjs</code>, <code>test.mjs</code>.</li>
<li><code>^test-.+</code> - Files whose basename starts with the string <code>'test-'</code>
followed by one or more characters. Examples: <code>test-example.js</code>,
<code>test-another-example.mjs</code>.</li>
<li><code>.+[\.\-\_]test$</code> - Files whose basename ends with <code>.test</code>, <code>-test</code>, or
<code>_test</code>, preceded by one or more characters. Examples: <code>example.test.js</code>,
<code>example-test.cjs</code>, <code>example_test.mjs</code>.</li>
<li>Other file types understood by Node.js such as <code>.node</code> and <code>.json</code> are not
automatically executed by the test runner, but are supported if explicitly
provided on the command line.</li>
</ul>
</li>
</ul>
<p>Each matching test file is executed in a separate child process. The maximum
number of child processes running at any time is controlled by the
<a href="#all_cli_--test-concurrency"><code>--test-concurrency</code></a> flag. If the child process finishes with an exit code
of 0, the test is considered passing. Otherwise, the test is considered to be a
failure. Test files must be executable by Node.js, but are not required to use
the <code>node:test</code> module internally.</p>
<p>Each test file is executed as if it was a regular script. That is, if the test
file itself uses <code>node:test</code> to define tests, all of those tests will be
executed within a single application thread, regardless of the value of the
<code>concurrency</code> option of <a href="#all_test_testname-options-fn"><code>test()</code></a>.</p>
</section><section><h3>Collecting code coverage<span><a class="mark" href="#all_test_collecting-code-coverage" id="all_test_collecting-code-coverage">#</a></span><a aria-hidden="true" class="legacy" id="test_collecting_code_coverage"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>When Node.js is started with the <a href="#all_cli_--experimental-test-coverage"><code>--experimental-test-coverage</code></a>
command-line flag, code coverage is collected and statistics are reported once
all tests have completed. If the <a href="#all_cli_node_v8_coveragedir"><code>NODE_V8_COVERAGE</code></a> environment variable is
used to specify a code coverage directory, the generated V8 coverage files are
written to that directory. Node.js core modules and files within
<code>node_modules/</code> directories are, by default, not included in the coverage report.
However, they can be explicity included via the <a href="#all_cli_--test-coverage-include"><code>--test-coverage-include</code></a> flag. If
coverage is enabled, the coverage report is sent to any <a href="#all_test_test-reporters">test reporters</a> via
the <code>'test:coverage'</code> event.</p>
<p>Coverage can be disabled on a series of lines using the following
comment syntax:</p>
<pre><code class="language-js"><span class="hljs-comment">/* node:coverage disable */</span>
<span class="hljs-keyword">if</span> (anAlwaysFalseCondition) {
<span class="hljs-comment">// Code in this branch will never be executed, but the lines are ignored for</span>
<span class="hljs-comment">// coverage purposes. All lines following the 'disable' comment are ignored</span>
<span class="hljs-comment">// until a corresponding 'enable' comment is encountered.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'this is never executed'</span>);
}
<span class="hljs-comment">/* node:coverage enable */</span></code> <button class="copy-button">copy</button></pre>
<p>Coverage can also be disabled for a specified number of lines. After the
specified number of lines, coverage will be automatically reenabled. If the
number of lines is not explicitly provided, a single line is ignored.</p>
<pre><code class="language-js"><span class="hljs-comment">/* node:coverage ignore next */</span>
<span class="hljs-keyword">if</span> (anAlwaysFalseCondition) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'this is never executed'</span>); }
<span class="hljs-comment">/* node:coverage ignore next 3 */</span>
<span class="hljs-keyword">if</span> (anAlwaysFalseCondition) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'this is never executed'</span>);
}</code> <button class="copy-button">copy</button></pre>
<h4>Coverage reporters<span><a class="mark" href="#all_test_coverage-reporters" id="all_test_coverage-reporters">#</a></span><a aria-hidden="true" class="legacy" id="test_coverage_reporters"></a></h4>
<p>The tap and spec reporters will print a summary of the coverage statistics.
There is also an lcov reporter that will generate an lcov file which can be
used as an in depth coverage report.</p>
<pre><code class="language-bash">node --<span class="hljs-built_in">test</span> --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info</code> <button class="copy-button">copy</button></pre>
<ul>
<li>No test results are reported by this reporter.</li>
<li>This reporter should ideally be used alongside another reporter.</li>
</ul>
<h4>Limitations<span><a class="mark" href="#all_test_limitations" id="all_test_limitations">#</a></span><a aria-hidden="true" class="legacy" id="test_limitations"></a></h4>
<p>The test runner's code coverage functionality does not support excluding
specific files or directories from the coverage report.</p>
</section><section><h3>Mocking<span><a class="mark" href="#all_test_mocking" id="all_test_mocking">#</a></span><a aria-hidden="true" class="legacy" id="test_mocking"></a></h3>
<p>The <code>node:test</code> module supports mocking during testing via a top-level <code>mock</code>
object. The following example creates a spy on a function that adds two numbers
together. The spy is then used to assert that the function was called as
expected.</p>
<pre class="with-39-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { mock, test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'spies on a function'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> sum = mock.<span class="hljs-title function_">fn</span>(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> {
<span class="hljs-keyword">return</span> a + b;
});
assert.<span class="hljs-title function_">strictEqual</span>(sum.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">sum</span>(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>), <span class="hljs-number">7</span>);
assert.<span class="hljs-title function_">strictEqual</span>(sum.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
<span class="hljs-keyword">const</span> call = sum.<span class="hljs-property">mock</span>.<span class="hljs-property">calls</span>[<span class="hljs-number">0</span>];
assert.<span class="hljs-title function_">deepStrictEqual</span>(call.<span class="hljs-property">arguments</span>, [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);
assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">result</span>, <span class="hljs-number">7</span>);
assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">error</span>, <span class="hljs-literal">undefined</span>);
<span class="hljs-comment">// Reset the globally tracked mocks.</span>
mock.<span class="hljs-title function_">reset</span>();
});</code><code class="language-js cjs"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { mock, test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'spies on a function'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> sum = mock.<span class="hljs-title function_">fn</span>(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> {
<span class="hljs-keyword">return</span> a + b;
});
assert.<span class="hljs-title function_">strictEqual</span>(sum.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">sum</span>(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>), <span class="hljs-number">7</span>);
assert.<span class="hljs-title function_">strictEqual</span>(sum.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
<span class="hljs-keyword">const</span> call = sum.<span class="hljs-property">mock</span>.<span class="hljs-property">calls</span>[<span class="hljs-number">0</span>];
assert.<span class="hljs-title function_">deepStrictEqual</span>(call.<span class="hljs-property">arguments</span>, [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);
assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">result</span>, <span class="hljs-number">7</span>);
assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">error</span>, <span class="hljs-literal">undefined</span>);
<span class="hljs-comment">// Reset the globally tracked mocks.</span>
mock.<span class="hljs-title function_">reset</span>();
});</code><button class="copy-button">copy</button></pre>
<p>The same mocking functionality is also exposed on the <a href="#all_test_class-testcontext"><code>TestContext</code></a> object
of each test. The following example creates a spy on an object method using the
API exposed on the <code>TestContext</code>. The benefit of mocking via the test context is
that the test runner will automatically restore all mocked functionality once
the test finishes.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'spies on an object method'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-keyword">const</span> number = {
<span class="hljs-attr">value</span>: <span class="hljs-number">5</span>,
<span class="hljs-title function_">add</span>(<span class="hljs-params">a</span>) {
<span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> + a;
},
};
t.<span class="hljs-property">mock</span>.<span class="hljs-title function_">method</span>(number, <span class="hljs-string">'add'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(number.<span class="hljs-property">add</span>.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
assert.<span class="hljs-title function_">strictEqual</span>(number.<span class="hljs-title function_">add</span>(<span class="hljs-number">3</span>), <span class="hljs-number">8</span>);
assert.<span class="hljs-title function_">strictEqual</span>(number.<span class="hljs-property">add</span>.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
<span class="hljs-keyword">const</span> call = number.<span class="hljs-property">add</span>.<span class="hljs-property">mock</span>.<span class="hljs-property">calls</span>[<span class="hljs-number">0</span>];
assert.<span class="hljs-title function_">deepStrictEqual</span>(call.<span class="hljs-property">arguments</span>, [<span class="hljs-number">3</span>]);
assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">result</span>, <span class="hljs-number">8</span>);
assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">target</span>, <span class="hljs-literal">undefined</span>);
assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">this</span>, number);
});</code> <button class="copy-button">copy</button></pre>
<h4>Timers<span><a class="mark" href="#all_test_timers" id="all_test_timers">#</a></span><a aria-hidden="true" class="legacy" id="test_timers"></a></h4>
<p>Mocking timers is a technique commonly used in software testing to simulate and
control the behavior of timers, such as <code>setInterval</code> and <code>setTimeout</code>,
without actually waiting for the specified time intervals.</p>
<p>Refer to the <a href="#all_test_class-mocktimers"><code>MockTimers</code></a> class for a full list of methods and features.</p>
<p>This allows developers to write more reliable and
predictable tests for time-dependent functionality.</p>
<p>The example below shows how to mock <code>setTimeout</code>.
Using <code>.enable({ apis: ['setTimeout'] });</code>
it will mock the <code>setTimeout</code> functions in the <a href="./timers.html">node:timers</a> and
<a href="./timers.html#timers-promises-api">node:timers/promises</a> modules,
as well as from the Node.js global context.</p>
<p><strong>Note:</strong> Destructuring functions such as
<code>import { setTimeout } from 'node:timers'</code>
is currently not supported by this API.</p>
<pre class="with-44-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { mock, test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> fn = mock.<span class="hljs-title function_">fn</span>();
<span class="hljs-comment">// Optionally choose what to mock</span>
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
<span class="hljs-comment">// Advance in time</span>
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
<span class="hljs-comment">// Reset the globally tracked mocks.</span>
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">reset</span>();
<span class="hljs-comment">// If you call reset mock instance, it will also reset timers instance</span>
mock.<span class="hljs-title function_">reset</span>();
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { mock, test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> fn = mock.<span class="hljs-title function_">fn</span>();
<span class="hljs-comment">// Optionally choose what to mock</span>
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
<span class="hljs-comment">// Advance in time</span>
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
<span class="hljs-comment">// Reset the globally tracked mocks.</span>
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">reset</span>();
<span class="hljs-comment">// If you call reset mock instance, it will also reset timers instance</span>
mock.<span class="hljs-title function_">reset</span>();
});</code><button class="copy-button">copy</button></pre>
<p>The same mocking functionality is also exposed in the mock property on the <a href="#all_test_class-testcontext"><code>TestContext</code></a> object
of each test. The benefit of mocking via the test context is
that the test runner will automatically restore all mocked timers
functionality once the test finishes.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
<span class="hljs-comment">// Advance in time</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
<span class="hljs-comment">// Advance in time</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><button class="copy-button">copy</button></pre>
<h4>Dates<span><a class="mark" href="#all_test_dates" id="all_test_dates">#</a></span><a aria-hidden="true" class="legacy" id="test_dates"></a></h4>
<p>The mock timers API also allows the mocking of the <code>Date</code> object. This is a
useful feature for testing time-dependent functionality, or to simulate
internal calendar functions such as <code>Date.now()</code>.</p>
<p>The dates implementation is also part of the <a href="#all_test_class-mocktimers"><code>MockTimers</code></a> class. Refer to it
for a full list of methods and features.</p>
<p><strong>Note:</strong> Dates and timers are dependent when mocked together. This means that
if you have both the <code>Date</code> and <code>setTimeout</code> mocked, advancing the time will
also advance the mocked date as they simulate a single internal clock.</p>
<p>The example below show how to mock the <code>Date</code> object and obtain the current
<code>Date.now()</code> value.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks the Date object'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>] });
<span class="hljs-comment">// If not specified, the initial date will be based on 0 in the UNIX epoch</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">0</span>);
<span class="hljs-comment">// Advance in time will also advance the date</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">9999</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks the Date object'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>] });
<span class="hljs-comment">// If not specified, the initial date will be based on 0 in the UNIX epoch</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">0</span>);
<span class="hljs-comment">// Advance in time will also advance the date</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">9999</span>);
});</code><button class="copy-button">copy</button></pre>
<p>If there is no initial epoch set, the initial date will be based on 0 in the
Unix epoch. This is January 1st, 1970, 00:00:00 UTC. You can set an initial date
by passing a <code>now</code> property to the <code>.enable()</code> method. This value will be used
as the initial date for the mocked <code>Date</code> object. It can either be a positive
integer, or another Date object.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks the Date object with initial time'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-number">100</span> });
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">100</span>);
<span class="hljs-comment">// Advance in time will also advance the date</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">200</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">300</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks the Date object with initial time'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-number">100</span> });
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">100</span>);
<span class="hljs-comment">// Advance in time will also advance the date</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">200</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">300</span>);
});</code><button class="copy-button">copy</button></pre>
<p>You can use the <code>.setTime()</code> method to manually move the mocked date to another
time. This method only accepts a positive integer.</p>
<p><strong>Note:</strong> This method will execute any mocked timers that are in the past
from the new time.</p>
<p>In the below example we are setting a new time for the mocked date.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'sets the time of a date object'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-number">100</span> });
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">100</span>);
<span class="hljs-comment">// Advance in time will also advance the date</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">1000</span>);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">200</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">1200</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'sets the time of a date object'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-number">100</span> });
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">100</span>);
<span class="hljs-comment">// Advance in time will also advance the date</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">1000</span>);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">200</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">1200</span>);
});</code><button class="copy-button">copy</button></pre>
<p>If you have any timer that's set to run in the past, it will be executed as if
the <code>.tick()</code> method has been called. This is useful if you want to test
time-dependent functionality that's already in the past.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'runs timers as setTime passes ticks'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">1000</span>);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">800</span>);
<span class="hljs-comment">// Timer is not executed as the time is not yet reached</span>
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">800</span>);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">1200</span>);
<span class="hljs-comment">// Timer is executed as the time is now reached</span>
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">1200</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'runs timers as setTime passes ticks'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">1000</span>);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">800</span>);
<span class="hljs-comment">// Timer is not executed as the time is not yet reached</span>
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">800</span>);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">1200</span>);
<span class="hljs-comment">// Timer is executed as the time is now reached</span>
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">1200</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Using <code>.runAll()</code> will execute all timers that are currently in the queue. This
will also advance the mocked date to the time of the last timer that was
executed as if the time has passed.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'runs timers as setTime passes ticks'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">1000</span>);
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">2000</span>);
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">3000</span>);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">runAll</span>();
<span class="hljs-comment">// All timers are executed as the time is now reached</span>
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">3</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">3000</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'runs timers as setTime passes ticks'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">1000</span>);
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">2000</span>);
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">3000</span>);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">runAll</span>();
<span class="hljs-comment">// All timers are executed as the time is now reached</span>
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">3</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">3000</span>);
});</code><button class="copy-button">copy</button></pre>
</section><section><h3>Test reporters<span><a class="mark" href="#all_test_test-reporters" id="all_test_test-reporters">#</a></span><a aria-hidden="true" class="legacy" id="test_test_reporters"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.9.0</td>
<td><p>Reporters are now exposed at <code>node:test/reporters</code>.</p></td></tr>
<tr><td>v19.6.0, v18.15.0</td>
<td><p><span>Added in: v19.6.0, v18.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>node:test</code> module supports passing <a href="#all_cli_--test-reporter"><code>--test-reporter</code></a>
flags for the test runner to use a specific reporter.</p>
<p>The following built-reporters are supported:</p>
<ul>
<li>
<p><code>tap</code>
The <code>tap</code> reporter outputs the test results in the <a href="https://testanything.org/">TAP</a> format.</p>
</li>
<li>
<p><code>spec</code>
The <code>spec</code> reporter outputs the test results in a human-readable format.</p>
</li>
<li>
<p><code>dot</code>
The <code>dot</code> reporter outputs the test results in a compact format,
where each passing test is represented by a <code>.</code>,
and each failing test is represented by a <code>X</code>.</p>
</li>
<li>
<p><code>junit</code>
The junit reporter outputs test results in a jUnit XML format</p>
</li>
<li>
<p><code>lcov</code>
The <code>lcov</code> reporter outputs test coverage when used with the
<a href="#all_cli_--experimental-test-coverage"><code>--experimental-test-coverage</code></a> flag.</p>
</li>
</ul>
<p>When <code>stdout</code> is a <a href="tty.html">TTY</a>, the <code>spec</code> reporter is used by default.
Otherwise, the <code>tap</code> reporter is used by default.</p>
<p>The exact output of these reporters is subject to change between versions of
Node.js, and should not be relied on programmatically. If programmatic access
to the test runner's output is required, use the events emitted by the
<a href="#all_test_class-testsstream" class="type"><TestsStream></a>.</p>
<p>The reporters are available via the <code>node:test/reporters</code> module:</p>
<pre class="with-71-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> { tap, spec, dot, junit, lcov } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test/reporters'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { tap, spec, dot, junit, lcov } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test/reporters'</span>);</code><button class="copy-button">copy</button></pre>
<h4>Custom reporters<span><a class="mark" href="#all_test_custom-reporters" id="all_test_custom-reporters">#</a></span><a aria-hidden="true" class="legacy" id="test_custom_reporters"></a></h4>
<p><a href="#all_cli_--test-reporter"><code>--test-reporter</code></a> can be used to specify a path to custom reporter.
A custom reporter is a module that exports a value
accepted by <a href="#all_stream_streamcomposestreams">stream.compose</a>.
Reporters should transform events emitted by a <a href="#all_test_class-testsstream" class="type"><TestsStream></a></p>
<p>Example of a custom reporter using <a href="#all_stream_class-streamtransform" class="type"><stream.Transform></a>:</p>
<pre class="with-45-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_">Transform</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">const</span> customReporter = <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">event, encoding, callback</span>) {
<span class="hljs-keyword">switch</span> (event.<span class="hljs-property">type</span>) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:dequeue'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> dequeued`</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:enqueue'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> enqueued`</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:watch:drained'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'test watch queue drained'</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:start'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> started`</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:pass'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> passed`</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:fail'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> failed`</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:plan'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'test plan'</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:diagnostic'</span>:
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:stderr'</span>:
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:stdout'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, event.<span class="hljs-property">data</span>.<span class="hljs-property">message</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:coverage'</span>: {
<span class="hljs-keyword">const</span> { totalLineCount } = event.<span class="hljs-property">data</span>.<span class="hljs-property">summary</span>.<span class="hljs-property">totals</span>;
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`total line count: <span class="hljs-subst">${totalLineCount}</span>\n`</span>);
<span class="hljs-keyword">break</span>;
}
}
},
});
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> customReporter;</code><code class="language-js cjs"><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> customReporter = <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">event, encoding, callback</span>) {
<span class="hljs-keyword">switch</span> (event.<span class="hljs-property">type</span>) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:dequeue'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> dequeued`</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:enqueue'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> enqueued`</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:watch:drained'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'test watch queue drained'</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:start'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> started`</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:pass'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> passed`</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:fail'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> failed`</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:plan'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'test plan'</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:diagnostic'</span>:
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:stderr'</span>:
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:stdout'</span>:
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, event.<span class="hljs-property">data</span>.<span class="hljs-property">message</span>);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:coverage'</span>: {
<span class="hljs-keyword">const</span> { totalLineCount } = event.<span class="hljs-property">data</span>.<span class="hljs-property">summary</span>.<span class="hljs-property">totals</span>;
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`total line count: <span class="hljs-subst">${totalLineCount}</span>\n`</span>);
<span class="hljs-keyword">break</span>;
}
}
},
});
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = customReporter;</code><button class="copy-button">copy</button></pre>
<p>Example of a custom reporter using a generator function:</p>
<pre class="with-58-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">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">customReporter</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> event <span class="hljs-keyword">of</span> source) {
<span class="hljs-keyword">switch</span> (event.<span class="hljs-property">type</span>) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:dequeue'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> dequeued\n`</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:enqueue'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> enqueued\n`</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:watch:drained'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">'test watch queue drained\n'</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:start'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> started\n`</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:pass'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> passed\n`</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:fail'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> failed\n`</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:plan'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">'test plan\n'</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:diagnostic'</span>:
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:stderr'</span>:
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:stdout'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">`<span class="hljs-subst">${event.data.message}</span>\n`</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:coverage'</span>: {
<span class="hljs-keyword">const</span> { totalLineCount } = event.<span class="hljs-property">data</span>.<span class="hljs-property">summary</span>.<span class="hljs-property">totals</span>;
<span class="hljs-keyword">yield</span> <span class="hljs-string">`total line count: <span class="hljs-subst">${totalLineCount}</span>\n`</span>;
<span class="hljs-keyword">break</span>;
}
}
}
}</code><code class="language-js cjs"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">customReporter</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> event <span class="hljs-keyword">of</span> source) {
<span class="hljs-keyword">switch</span> (event.<span class="hljs-property">type</span>) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:dequeue'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> dequeued\n`</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:enqueue'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> enqueued\n`</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:watch:drained'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">'test watch queue drained\n'</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:start'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> started\n`</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:pass'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> passed\n`</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:fail'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> failed\n`</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:plan'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">'test plan\n'</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:diagnostic'</span>:
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:stderr'</span>:
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:stdout'</span>:
<span class="hljs-keyword">yield</span> <span class="hljs-string">`<span class="hljs-subst">${event.data.message}</span>\n`</span>;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'test:coverage'</span>: {
<span class="hljs-keyword">const</span> { totalLineCount } = event.<span class="hljs-property">data</span>.<span class="hljs-property">summary</span>.<span class="hljs-property">totals</span>;
<span class="hljs-keyword">yield</span> <span class="hljs-string">`total line count: <span class="hljs-subst">${totalLineCount}</span>\n`</span>;
<span class="hljs-keyword">break</span>;
}
}
}
};</code><button class="copy-button">copy</button></pre>
<p>The value provided to <code>--test-reporter</code> should be a string like one used in an
<code>import()</code> in JavaScript code, or a value provided for <a href="#all_cli_--importmodule"><code>--import</code></a>.</p>
<h4>Multiple reporters<span><a class="mark" href="#all_test_multiple-reporters" id="all_test_multiple-reporters">#</a></span><a aria-hidden="true" class="legacy" id="test_multiple_reporters"></a></h4>
<p>The <a href="#all_cli_--test-reporter"><code>--test-reporter</code></a> flag can be specified multiple times to report test
results in several formats. In this situation
it is required to specify a destination for each reporter
using <a href="#all_cli_--test-reporter-destination"><code>--test-reporter-destination</code></a>.
Destination can be <code>stdout</code>, <code>stderr</code>, or a file path.
Reporters and destinations are paired according
to the order they were specified.</p>
<p>In the following example, the <code>spec</code> reporter will output to <code>stdout</code>,
and the <code>dot</code> reporter will output to <code>file.txt</code>:</p>
<pre><code class="language-bash">node --test-reporter=spec --test-reporter=dot --test-reporter-destination=stdout --test-reporter-destination=file.txt</code> <button class="copy-button">copy</button></pre>
<p>When a single reporter is specified, the destination will default to <code>stdout</code>,
unless a destination is explicitly provided.</p>
</section><section><h3><code>run([options])</code><span><a class="mark" href="#all_test_runoptions" id="all_test_runoptions">#</a></span><a aria-hidden="true" class="legacy" id="test_run_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.14.0</td>
<td><p>Added the <code>forceExit</code> option.</p></td></tr>
<tr><td>v20.1.0, v18.17.0</td>
<td><p>Add a testNamePatterns option.</p></td></tr>
<tr><td>v18.9.0, v16.19.0</td>
<td><p><span>Added in: v18.9.0, v16.19.0</span></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> Configuration options for running tests. The following
properties are supported:
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If a number is provided,
then that many test processes would run in parallel, where each process
corresponds to one test file.
If <code>true</code>, it would run <code>os.availableParallelism() - 1</code> test files in
parallel.
If <code>false</code>, it would only run one test file at a time.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>files</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array containing the list of files to run.
<strong>Default:</strong> matching files from <a href="#all_test_test-runner-execution-model">test runner execution model</a>.</li>
<li><code>forceExit</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Configures the test runner to exit the process once
all known tests have finished executing even if the event loop would
otherwise remain active. <strong>Default:</strong> <code>false</code>.</li>
<li><code>inspectPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Sets inspector port of test child process.
This can be a number, or a function that takes no arguments and returns a
number. If a nullish value is provided, each process gets its own port,
incremented from the primary's <code>process.debugPort</code>.
<strong>Default:</strong> <code>undefined</code>.</li>
<li><code>only</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If truthy, the test context will only run tests that
have the <code>only</code> option set</li>
<li><code>setup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A function that accepts the <code>TestsStream</code> instance
and can be used to setup listeners before any tests are run.
<strong>Default:</strong> <code>undefined</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress test execution.</li>
<li><code>testNamePatterns</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/Reference/Global_Objects/RegExp" class="type"><RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> A String, RegExp or a RegExp Array,
that can be used to only run tests whose name matches the provided pattern.
Test name patterns are interpreted as JavaScript regular expressions.
For each test that is executed, any corresponding test hooks, such as
<code>beforeEach()</code>, are also run.
<strong>Default:</strong> <code>undefined</code>.</li>
<li><code>testSkipPatterns</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/Reference/Global_Objects/RegExp" class="type"><RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> A String, RegExp or a RegExp Array,
that can be used to exclude running tests whose name matches the provided pattern.
Test name patterns are interpreted as JavaScript regular expressions.
For each test that is executed, any corresponding test hooks, such as
<code>beforeEach()</code>, are also run.
<strong>Default:</strong> <code>undefined</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the test execution will
fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
<li><code>watch</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether to run in watch mode or not. <strong>Default:</strong> <code>false</code>.</li>
<li><code>shard</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Running tests in a specific shard. <strong>Default:</strong> <code>undefined</code>.
<ul>
<li><code>index</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> is a positive integer between 1 and <code><total></code>
that specifies the index of the shard to run. This option is <em>required</em>.</li>
<li><code>total</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> is a positive integer that specifies the total number
of shards to split the test files to. This option is <em>required</em>.</li>
</ul>
</li>
</ul>
</li>
<li>Returns: <a href="#all_test_class-testsstream" class="type"><TestsStream></a></li>
</ul>
<p><strong>Note:</strong> <code>shard</code> is used to horizontally parallelize test running across
machines or processes, ideal for large-scale executions across varied
environments. It's incompatible with <code>watch</code> mode, tailored for rapid
code iteration by automatically rerunning tests on file changes.</p>
<pre class="with-47-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> { tap } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test/reporters'</span>;
<span class="hljs-keyword">import</span> { run } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-title function_">run</span>({ <span class="hljs-attr">files</span>: [path.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'./tests/test.js'</span>)] })
.<span class="hljs-title function_">on</span>(<span class="hljs-string">'test:fail'</span>, <span class="hljs-function">() =></span> {
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
})
.<span class="hljs-title function_">compose</span>(tap)
.<span class="hljs-title function_">pipe</span>(process.<span class="hljs-property">stdout</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { tap } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test/reporters'</span>);
<span class="hljs-keyword">const</span> { run } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-title function_">run</span>({ <span class="hljs-attr">files</span>: [path.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'./tests/test.js'</span>)] })
.<span class="hljs-title function_">on</span>(<span class="hljs-string">'test:fail'</span>, <span class="hljs-function">() =></span> {
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
})
.<span class="hljs-title function_">compose</span>(tap)
.<span class="hljs-title function_">pipe</span>(process.<span class="hljs-property">stdout</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>suite([name][, options][, fn])</code><span><a class="mark" href="#all_test_suitename-options-fn" id="all_test_suitename-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_suite_name_options_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the suite, which is displayed when reporting test
results. <strong>Default:</strong> The <code>name</code> property of <code>fn</code>, or <code>'<anonymous>'</code> if <code>fn</code>
does not have a name.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Optional configuration options for the suite.
This supports the same options as <code>test([name][, options][, fn])</code>.</li>
<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> The suite function declaring nested tests and
suites. The first argument to this function is a <a href="#all_test_class-suitecontext"><code>SuiteContext</code></a> object.
<strong>Default:</strong> A no-op function.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Immediately fulfilled with <code>undefined</code>.</li>
</ul>
<p>The <code>suite()</code> function is imported from the <code>node:test</code> module.</p>
</section><section><h3><code>suite.skip([name][, options][, fn])</code><span><a class="mark" href="#all_test_suiteskipname-options-fn" id="all_test_suiteskipname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_suite_skip_name_options_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p>Shorthand for skipping a suite. This is the same as
<a href="#all_test_suitename-options-fn"><code>suite([name], { skip: true }[, fn])</code></a>.</p>
</section><section><h3><code>suite.todo([name][, options][, fn])</code><span><a class="mark" href="#all_test_suitetodoname-options-fn" id="all_test_suitetodoname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_suite_todo_name_options_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p>Shorthand for marking a suite as <code>TODO</code>. This is the same as
<a href="#all_test_suitename-options-fn"><code>suite([name], { todo: true }[, fn])</code></a>.</p>
</section><section><h3><code>suite.only([name][, options][, fn])</code><span><a class="mark" href="#all_test_suiteonlyname-options-fn" id="all_test_suiteonlyname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_suite_only_name_options_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p>Shorthand for marking a suite as <code>only</code>. This is the same as
<a href="#all_test_suitename-options-fn"><code>suite([name], { only: true }[, fn])</code></a>.</p>
</section><section><h3><code>test([name][, options][, fn])</code><span><a class="mark" href="#all_test_testname-options-fn" id="all_test_testname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_test_name_options_fn"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.2.0</td>
<td><p>Added the <code>skip</code>, <code>todo</code>, and <code>only</code> shorthands.</p></td></tr>
<tr><td>v18.8.0, v16.18.0</td>
<td><p>Add a <code>signal</code> option.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p>Add a <code>timeout</code> option.</p></td></tr>
<tr><td>v18.0.0, v16.17.0</td>
<td><p><span>Added in: v18.0.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the test, which is displayed when reporting test
results. <strong>Default:</strong> The <code>name</code> property of <code>fn</code>, or <code>'<anonymous>'</code> if <code>fn</code>
does not have a name.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the test. The following
properties are supported:
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If a number is provided,
then that many tests would run in parallel within the application thread.
If <code>true</code>, all scheduled asynchronous tests run concurrently within the
thread. If <code>false</code>, only one test runs at a time.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>only</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If truthy, and the test context is configured to run
<code>only</code> tests, then this test will be run. Otherwise, the test is skipped.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress test.</li>
<li><code>skip</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#String_type" class="type"><string></a> If truthy, the test is skipped. If a string is
provided, that string is displayed in the test results as the reason for
skipping the test. <strong>Default:</strong> <code>false</code>.</li>
<li><code>todo</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#String_type" class="type"><string></a> If truthy, the test marked as <code>TODO</code>. If a string
is provided, that string is displayed in the test results as the reason why
the test is <code>TODO</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the test will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
<li><code>plan</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of assertions and subtests expected to be run in the test.
If the number of assertions run in the test does not match the number
specified in the plan, the test will fail.
<strong>Default:</strong> <code>undefined</code>.</li>
</ul>
</li>
<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> The function under test. The first argument
to this function is a <a href="#all_test_class-testcontext"><code>TestContext</code></a> object. If the test uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfilled with <code>undefined</code> once
the test completes, or immediately if the test runs within a suite.</li>
</ul>
<p>The <code>test()</code> function is the value imported from the <code>test</code> module. Each
invocation of this function results in reporting the test to the <a href="#all_test_class-testsstream" class="type"><TestsStream></a>.</p>
<p>The <code>TestContext</code> object passed to the <code>fn</code> argument can be used to perform
actions related to the current test. Examples include skipping the test, adding
additional diagnostic information, or creating subtests.</p>
<p><code>test()</code> returns a <code>Promise</code> that fulfills once the test completes.
if <code>test()</code> is called within a suite, it fulfills immediately.
The return value can usually be discarded for top level tests.
However, the return value from subtests should be used to prevent the parent
test from finishing first and cancelling the subtest
as shown in the following example.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-title function_">async</span> (t) => {
<span class="hljs-comment">// The setTimeout() in the following subtest would cause it to outlive its</span>
<span class="hljs-comment">// parent test if 'await' is removed on the next line. Once the parent test</span>
<span class="hljs-comment">// completes, it will cancel any outstanding subtests.</span>
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'longer running subtest'</span>, <span class="hljs-title function_">async</span> (t) => {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
<span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">1000</span>);
});
});
});</code> <button class="copy-button">copy</button></pre>
<p>The <code>timeout</code> option can be used to fail the test if it takes longer than
<code>timeout</code> milliseconds to complete. However, it is not a reliable mechanism for
canceling tests because a running test might block the application thread and
thus prevent the scheduled cancellation.</p>
</section><section><h3><code>test.skip([name][, options][, fn])</code><span><a class="mark" href="#all_test_testskipname-options-fn" id="all_test_testskipname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_test_skip_name_options_fn"></a></h3>
<p>Shorthand for skipping a test,
same as <a href="#all_test_testname-options-fn"><code>test([name], { skip: true }[, fn])</code></a>.</p>
</section><section><h3><code>test.todo([name][, options][, fn])</code><span><a class="mark" href="#all_test_testtodoname-options-fn" id="all_test_testtodoname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_test_todo_name_options_fn"></a></h3>
<p>Shorthand for marking a test as <code>TODO</code>,
same as <a href="#all_test_testname-options-fn"><code>test([name], { todo: true }[, fn])</code></a>.</p>
</section><section><h3><code>test.only([name][, options][, fn])</code><span><a class="mark" href="#all_test_testonlyname-options-fn" id="all_test_testonlyname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_test_only_name_options_fn"></a></h3>
<p>Shorthand for marking a test as <code>only</code>,
same as <a href="#all_test_testname-options-fn"><code>test([name], { only: true }[, fn])</code></a>.</p>
</section><section><h3><code>describe([name][, options][, fn])</code><span><a class="mark" href="#all_test_describename-options-fn" id="all_test_describename-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_name_options_fn"></a></h3>
<p>Alias for <a href="#all_test_suitename-options-fn"><code>suite()</code></a>.</p>
<p>The <code>describe()</code> function is imported from the <code>node:test</code> module.</p>
</section><section><h3><code>describe.skip([name][, options][, fn])</code><span><a class="mark" href="#all_test_describeskipname-options-fn" id="all_test_describeskipname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_skip_name_options_fn"></a></h3>
<p>Shorthand for skipping a suite. This is the same as
<a href="#all_test_describename-options-fn"><code>describe([name], { skip: true }[, fn])</code></a>.</p>
</section><section><h3><code>describe.todo([name][, options][, fn])</code><span><a class="mark" href="#all_test_describetodoname-options-fn" id="all_test_describetodoname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_todo_name_options_fn"></a></h3>
<p>Shorthand for marking a suite as <code>TODO</code>. This is the same as
<a href="#all_test_describename-options-fn"><code>describe([name], { todo: true }[, fn])</code></a>.</p>
</section><section><h3><code>describe.only([name][, options][, fn])</code><span><a class="mark" href="#all_test_describeonlyname-options-fn" id="all_test_describeonlyname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_only_name_options_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v19.8.0, v18.15.0</span>
</div>
<p>Shorthand for marking a suite as <code>only</code>. This is the same as
<a href="#all_test_describename-options-fn"><code>describe([name], { only: true }[, fn])</code></a>.</p>
</section><section><h3><code>it([name][, options][, fn])</code><span><a class="mark" href="#all_test_itname-options-fn" id="all_test_itname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_it_name_options_fn"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.8.0</td>
<td><p>Calling <code>it()</code> is now equivalent to calling <code>test()</code>.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p><span>Added in: v18.6.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Alias for <a href="#all_test_testname-options-fn"><code>test()</code></a>.</p>
<p>The <code>it()</code> function is imported from the <code>node:test</code> module.</p>
</section><section><h3><code>it.skip([name][, options][, fn])</code><span><a class="mark" href="#all_test_itskipname-options-fn" id="all_test_itskipname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_it_skip_name_options_fn"></a></h3>
<p>Shorthand for skipping a test,
same as <a href="#all_test_testname-options-fn"><code>it([name], { skip: true }[, fn])</code></a>.</p>
</section><section><h3><code>it.todo([name][, options][, fn])</code><span><a class="mark" href="#all_test_ittodoname-options-fn" id="all_test_ittodoname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_it_todo_name_options_fn"></a></h3>
<p>Shorthand for marking a test as <code>TODO</code>,
same as <a href="#all_test_testname-options-fn"><code>it([name], { todo: true }[, fn])</code></a>.</p>
</section><section><h3><code>it.only([name][, options][, fn])</code><span><a class="mark" href="#all_test_itonlyname-options-fn" id="all_test_itonlyname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_it_only_name_options_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v19.8.0, v18.15.0</span>
</div>
<p>Shorthand for marking a test as <code>only</code>,
same as <a href="#all_test_testname-options-fn"><code>it([name], { only: true }[, fn])</code></a>.</p>
</section><section><h3><code>before([fn][, options])</code><span><a class="mark" href="#all_test_beforefn-options" id="all_test_beforefn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_before_fn_options"></a></h3>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<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> The hook function.
If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function creates a hook that runs before executing a suite.</p>
<pre><code class="language-js"><span class="hljs-title function_">describe</span>(<span class="hljs-string">'tests'</span>, <span class="hljs-title function_">async</span> () => {
<span class="hljs-title function_">before</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'about to run some test'</span>));
<span class="hljs-title function_">it</span>(<span class="hljs-string">'is a subtest'</span>, <span class="hljs-function">() =></span> {
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
});
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>after([fn][, options])</code><span><a class="mark" href="#all_test_afterfn-options" id="all_test_afterfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_after_fn_options"></a></h3>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<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> The hook function.
If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function creates a hook that runs after executing a suite.</p>
<pre><code class="language-js"><span class="hljs-title function_">describe</span>(<span class="hljs-string">'tests'</span>, <span class="hljs-title function_">async</span> () => {
<span class="hljs-title function_">after</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'finished running tests'</span>));
<span class="hljs-title function_">it</span>(<span class="hljs-string">'is a subtest'</span>, <span class="hljs-function">() =></span> {
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
});
});</code> <button class="copy-button">copy</button></pre>
<p><strong>Note:</strong> The <code>after</code> hook is guaranteed to run,
even if tests within the suite fail.</p>
</section><section><h3><code>beforeEach([fn][, options])</code><span><a class="mark" href="#all_test_beforeeachfn-options" id="all_test_beforeeachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_beforeeach_fn_options"></a></h3>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<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> The hook function.
If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function creates a hook that runs before each test in the current suite.</p>
<pre><code class="language-js"><span class="hljs-title function_">describe</span>(<span class="hljs-string">'tests'</span>, <span class="hljs-title function_">async</span> () => {
<span class="hljs-title function_">beforeEach</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'about to run a test'</span>));
<span class="hljs-title function_">it</span>(<span class="hljs-string">'is a subtest'</span>, <span class="hljs-function">() =></span> {
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
});
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>afterEach([fn][, options])</code><span><a class="mark" href="#all_test_aftereachfn-options" id="all_test_aftereachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_aftereach_fn_options"></a></h3>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<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> The hook function.
If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function creates a hook that runs after each test in the current suite.
The <code>afterEach()</code> hook is run even if the test fails.</p>
<pre><code class="language-js"><span class="hljs-title function_">describe</span>(<span class="hljs-string">'tests'</span>, <span class="hljs-title function_">async</span> () => {
<span class="hljs-title function_">afterEach</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'finished running a test'</span>));
<span class="hljs-title function_">it</span>(<span class="hljs-string">'is a subtest'</span>, <span class="hljs-function">() =></span> {
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
});
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>MockFunctionContext</code><span><a class="mark" href="#all_test_class-mockfunctioncontext" id="all_test_class-mockfunctioncontext">#</a></span><a aria-hidden="true" class="legacy" id="test_class_mockfunctioncontext"></a></h3>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p>The <code>MockFunctionContext</code> class is used to inspect or manipulate the behavior of
mocks created via the <a href="#all_test_class-mocktracker"><code>MockTracker</code></a> APIs.</p>
<h4><code>ctx.calls</code><span><a class="mark" href="#all_test_ctxcalls" id="all_test_ctxcalls">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_calls"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>A getter that returns a copy of the internal array used to track calls to the
mock. Each entry in the array is an object with the following properties.</p>
<ul>
<li><code>arguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array of the arguments passed to the mock function.</li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> If the mocked function threw then this property contains the
thrown value. <strong>Default:</strong> <code>undefined</code>.</li>
<li><code>result</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The value returned by the mocked function.</li>
<li><code>stack</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> An <code>Error</code> object whose stack can be used to determine the
callsite of the mocked function invocation.</li>
<li><code>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> If the mocked function is a constructor, this
field contains the class being constructed. Otherwise this will be
<code>undefined</code>.</li>
<li><code>this</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The mocked function's <code>this</code> value.</li>
</ul>
<h4><code>ctx.callCount()</code><span><a class="mark" href="#all_test_ctxcallcount" id="all_test_ctxcallcount">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_callcount"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of times that this mock has been invoked.</li>
</ul>
<p>This function returns the number of times that this mock has been invoked. This
function is more efficient than checking <code>ctx.calls.length</code> because <code>ctx.calls</code>
is a getter that creates a copy of the internal call tracking array.</p>
<h4><code>ctx.mockImplementation(implementation)</code><span><a class="mark" href="#all_test_ctxmockimplementationimplementation" id="all_test_ctxmockimplementationimplementation">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_mockimplementation_implementation"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<ul>
<li><code>implementation</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> The function to be used as the
mock's new implementation.</li>
</ul>
<p>This function is used to change the behavior of an existing mock.</p>
<p>The following example creates a mock function using <code>t.mock.fn()</code>, calls the
mock function, and then changes the mock implementation to a different function.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'changes a mock behavior'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-keyword">let</span> cnt = <span class="hljs-number">0</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">addOne</span>(<span class="hljs-params"></span>) {
cnt++;
<span class="hljs-keyword">return</span> cnt;
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">addTwo</span>(<span class="hljs-params"></span>) {
cnt += <span class="hljs-number">2</span>;
<span class="hljs-keyword">return</span> cnt;
}
<span class="hljs-keyword">const</span> fn = t.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>(addOne);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">1</span>);
fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">mockImplementation</span>(addTwo);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">3</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">5</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>ctx.mockImplementationOnce(implementation[, onCall])</code><span><a class="mark" href="#all_test_ctxmockimplementationonceimplementation-oncall" id="all_test_ctxmockimplementationonceimplementation-oncall">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_mockimplementationonce_implementation_oncall"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<ul>
<li><code>implementation</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> The function to be used as the
mock's implementation for the invocation number specified by <code>onCall</code>.</li>
<li><code>onCall</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The invocation number that will use <code>implementation</code>. If
the specified invocation has already occurred then an exception is thrown.
<strong>Default:</strong> The number of the next invocation.</li>
</ul>
<p>This function is used to change the behavior of an existing mock for a single
invocation. Once invocation <code>onCall</code> has occurred, the mock will revert to
whatever behavior it would have used had <code>mockImplementationOnce()</code> not been
called.</p>
<p>The following example creates a mock function using <code>t.mock.fn()</code>, calls the
mock function, changes the mock implementation to a different function for the
next invocation, and then resumes its previous behavior.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'changes a mock behavior once'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-keyword">let</span> cnt = <span class="hljs-number">0</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">addOne</span>(<span class="hljs-params"></span>) {
cnt++;
<span class="hljs-keyword">return</span> cnt;
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">addTwo</span>(<span class="hljs-params"></span>) {
cnt += <span class="hljs-number">2</span>;
<span class="hljs-keyword">return</span> cnt;
}
<span class="hljs-keyword">const</span> fn = t.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>(addOne);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">1</span>);
fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">mockImplementationOnce</span>(addTwo);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">3</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">4</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>ctx.resetCalls()</code><span><a class="mark" href="#all_test_ctxresetcalls" id="all_test_ctxresetcalls">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_resetcalls"></a></h4>
<div class="api_metadata">
<span>Added in: v19.3.0, v18.13.0</span>
</div>
<p>Resets the call history of the mock function.</p>
<h4><code>ctx.restore()</code><span><a class="mark" href="#all_test_ctxrestore" id="all_test_ctxrestore">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_restore"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p>Resets the implementation of the mock function to its original behavior. The
mock can still be used after calling this function.</p>
</section><section><h3>Class: <code>MockModuleContext</code><span><a class="mark" href="#all_test_class-mockmodulecontext" id="all_test_class-mockmodulecontext">#</a></span><a aria-hidden="true" class="legacy" id="test_class_mockmodulecontext"></a></h3>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.0 - Early development</div><p></p>
<p>The <code>MockModuleContext</code> class is used to manipulate the behavior of module mocks
created via the <a href="#all_test_class-mocktracker"><code>MockTracker</code></a> APIs.</p>
<h4><code>ctx.restore()</code><span><a class="mark" href="#all_test_ctxrestore_1" id="all_test_ctxrestore_1">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_restore_1"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p>Resets the implementation of the mock module.</p>
</section><section><h3>Class: <code>MockTracker</code><span><a class="mark" href="#all_test_class-mocktracker" id="all_test_class-mocktracker">#</a></span><a aria-hidden="true" class="legacy" id="test_class_mocktracker"></a></h3>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p>The <code>MockTracker</code> class is used to manage mocking functionality. The test runner
module provides a top level <code>mock</code> export which is a <code>MockTracker</code> instance.
Each test also provides its own <code>MockTracker</code> instance via the test context's
<code>mock</code> property.</p>
<h4><code>mock.fn([original[, implementation]][, options])</code><span><a class="mark" href="#all_test_mockfnoriginal-implementation-options" id="all_test_mockfnoriginal-implementation-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_fn_original_implementation_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<ul>
<li><code>original</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> An optional function to create a mock on.
<strong>Default:</strong> A no-op function.</li>
<li><code>implementation</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> An optional function used as the
mock implementation for <code>original</code>. This is useful for creating mocks that
exhibit one behavior for a specified number of calls and then restore the
behavior of <code>original</code>. <strong>Default:</strong> The function specified by <code>original</code>.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Optional configuration options for the mock function. The
following properties are supported:
<ul>
<li><code>times</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of times that the mock will use the behavior of
<code>implementation</code>. Once the mock function has been called <code>times</code> times, it
will automatically restore the behavior of <code>original</code>. This value must be an
integer greater than zero. <strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" class="type"><Proxy></a> The mocked function. The mocked function contains a special
<code>mock</code> property, which is an instance of <a href="#all_test_class-mockfunctioncontext"><code>MockFunctionContext</code></a>, and can
be used for inspecting and changing the behavior of the mocked function.</li>
</ul>
<p>This function is used to create a mock function.</p>
<p>The following example creates a mock function that increments a counter by one
on each invocation. The <code>times</code> option is used to modify the mock behavior such
that the first two invocations add two to the counter instead of one.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks a counting function'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-keyword">let</span> cnt = <span class="hljs-number">0</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">addOne</span>(<span class="hljs-params"></span>) {
cnt++;
<span class="hljs-keyword">return</span> cnt;
}
<span class="hljs-keyword">function</span> <span class="hljs-title function_">addTwo</span>(<span class="hljs-params"></span>) {
cnt += <span class="hljs-number">2</span>;
<span class="hljs-keyword">return</span> cnt;
}
<span class="hljs-keyword">const</span> fn = t.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>(addOne, addTwo, { <span class="hljs-attr">times</span>: <span class="hljs-number">2</span> });
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">2</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">4</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">5</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">6</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>mock.getter(object, methodName[, implementation][, options])</code><span><a class="mark" href="#all_test_mockgetterobject-methodname-implementation-options" id="all_test_mockgetterobject-methodname-implementation-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_getter_object_methodname_implementation_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.3.0, v18.13.0</span>
</div>
<p>This function is syntax sugar for <a href="#all_test_mockmethodobject-methodname-implementation-options"><code>MockTracker.method</code></a> with <code>options.getter</code>
set to <code>true</code>.</p>
<h4><code>mock.method(object, methodName[, implementation][, options])</code><span><a class="mark" href="#all_test_mockmethodobject-methodname-implementation-options" id="all_test_mockmethodobject-methodname-implementation-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_method_object_methodname_implementation_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The object whose method is being mocked.</li>
<li><code>methodName</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#Symbol_type" class="type"><symbol></a> The identifier of the method on <code>object</code> to mock.
If <code>object[methodName]</code> is not a function, an error is thrown.</li>
<li><code>implementation</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> An optional function used as the
mock implementation for <code>object[methodName]</code>. <strong>Default:</strong> The original method
specified by <code>object[methodName]</code>.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Optional configuration options for the mock method. The
following properties are supported:
<ul>
<li><code>getter</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, <code>object[methodName]</code> is treated as a getter.
This option cannot be used with the <code>setter</code> option. <strong>Default:</strong> false.</li>
<li><code>setter</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, <code>object[methodName]</code> is treated as a setter.
This option cannot be used with the <code>getter</code> option. <strong>Default:</strong> false.</li>
<li><code>times</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of times that the mock will use the behavior of
<code>implementation</code>. Once the mocked method has been called <code>times</code> times, it
will automatically restore the original behavior. This value must be an
integer greater than zero. <strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" class="type"><Proxy></a> The mocked method. The mocked method contains a special
<code>mock</code> property, which is an instance of <a href="#all_test_class-mockfunctioncontext"><code>MockFunctionContext</code></a>, and can
be used for inspecting and changing the behavior of the mocked method.</li>
</ul>
<p>This function is used to create a mock on an existing object method. The
following example demonstrates how a mock is created on an existing object
method.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'spies on an object method'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-keyword">const</span> number = {
<span class="hljs-attr">value</span>: <span class="hljs-number">5</span>,
<span class="hljs-title function_">subtract</span>(<span class="hljs-params">a</span>) {
<span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> - a;
},
};
t.<span class="hljs-property">mock</span>.<span class="hljs-title function_">method</span>(number, <span class="hljs-string">'subtract'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(number.<span class="hljs-property">subtract</span>.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
assert.<span class="hljs-title function_">strictEqual</span>(number.<span class="hljs-title function_">subtract</span>(<span class="hljs-number">3</span>), <span class="hljs-number">2</span>);
assert.<span class="hljs-title function_">strictEqual</span>(number.<span class="hljs-property">subtract</span>.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
<span class="hljs-keyword">const</span> call = number.<span class="hljs-property">subtract</span>.<span class="hljs-property">mock</span>.<span class="hljs-property">calls</span>[<span class="hljs-number">0</span>];
assert.<span class="hljs-title function_">deepStrictEqual</span>(call.<span class="hljs-property">arguments</span>, [<span class="hljs-number">3</span>]);
assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">result</span>, <span class="hljs-number">2</span>);
assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">error</span>, <span class="hljs-literal">undefined</span>);
assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">target</span>, <span class="hljs-literal">undefined</span>);
assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">this</span>, number);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>mock.module(specifier[, options])</code><span><a class="mark" href="#all_test_mockmodulespecifier-options" id="all_test_mockmodulespecifier-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_module_specifier_options"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.0 - Early development</div><p></p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string identifying the module to mock.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Optional configuration options for the mock module. The
following properties are supported:
<ul>
<li><code>cache</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>false</code>, each call to <code>require()</code> or <code>import()</code>
generates a new mock module. If <code>true</code>, subsequent calls will return the same
module mock, and the mock module is inserted into the CommonJS cache.
<strong>Default:</strong> false.</li>
<li><code>defaultExport</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> An optional value used as the mocked module's default
export. If this value is not provided, ESM mocks do not include a default
export. If the mock is a CommonJS or builtin module, this setting is used as
the value of <code>module.exports</code>. If this value is not provided, CJS and builtin
mocks use an empty object as the value of <code>module.exports</code>.</li>
<li><code>namedExports</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An optional object whose keys and values are used to
create the named exports of the mock module. If the mock is a CommonJS or
builtin module, these values are copied onto <code>module.exports</code>. Therefore, if a
mock is created with both named exports and a non-object default export, the
mock will throw an exception when used as a CJS or builtin module.</li>
</ul>
</li>
<li>Returns: <a href="#all_test_class-mockmodulecontext" class="type"><MockModuleContext></a> An object that can be used to manipulate the mock.</li>
</ul>
<p>This function is used to mock the exports of ECMAScript modules, CommonJS
modules, and Node.js builtin modules. Any references to the original module
prior to mocking are not impacted. The following example demonstrates how a mock
is created for a module.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks a builtin module in both module systems'</span>, <span class="hljs-title function_">async</span> (t) => {
<span class="hljs-comment">// Create a mock of 'node:readline' with a named export named 'fn', which</span>
<span class="hljs-comment">// does not exist in the original 'node:readline' module.</span>
<span class="hljs-keyword">const</span> mock = t.<span class="hljs-property">mock</span>.<span class="hljs-title function_">module</span>(<span class="hljs-string">'node:readline'</span>, {
<span class="hljs-attr">namedExports</span>: { <span class="hljs-title function_">fn</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">return</span> <span class="hljs-number">42</span>; } },
});
<span class="hljs-keyword">let</span> esmImpl = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:readline'</span>);
<span class="hljs-keyword">let</span> cjsImpl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);
<span class="hljs-comment">// cursorTo() is an export of the original 'node:readline' module.</span>
assert.<span class="hljs-title function_">strictEqual</span>(esmImpl.<span class="hljs-property">cursorTo</span>, <span class="hljs-literal">undefined</span>);
assert.<span class="hljs-title function_">strictEqual</span>(cjsImpl.<span class="hljs-property">cursorTo</span>, <span class="hljs-literal">undefined</span>);
assert.<span class="hljs-title function_">strictEqual</span>(esmImpl.<span class="hljs-title function_">fn</span>(), <span class="hljs-number">42</span>);
assert.<span class="hljs-title function_">strictEqual</span>(cjsImpl.<span class="hljs-title function_">fn</span>(), <span class="hljs-number">42</span>);
mock.<span class="hljs-title function_">restore</span>();
<span class="hljs-comment">// The mock is restored, so the original builtin module is returned.</span>
esmImpl = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:readline'</span>);
cjsImpl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-keyword">typeof</span> esmImpl.<span class="hljs-property">cursorTo</span>, <span class="hljs-string">'function'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-keyword">typeof</span> cjsImpl.<span class="hljs-property">cursorTo</span>, <span class="hljs-string">'function'</span>);
assert.<span class="hljs-title function_">strictEqual</span>(esmImpl.<span class="hljs-property">fn</span>, <span class="hljs-literal">undefined</span>);
assert.<span class="hljs-title function_">strictEqual</span>(cjsImpl.<span class="hljs-property">fn</span>, <span class="hljs-literal">undefined</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>mock.reset()</code><span><a class="mark" href="#all_test_mockreset" id="all_test_mockreset">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_reset"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p>This function restores the default behavior of all mocks that were previously
created by this <code>MockTracker</code> and disassociates the mocks from the
<code>MockTracker</code> instance. Once disassociated, the mocks can still be used, but the
<code>MockTracker</code> instance can no longer be used to reset their behavior or
otherwise interact with them.</p>
<p>After each test completes, this function is called on the test context's
<code>MockTracker</code>. If the global <code>MockTracker</code> is used extensively, calling this
function manually is recommended.</p>
<h4><code>mock.restoreAll()</code><span><a class="mark" href="#all_test_mockrestoreall" id="all_test_mockrestoreall">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_restoreall"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p>This function restores the default behavior of all mocks that were previously
created by this <code>MockTracker</code>. Unlike <code>mock.reset()</code>, <code>mock.restoreAll()</code> does
not disassociate the mocks from the <code>MockTracker</code> instance.</p>
<h4><code>mock.setter(object, methodName[, implementation][, options])</code><span><a class="mark" href="#all_test_mocksetterobject-methodname-implementation-options" id="all_test_mocksetterobject-methodname-implementation-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_setter_object_methodname_implementation_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.3.0, v18.13.0</span>
</div>
<p>This function is syntax sugar for <a href="#all_test_mockmethodobject-methodname-implementation-options"><code>MockTracker.method</code></a> with <code>options.setter</code>
set to <code>true</code>.</p>
</section><section><h3>Class: <code>MockTimers</code><span><a class="mark" href="#all_test_class-mocktimers" id="all_test_class-mocktimers">#</a></span><a aria-hidden="true" class="legacy" id="test_class_mocktimers"></a></h3>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Mocking timers is a technique commonly used in software testing to simulate and
control the behavior of timers, such as <code>setInterval</code> and <code>setTimeout</code>,
without actually waiting for the specified time intervals.</p>
<p>MockTimers is also able to mock the <code>Date</code> object.</p>
<p>The <a href="#all_test_class-mocktracker"><code>MockTracker</code></a> provides a top-level <code>timers</code> export
which is a <code>MockTimers</code> instance.</p>
<h4><code>timers.enable([enableOptions])</code><span><a class="mark" href="#all_test_timersenableenableoptions" id="all_test_timersenableenableoptions">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_enable_enableoptions"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.11.0</td>
<td><p>Updated parameters to be an option object with available APIs and the default initial epoch.</p></td></tr>
<tr><td>v20.4.0</td>
<td><p><span>Added in: v20.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enables timer mocking for the specified timers.</p>
<ul>
<li><code>enableOptions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Optional configuration options for enabling timer
mocking. The following properties are supported:
<ul>
<li><code>apis</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An optional array containing the timers to mock.
The currently supported timer values are <code>'setInterval'</code>, <code>'setTimeout'</code>, <code>'setImmediate'</code>,
and <code>'Date'</code>. <strong>Default:</strong> <code>['setInterval', 'setTimeout', 'setImmediate', 'Date']</code>.
If no array is provided, all time related APIs (<code>'setInterval'</code>, <code>'clearInterval'</code>,
<code>'setTimeout'</code>, <code>'clearTimeout'</code>, <code>'setImmediate'</code>, <code>'clearImmediate'</code>, and
<code>'Date'</code>) will be mocked by default.</li>
<li><code>now</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a> An optional number or Date object representing the
initial time (in milliseconds) to use as the value
for <code>Date.now()</code>. <strong>Default:</strong> <code>0</code>.</li>
</ul>
</li>
</ul>
<p><strong>Note:</strong> When you enable mocking for a specific timer, its associated
clear function will also be implicitly mocked.</p>
<p><strong>Note:</strong> Mocking <code>Date</code> will affect the behavior of the mocked timers
as they use the same internal clock.</p>
<p>Example usage without setting initial time:</p>
<pre class="with-46-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> { mock } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setInterval'</span>] });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { mock } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setInterval'</span>] });</code><button class="copy-button">copy</button></pre>
<p>The above example enables mocking for the <code>setInterval</code> timer and
implicitly mocks the <code>clearInterval</code> function. Only the <code>setInterval</code>
and <code>clearInterval</code> functions from <a href="./timers.html">node:timers</a>,
<a href="./timers.html#timers-promises-api">node:timers/promises</a>, and
<code>globalThis</code> will be mocked.</p>
<p>Example usage with initial time set</p>
<pre class="with-50-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> { mock } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-number">1000</span> });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { mock } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-number">1000</span> });</code><button class="copy-button">copy</button></pre>
<p>Example usage with initial Date object as time set</p>
<pre class="with-56-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> { mock } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>() });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { mock } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>() });</code><button class="copy-button">copy</button></pre>
<p>Alternatively, if you call <code>mock.timers.enable()</code> without any parameters:</p>
<p>All timers (<code>'setInterval'</code>, <code>'clearInterval'</code>, <code>'setTimeout'</code>, <code>'clearTimeout'</code>,
<code>'setImmediate'</code>, and <code>'clearImmediate'</code>) will be mocked. The <code>setInterval</code>,
<code>clearInterval</code>, <code>setTimeout</code>, <code>clearTimeout</code>, <code>setImmediate</code>, and
<code>clearImmediate</code> functions from <code>node:timers</code>, <code>node:timers/promises</code>, and
<code>globalThis</code> will be mocked. As well as the global <code>Date</code> object.</p>
<h4><code>timers.reset()</code><span><a class="mark" href="#all_test_timersreset" id="all_test_timersreset">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_reset"></a></h4>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p>This function restores the default behavior of all mocks that were previously
created by this <code>MockTimers</code> instance and disassociates the mocks
from the <code>MockTracker</code> instance.</p>
<p><strong>Note:</strong> After each test completes, this function is called on
the test context's <code>MockTracker</code>.</p>
<pre class="with-38-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> { mock } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">reset</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { mock } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">reset</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>timers[Symbol.dispose]()</code><span><a class="mark" href="#all_test_timerssymboldispose" id="all_test_timerssymboldispose">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_symbol_dispose"></a></h4>
<p>Calls <code>timers.reset()</code>.</p>
<h4><code>timers.tick([milliseconds])</code><span><a class="mark" href="#all_test_timerstickmilliseconds" id="all_test_timerstickmilliseconds">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_tick_milliseconds"></a></h4>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p>Advances time for all mocked timers.</p>
<ul>
<li><code>milliseconds</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The amount of time, in milliseconds,
to advance the timers. <strong>Default:</strong> <code>1</code>.</li>
</ul>
<p><strong>Note:</strong> This diverges from how <code>setTimeout</code> in Node.js behaves and accepts
only positive numbers. In Node.js, <code>setTimeout</code> with negative numbers is
only supported for web compatibility reasons.</p>
<p>The following example mocks a <code>setTimeout</code> function and
by using <code>.tick</code> advances in
time triggering all pending timers.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
<span class="hljs-comment">// Advance in time</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
<span class="hljs-comment">// Advance in time</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Alternatively, the <code>.tick</code> function can be called many times</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
<span class="hljs-keyword">const</span> nineSecs = <span class="hljs-number">9000</span>;
<span class="hljs-built_in">setTimeout</span>(fn, nineSecs);
<span class="hljs-keyword">const</span> threeSeconds = <span class="hljs-number">3000</span>;
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(threeSeconds);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(threeSeconds);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(threeSeconds);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
<span class="hljs-keyword">const</span> nineSecs = <span class="hljs-number">9000</span>;
<span class="hljs-built_in">setTimeout</span>(fn, nineSecs);
<span class="hljs-keyword">const</span> threeSeconds = <span class="hljs-number">3000</span>;
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(threeSeconds);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(threeSeconds);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(threeSeconds);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Advancing time using <code>.tick</code> will also advance the time for any <code>Date</code> object
created after the mock was enabled (if <code>Date</code> was also set to be mocked).</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">0</span>);
<span class="hljs-comment">// Advance in time</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">9999</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
<span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">0</span>);
<span class="hljs-comment">// Advance in time</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">9999</span>);
});</code><button class="copy-button">copy</button></pre>
<h5>Using clear functions<span><a class="mark" href="#all_test_using-clear-functions" id="all_test_using-clear-functions">#</a></span><a aria-hidden="true" class="legacy" id="test_using_clear_functions"></a></h5>
<p>As mentioned, all clear functions from timers (<code>clearTimeout</code>, <code>clearInterval</code>,and
<code>clearImmediate</code>) are implicitly mocked. Take a look at this example using <code>setTimeout</code>:</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
<span class="hljs-keyword">const</span> id = <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
<span class="hljs-comment">// Implicitly mocked as well</span>
<span class="hljs-built_in">clearTimeout</span>(id);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
<span class="hljs-comment">// As that setTimeout was cleared the mock function will never be called</span>
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
<span class="hljs-keyword">const</span> id = <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
<span class="hljs-comment">// Implicitly mocked as well</span>
<span class="hljs-built_in">clearTimeout</span>(id);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
<span class="hljs-comment">// As that setTimeout was cleared the mock function will never be called</span>
assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
});</code><button class="copy-button">copy</button></pre>
<h5>Working with Node.js timers modules<span><a class="mark" href="#all_test_working-with-nodejs-timers-modules" id="all_test_working-with-nodejs-timers-modules">#</a></span><a aria-hidden="true" class="legacy" id="test_working_with_node_js_timers_modules"></a></h5>
<p>Once you enable mocking timers, <a href="./timers.html">node:timers</a>,
<a href="./timers.html#timers-promises-api">node:timers/promises</a> modules,
and timers from the Node.js global context are enabled:</p>
<p><strong>Note:</strong> Destructuring functions such as
<code>import { setTimeout } from 'node:timers'</code> is currently
not supported by this API.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-keyword">import</span> nodeTimers <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers'</span>;
<span class="hljs-keyword">import</span> nodeTimersPromises <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-title function_">async</span> (context) => {
<span class="hljs-keyword">const</span> globalTimeoutObjectSpy = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-keyword">const</span> nodeTimerSpy = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-keyword">const</span> nodeTimerPromiseSpy = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
<span class="hljs-built_in">setTimeout</span>(globalTimeoutObjectSpy, <span class="hljs-number">9999</span>);
nodeTimers.<span class="hljs-built_in">setTimeout</span>(nodeTimerSpy, <span class="hljs-number">9999</span>);
<span class="hljs-keyword">const</span> promise = nodeTimersPromises.<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">9999</span>).<span class="hljs-title function_">then</span>(nodeTimerPromiseSpy);
<span class="hljs-comment">// Advance in time</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(globalTimeoutObjectSpy.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
assert.<span class="hljs-title function_">strictEqual</span>(nodeTimerSpy.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
<span class="hljs-keyword">await</span> promise;
assert.<span class="hljs-title function_">strictEqual</span>(nodeTimerPromiseSpy.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-keyword">const</span> nodeTimers = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers'</span>);
<span class="hljs-keyword">const</span> nodeTimersPromises = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-title function_">async</span> (context) => {
<span class="hljs-keyword">const</span> globalTimeoutObjectSpy = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-keyword">const</span> nodeTimerSpy = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-keyword">const</span> nodeTimerPromiseSpy = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
<span class="hljs-comment">// Optionally choose what to mock</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
<span class="hljs-built_in">setTimeout</span>(globalTimeoutObjectSpy, <span class="hljs-number">9999</span>);
nodeTimers.<span class="hljs-built_in">setTimeout</span>(nodeTimerSpy, <span class="hljs-number">9999</span>);
<span class="hljs-keyword">const</span> promise = nodeTimersPromises.<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">9999</span>).<span class="hljs-title function_">then</span>(nodeTimerPromiseSpy);
<span class="hljs-comment">// Advance in time</span>
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">strictEqual</span>(globalTimeoutObjectSpy.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
assert.<span class="hljs-title function_">strictEqual</span>(nodeTimerSpy.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
<span class="hljs-keyword">await</span> promise;
assert.<span class="hljs-title function_">strictEqual</span>(nodeTimerPromiseSpy.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><button class="copy-button">copy</button></pre>
<p>In Node.js, <code>setInterval</code> from <a href="./timers.html#timers-promises-api">node:timers/promises</a>
is an <code>AsyncGenerator</code> and is also supported by this API:</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-keyword">import</span> nodeTimersPromises <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'should tick five times testing a real use case'</span>, <span class="hljs-title function_">async</span> (context) => {
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setInterval'</span>] });
<span class="hljs-keyword">const</span> expectedIterations = <span class="hljs-number">3</span>;
<span class="hljs-keyword">const</span> interval = <span class="hljs-number">1000</span>;
<span class="hljs-keyword">const</span> startedAt = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</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> times = [];
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> time <span class="hljs-keyword">of</span> nodeTimersPromises.<span class="hljs-built_in">setInterval</span>(interval, startedAt)) {
times.<span class="hljs-title function_">push</span>(time);
<span class="hljs-keyword">if</span> (times.<span class="hljs-property">length</span> === expectedIterations) <span class="hljs-keyword">break</span>;
}
<span class="hljs-keyword">return</span> times;
}
<span class="hljs-keyword">const</span> r = <span class="hljs-title function_">run</span>();
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(interval);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(interval);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(interval);
<span class="hljs-keyword">const</span> timeResults = <span class="hljs-keyword">await</span> r;
assert.<span class="hljs-title function_">strictEqual</span>(timeResults.<span class="hljs-property">length</span>, expectedIterations);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> it = <span class="hljs-number">1</span>; it < expectedIterations; it++) {
assert.<span class="hljs-title function_">strictEqual</span>(timeResults[it - <span class="hljs-number">1</span>], startedAt + (interval * it));
}
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-keyword">const</span> nodeTimersPromises = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'should tick five times testing a real use case'</span>, <span class="hljs-title function_">async</span> (context) => {
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setInterval'</span>] });
<span class="hljs-keyword">const</span> expectedIterations = <span class="hljs-number">3</span>;
<span class="hljs-keyword">const</span> interval = <span class="hljs-number">1000</span>;
<span class="hljs-keyword">const</span> startedAt = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</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> times = [];
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> time <span class="hljs-keyword">of</span> nodeTimersPromises.<span class="hljs-built_in">setInterval</span>(interval, startedAt)) {
times.<span class="hljs-title function_">push</span>(time);
<span class="hljs-keyword">if</span> (times.<span class="hljs-property">length</span> === expectedIterations) <span class="hljs-keyword">break</span>;
}
<span class="hljs-keyword">return</span> times;
}
<span class="hljs-keyword">const</span> r = <span class="hljs-title function_">run</span>();
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(interval);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(interval);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(interval);
<span class="hljs-keyword">const</span> timeResults = <span class="hljs-keyword">await</span> r;
assert.<span class="hljs-title function_">strictEqual</span>(timeResults.<span class="hljs-property">length</span>, expectedIterations);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> it = <span class="hljs-number">1</span>; it < expectedIterations; it++) {
assert.<span class="hljs-title function_">strictEqual</span>(timeResults[it - <span class="hljs-number">1</span>], startedAt + (interval * it));
}
});</code><button class="copy-button">copy</button></pre>
<h4><code>timers.runAll()</code><span><a class="mark" href="#all_test_timersrunall" id="all_test_timersrunall">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_runall"></a></h4>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p>Triggers all pending mocked timers immediately. If the <code>Date</code> object is also
mocked, it will also advance the <code>Date</code> object to the furthest timer's time.</p>
<p>The example below triggers all pending timers immediately,
causing them to execute without any delay.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'runAll functions following the given order'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
<span class="hljs-keyword">const</span> results = [];
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">1</span>), <span class="hljs-number">9999</span>);
<span class="hljs-comment">// Notice that if both timers have the same timeout,</span>
<span class="hljs-comment">// the order of execution is guaranteed</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">3</span>), <span class="hljs-number">8888</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">2</span>), <span class="hljs-number">8888</span>);
assert.<span class="hljs-title function_">deepStrictEqual</span>(results, []);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">runAll</span>();
assert.<span class="hljs-title function_">deepStrictEqual</span>(results, [<span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>]);
<span class="hljs-comment">// The Date object is also advanced to the furthest timer's time</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">9999</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'runAll functions following the given order'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
<span class="hljs-keyword">const</span> results = [];
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">1</span>), <span class="hljs-number">9999</span>);
<span class="hljs-comment">// Notice that if both timers have the same timeout,</span>
<span class="hljs-comment">// the order of execution is guaranteed</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">3</span>), <span class="hljs-number">8888</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">2</span>), <span class="hljs-number">8888</span>);
assert.<span class="hljs-title function_">deepStrictEqual</span>(results, []);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">runAll</span>();
assert.<span class="hljs-title function_">deepStrictEqual</span>(results, [<span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>]);
<span class="hljs-comment">// The Date object is also advanced to the furthest timer's time</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">9999</span>);
});</code><button class="copy-button">copy</button></pre>
<p><strong>Note:</strong> The <code>runAll()</code> function is specifically designed for
triggering timers in the context of timer mocking.
It does not have any effect on real-time system
clocks or actual timers outside of the mocking environment.</p>
<h4><code>timers.setTime(milliseconds)</code><span><a class="mark" href="#all_test_timerssettimemilliseconds" id="all_test_timerssettimemilliseconds">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_settime_milliseconds"></a></h4>
<div class="api_metadata">
<span>Added in: v20.11.0</span>
</div>
<p>Sets the current Unix timestamp that will be used as reference for any mocked
<code>Date</code> objects.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'runAll functions following the given order'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-keyword">const</span> now = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
<span class="hljs-keyword">const</span> setTime = <span class="hljs-number">1000</span>;
<span class="hljs-comment">// Date.now is not mocked</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), now);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>] });
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(setTime);
<span class="hljs-comment">// Date.now is now 1000</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), setTime);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'setTime replaces current time'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
<span class="hljs-keyword">const</span> now = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
<span class="hljs-keyword">const</span> setTime = <span class="hljs-number">1000</span>;
<span class="hljs-comment">// Date.now is not mocked</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), now);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>] });
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(setTime);
<span class="hljs-comment">// Date.now is now 1000</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), setTime);
});</code><button class="copy-button">copy</button></pre>
<h5>Dates and Timers working together<span><a class="mark" href="#all_test_dates-and-timers-working-together" id="all_test_dates-and-timers-working-together">#</a></span><a aria-hidden="true" class="legacy" id="test_dates_and_timers_working_together"></a></h5>
<p>Dates and timer objects are dependent on each other. If you use <code>setTime()</code> to
pass the current time to the mocked <code>Date</code> object, the set timers with
<code>setTimeout</code> and <code>setInterval</code> will <strong>not</strong> be affected.</p>
<p>However, the <code>tick</code> method <strong>will</strong> advanced the mocked <code>Date</code> object.</p>
<pre class="with-38-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> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'runAll functions following the given order'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
<span class="hljs-keyword">const</span> results = [];
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">1</span>), <span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">deepStrictEqual</span>(results, []);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">12000</span>);
assert.<span class="hljs-title function_">deepStrictEqual</span>(results, []);
<span class="hljs-comment">// The date is advanced but the timers don't tick</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">12000</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'runAll functions following the given order'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
<span class="hljs-keyword">const</span> results = [];
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">1</span>), <span class="hljs-number">9999</span>);
assert.<span class="hljs-title function_">deepStrictEqual</span>(results, []);
context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">12000</span>);
assert.<span class="hljs-title function_">deepStrictEqual</span>(results, []);
<span class="hljs-comment">// The date is advanced but the timers don't tick</span>
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">12000</span>);
});</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>TestsStream</code><span><a class="mark" href="#all_test_class-testsstream" id="all_test_class-testsstream">#</a></span><a aria-hidden="true" class="legacy" id="test_class_testsstream"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0, v19.9.0, v18.17.0</td>
<td><p>added type to test:pass and test:fail events for when the test is a suite.</p></td></tr>
<tr><td>v18.9.0, v16.19.0</td>
<td><p><span>Added in: v18.9.0, v16.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Extends <a href="#all_stream_class-streamreadable" class="type"><Readable></a></li>
</ul>
<p>A successful call to <a href="#all_test_runoptions"><code>run()</code></a> method will return a new <a href="#all_test_class-testsstream" class="type"><TestsStream></a>
object, streaming a series of events representing the execution of the tests.
<code>TestsStream</code> will emit events, in the order of the tests definition</p>
<p>Some of the events are guaranteed to be emitted in the same order as the tests
are defined, while others are emitted in the order that the tests execute.</p>
<h4>Event: <code>'test:coverage'</code><span><a class="mark" href="#all_test_event-testcoverage" id="all_test_event-testcoverage">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_coverage"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>summary</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing the coverage report.
<ul>
<li><code>files</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array of coverage reports for individual files. Each
report is an object with the following schema:
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The absolute path of the file.</li>
<li><code>totalLineCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of lines.</li>
<li><code>totalBranchCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of branches.</li>
<li><code>totalFunctionCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of functions.</li>
<li><code>coveredLineCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of covered lines.</li>
<li><code>coveredBranchCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of covered branches.</li>
<li><code>coveredFunctionCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of covered functions.</li>
<li><code>coveredLinePercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The percentage of lines covered.</li>
<li><code>coveredBranchPercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The percentage of branches covered.</li>
<li><code>coveredFunctionPercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The percentage of functions covered.</li>
<li><code>functions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array of functions representing function
coverage.
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the function.</li>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The line number where the function is defined.</li>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of times the function was called.</li>
</ul>
</li>
<li><code>branches</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array of branches representing branch coverage.
<ul>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The line number where the branch is defined.</li>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of times the branch was taken.</li>
</ul>
</li>
<li><code>lines</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array of lines representing line
numbers and the number of times they were covered.
<ul>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The line number.</li>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of times the line was covered.</li>
</ul>
</li>
</ul>
</li>
<li><code>totals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing a summary of coverage for all
files.
<ul>
<li><code>totalLineCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of lines.</li>
<li><code>totalBranchCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of branches.</li>
<li><code>totalFunctionCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of functions.</li>
<li><code>coveredLineCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of covered lines.</li>
<li><code>coveredBranchCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of covered branches.</li>
<li><code>coveredFunctionCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of covered functions.</li>
<li><code>coveredLinePercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The percentage of lines covered.</li>
<li><code>coveredBranchPercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The percentage of branches covered.</li>
<li><code>coveredFunctionPercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The percentage of functions covered.</li>
</ul>
</li>
<li><code>workingDirectory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The working directory when code coverage
began. This is useful for displaying relative path names in case the tests
changed the working directory of the Node.js process.</li>
</ul>
</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li>
</ul>
</li>
</ul>
<p>Emitted when code coverage is enabled and all tests have completed.</p>
<h4>Event: <code>'test:complete'</code><span><a class="mark" href="#all_test_event-testcomplete" id="all_test_event-testcomplete">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_complete"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>column</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>details</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Additional execution metadata.
<ul>
<li><code>passed</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the test passed or not.</li>
<li><code>duration_ms</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The duration of the test in milliseconds.</li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> An error wrapping the error thrown by the test
if it did not pass.
<ul>
<li><code>cause</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The actual error thrown by the test.</li>
</ul>
</li>
<li><code>type</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#Undefined_type" class="type"><undefined></a> The type of the test, used to denote whether
this is a suite.</li>
</ul>
</li>
<li><code>file</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#Undefined_type" class="type"><undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The test name.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li>
<li><code>testNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ordinal number of the test.</li>
<li><code>todo</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#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> Present if <a href="#all_test_contexttodomessage"><code>context.todo</code></a> is called</li>
<li><code>skip</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#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> Present if <a href="#all_test_contextskipmessage"><code>context.skip</code></a> is called</li>
</ul>
</li>
</ul>
<p>Emitted when a test completes its execution.
This event is not emitted in the same order as the tests are
defined.
The corresponding declaration ordered events are <code>'test:pass'</code> and <code>'test:fail'</code>.</p>
<h4>Event: <code>'test:dequeue'</code><span><a class="mark" href="#all_test_event-testdequeue" id="all_test_event-testdequeue">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_dequeue"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>column</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>file</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#Undefined_type" class="type"><undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The test name.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li>
</ul>
</li>
</ul>
<p>Emitted when a test is dequeued, right before it is executed.
This event is not guaranteed to be emitted in the same order as the tests are
defined. The corresponding declaration ordered event is <code>'test:start'</code>.</p>
<h4>Event: <code>'test:diagnostic'</code><span><a class="mark" href="#all_test_event-testdiagnostic" id="all_test_event-testdiagnostic">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_diagnostic"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>column</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>file</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#Undefined_type" class="type"><undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The diagnostic message.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li>
</ul>
</li>
</ul>
<p>Emitted when <a href="#all_test_contextdiagnosticmessage"><code>context.diagnostic</code></a> is called.
This event is guaranteed to be emitted in the same order as the tests are
defined.</p>
<h4>Event: <code>'test:enqueue'</code><span><a class="mark" href="#all_test_event-testenqueue" id="all_test_event-testenqueue">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_enqueue"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>column</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>file</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#Undefined_type" class="type"><undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The test name.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li>
</ul>
</li>
</ul>
<p>Emitted when a test is enqueued for execution.</p>
<h4>Event: <code>'test:fail'</code><span><a class="mark" href="#all_test_event-testfail" id="all_test_event-testfail">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_fail"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>column</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>details</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Additional execution metadata.
<ul>
<li><code>duration_ms</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The duration of the test in milliseconds.</li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> An error wrapping the error thrown by the test.
<ul>
<li><code>cause</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The actual error thrown by the test.</li>
</ul>
</li>
<li><code>type</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#Undefined_type" class="type"><undefined></a> The type of the test, used to denote whether
this is a suite.</li>
</ul>
</li>
<li><code>file</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#Undefined_type" class="type"><undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The test name.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li>
<li><code>testNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ordinal number of the test.</li>
<li><code>todo</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#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> Present if <a href="#all_test_contexttodomessage"><code>context.todo</code></a> is called</li>
<li><code>skip</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#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> Present if <a href="#all_test_contextskipmessage"><code>context.skip</code></a> is called</li>
</ul>
</li>
</ul>
<p>Emitted when a test fails.
This event is guaranteed to be emitted in the same order as the tests are
defined.
The corresponding execution ordered event is <code>'test:complete'</code>.</p>
<h4>Event: <code>'test:pass'</code><span><a class="mark" href="#all_test_event-testpass" id="all_test_event-testpass">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_pass"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>column</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>details</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Additional execution metadata.
<ul>
<li><code>duration_ms</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The duration of the test in milliseconds.</li>
<li><code>type</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#Undefined_type" class="type"><undefined></a> The type of the test, used to denote whether
this is a suite.</li>
</ul>
</li>
<li><code>file</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#Undefined_type" class="type"><undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The test name.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li>
<li><code>testNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ordinal number of the test.</li>
<li><code>todo</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#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> Present if <a href="#all_test_contexttodomessage"><code>context.todo</code></a> is called</li>
<li><code>skip</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#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> Present if <a href="#all_test_contextskipmessage"><code>context.skip</code></a> is called</li>
</ul>
</li>
</ul>
<p>Emitted when a test passes.
This event is guaranteed to be emitted in the same order as the tests are
defined.
The corresponding execution ordered event is <code>'test:complete'</code>.</p>
<h4>Event: <code>'test:plan'</code><span><a class="mark" href="#all_test_event-testplan" id="all_test_event-testplan">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_plan"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>column</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>file</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#Undefined_type" class="type"><undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of subtests that have ran.</li>
</ul>
</li>
</ul>
<p>Emitted when all subtests have completed for a given test.
This event is guaranteed to be emitted in the same order as the tests are
defined.</p>
<h4>Event: <code>'test:start'</code><span><a class="mark" href="#all_test_event-teststart" id="all_test_event-teststart">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_start"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>column</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>file</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#Undefined_type" class="type"><undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The test name.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li>
</ul>
</li>
</ul>
<p>Emitted when a test starts reporting its own and its subtests status.
This event is guaranteed to be emitted in the same order as the tests are
defined.
The corresponding execution ordered event is <code>'test:dequeue'</code>.</p>
<h4>Event: <code>'test:stderr'</code><span><a class="mark" href="#all_test_event-teststderr" id="all_test_event-teststderr">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_stderr"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The path of the test file.</li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The message written to <code>stderr</code>.</li>
</ul>
</li>
</ul>
<p>Emitted when a running test writes to <code>stderr</code>.
This event is only emitted if <code>--test</code> flag is passed.
This event is not guaranteed to be emitted in the same order as the tests are
defined.</p>
<h4>Event: <code>'test:stdout'</code><span><a class="mark" href="#all_test_event-teststdout" id="all_test_event-teststdout">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_stdout"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The path of the test file.</li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The message written to <code>stdout</code>.</li>
</ul>
</li>
</ul>
<p>Emitted when a running test writes to <code>stdout</code>.
This event is only emitted if <code>--test</code> flag is passed.
This event is not guaranteed to be emitted in the same order as the tests are
defined.</p>
<h4>Event: <code>'test:watch:drained'</code><span><a class="mark" href="#all_test_event-testwatchdrained" id="all_test_event-testwatchdrained">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_watch_drained"></a></h4>
<p>Emitted when no more tests are queued for execution in watch mode.</p>
</section><section><h3>Class: <code>TestContext</code><span><a class="mark" href="#all_test_class-testcontext" id="all_test_class-testcontext">#</a></span><a aria-hidden="true" class="legacy" id="test_class_testcontext"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>The <code>before</code> function was added to TestContext.</p></td></tr>
<tr><td>v18.0.0, v16.17.0</td>
<td><p><span>Added in: v18.0.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An instance of <code>TestContext</code> is passed to each test function in order to
interact with the test runner. However, the <code>TestContext</code> constructor is not
exposed as part of the API.</p>
<h4><code>context.before([fn][, options])</code><span><a class="mark" href="#all_test_contextbeforefn-options" id="all_test_contextbeforefn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_context_before_fn_options"></a></h4>
<div class="api_metadata">
<span>Added in: v20.1.0</span>
</div>
<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> The hook function. The first argument
to this function is a <a href="#all_test_class-testcontext"><code>TestContext</code></a> object. If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function is used to create a hook running before
subtest of the current test.</p>
<h4><code>context.beforeEach([fn][, options])</code><span><a class="mark" href="#all_test_contextbeforeeachfn-options" id="all_test_contextbeforeeachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_context_beforeeach_fn_options"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<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> The hook function. The first argument
to this function is a <a href="#all_test_class-testcontext"><code>TestContext</code></a> object. If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function is used to create a hook running
before each subtest of the current test.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-title function_">async</span> (t) => {
t.<span class="hljs-title function_">beforeEach</span>(<span class="hljs-function">(<span class="hljs-params">t</span>) =></span> t.<span class="hljs-title function_">diagnostic</span>(<span class="hljs-string">`about to run <span class="hljs-subst">${t.name}</span>`</span>));
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(
<span class="hljs-string">'This is a subtest'</span>,
<span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
},
);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.after([fn][, options])</code><span><a class="mark" href="#all_test_contextafterfn-options" id="all_test_contextafterfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_context_after_fn_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.3.0, v18.13.0</span>
</div>
<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> The hook function. The first argument
to this function is a <a href="#all_test_class-testcontext"><code>TestContext</code></a> object. If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function is used to create a hook that runs after the current test
finishes.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-title function_">async</span> (t) => {
t.<span class="hljs-title function_">after</span>(<span class="hljs-function">(<span class="hljs-params">t</span>) =></span> t.<span class="hljs-title function_">diagnostic</span>(<span class="hljs-string">`finished running <span class="hljs-subst">${t.name}</span>`</span>));
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.afterEach([fn][, options])</code><span><a class="mark" href="#all_test_contextaftereachfn-options" id="all_test_contextaftereachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_context_aftereach_fn_options"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<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> The hook function. The first argument
to this function is a <a href="#all_test_class-testcontext"><code>TestContext</code></a> object. If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function is used to create a hook running
after each subtest of the current test.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-title function_">async</span> (t) => {
t.<span class="hljs-title function_">afterEach</span>(<span class="hljs-function">(<span class="hljs-params">t</span>) =></span> t.<span class="hljs-title function_">diagnostic</span>(<span class="hljs-string">`finished running <span class="hljs-subst">${t.name}</span>`</span>));
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(
<span class="hljs-string">'This is a subtest'</span>,
<span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
},
);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.assert</code><span><a class="mark" href="#all_test_contextassert" id="all_test_contextassert">#</a></span><a aria-hidden="true" class="legacy" id="test_context_assert"></a></h4>
<div class="api_metadata">
<span>Added in: v22.2.0</span>
</div>
<p>An object containing assertion methods bound to <code>context</code>. The top-level
functions from the <code>node:assert</code> module are exposed here for the purpose of
creating test plans.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
t.<span class="hljs-title function_">plan</span>(<span class="hljs-number">1</span>);
t.<span class="hljs-property">assert</span>.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-literal">true</span>, <span class="hljs-literal">true</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.diagnostic(message)</code><span><a class="mark" href="#all_test_contextdiagnosticmessage" id="all_test_contextdiagnosticmessage">#</a></span><a aria-hidden="true" class="legacy" id="test_context_diagnostic_message"></a></h4>
<div class="api_metadata">
<span>Added in: v18.0.0, v16.17.0</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Message to be reported.</li>
</ul>
<p>This function is used to write diagnostics to the output. Any diagnostic
information is included at the end of the test's results. This function does
not return a value.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
t.<span class="hljs-title function_">diagnostic</span>(<span class="hljs-string">'A diagnostic message'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.fullName</code><span><a class="mark" href="#all_test_contextfullname" id="all_test_contextfullname">#</a></span><a aria-hidden="true" class="legacy" id="test_context_fullname"></a></h4>
<div class="api_metadata">
<span>Added in: v20.16.0</span>
</div>
<p>The name of the test and each of its ancestors, separated by <code>></code>.</p>
<h4><code>context.name</code><span><a class="mark" href="#all_test_contextname" id="all_test_contextname">#</a></span><a aria-hidden="true" class="legacy" id="test_context_name"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<p>The name of the test.</p>
<h4><code>context.plan(count)</code><span><a class="mark" href="#all_test_contextplancount" id="all_test_contextplancount">#</a></span><a aria-hidden="true" class="legacy" id="test_context_plan_count"></a></h4>
<div class="api_metadata">
<span>Added in: v20.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of assertions and subtests that are expected to run.</li>
</ul>
<p>This function is used to set the number of assertions and subtests that are expected to run
within the test. If the number of assertions and subtests that run does not match the
expected count, the test will fail.</p>
<blockquote>
<p>Note: To make sure assertions are tracked, <code>t.assert</code> must be used instead of <code>assert</code> directly.</p>
</blockquote>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
t.<span class="hljs-title function_">plan</span>(<span class="hljs-number">2</span>);
t.<span class="hljs-property">assert</span>.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'subtest'</span>, <span class="hljs-function">() =></span> {});
});</code> <button class="copy-button">copy</button></pre>
<p>When working with asynchronous code, the <code>plan</code> function can be used to ensure that the
correct number of assertions are run:</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'planning with streams'</span>, <span class="hljs-function">(<span class="hljs-params">t, done</span>) =></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">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> expected = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>];
t.<span class="hljs-title function_">plan</span>(expected.<span class="hljs-property">length</span>);
<span class="hljs-keyword">const</span> stream = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">generate</span>());
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
t.<span class="hljs-property">assert</span>.<span class="hljs-title function_">strictEqual</span>(chunk, expected.<span class="hljs-title function_">shift</span>());
});
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-title function_">done</span>();
});
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.runOnly(shouldRunOnlyTests)</code><span><a class="mark" href="#all_test_contextrunonlyshouldrunonlytests" id="all_test_contextrunonlyshouldrunonlytests">#</a></span><a aria-hidden="true" class="legacy" id="test_context_runonly_shouldrunonlytests"></a></h4>
<div class="api_metadata">
<span>Added in: v18.0.0, v16.17.0</span>
</div>
<ul>
<li><code>shouldRunOnlyTests</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not to run <code>only</code> tests.</li>
</ul>
<p>If <code>shouldRunOnlyTests</code> is truthy, the test context will only run tests that
have the <code>only</code> option set. Otherwise, all tests are run. If Node.js was not
started with the <a href="#all_cli_--test-only"><code>--test-only</code></a> command-line option, this function is a
no-op.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-comment">// The test context can be set to run subtests with the 'only' option.</span>
t.<span class="hljs-title function_">runOnly</span>(<span class="hljs-literal">true</span>);
<span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([
t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'this subtest is now skipped'</span>),
t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'this subtest is run'</span>, { <span class="hljs-attr">only</span>: <span class="hljs-literal">true</span> }),
]);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.signal</code><span><a class="mark" href="#all_test_contextsignal" id="all_test_contextsignal">#</a></span><a aria-hidden="true" class="legacy" id="test_context_signal"></a></h4>
<div class="api_metadata">
<span>Added in: v18.7.0, v16.17.0</span>
</div>
<ul>
<li>Type: <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a></li>
</ul>
<p>Can be used to abort test subtasks when the test has been aborted.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-title function_">async</span> (t) => {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<span class="hljs-string">'some/uri'</span>, { <span class="hljs-attr">signal</span>: t.<span class="hljs-property">signal</span> });
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.skip([message])</code><span><a class="mark" href="#all_test_contextskipmessage" id="all_test_contextskipmessage">#</a></span><a aria-hidden="true" class="legacy" id="test_context_skip_message"></a></h4>
<div class="api_metadata">
<span>Added in: v18.0.0, v16.17.0</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optional skip message.</li>
</ul>
<p>This function causes the test's output to indicate the test as skipped. If
<code>message</code> is provided, it is included in the output. Calling <code>skip()</code> does
not terminate execution of the test function. This function does not return a
value.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-comment">// Make sure to return here as well if the test contains additional logic.</span>
t.<span class="hljs-title function_">skip</span>(<span class="hljs-string">'this is skipped'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.todo([message])</code><span><a class="mark" href="#all_test_contexttodomessage" id="all_test_contexttodomessage">#</a></span><a aria-hidden="true" class="legacy" id="test_context_todo_message"></a></h4>
<div class="api_metadata">
<span>Added in: v18.0.0, v16.17.0</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optional <code>TODO</code> message.</li>
</ul>
<p>This function adds a <code>TODO</code> directive to the test's output. If <code>message</code> is
provided, it is included in the output. Calling <code>todo()</code> does not terminate
execution of the test function. This function does not return a value.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
<span class="hljs-comment">// This test is marked as `TODO`</span>
t.<span class="hljs-title function_">todo</span>(<span class="hljs-string">'this is a todo'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.test([name][, options][, fn])</code><span><a class="mark" href="#all_test_contexttestname-options-fn" id="all_test_contexttestname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_context_test_name_options_fn"></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.8.0, v16.18.0</td>
<td><p>Add a <code>signal</code> option.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p>Add a <code>timeout</code> option.</p></td></tr>
<tr><td>v18.0.0, v16.17.0</td>
<td><p><span>Added in: v18.0.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the subtest, which is displayed when reporting
test results. <strong>Default:</strong> The <code>name</code> property of <code>fn</code>, or <code>'<anonymous>'</code> if
<code>fn</code> does not have a name.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the subtest. The following
properties are supported:
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <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#Null_type" class="type"><null></a> If a number is provided,
then that many tests would run in parallel within the application thread.
If <code>true</code>, it would run all subtests in parallel.
If <code>false</code>, it would only run one test at a time.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>null</code>.</li>
<li><code>only</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If truthy, and the test context is configured to run
<code>only</code> tests, then this test will be run. Otherwise, the test is skipped.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress test.</li>
<li><code>skip</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#String_type" class="type"><string></a> If truthy, the test is skipped. If a string is
provided, that string is displayed in the test results as the reason for
skipping the test. <strong>Default:</strong> <code>false</code>.</li>
<li><code>todo</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#String_type" class="type"><string></a> If truthy, the test marked as <code>TODO</code>. If a string
is provided, that string is displayed in the test results as the reason why
the test is <code>TODO</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the test will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
<li><code>plan</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of assertions and subtests expected to be run in the test.
If the number of assertions run in the test does not match the number
specified in the plan, the test will fail.
<strong>Default:</strong> <code>undefined</code>.</li>
</ul>
</li>
<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> The function under test. The first argument
to this function is a <a href="#all_test_class-testcontext"><code>TestContext</code></a> object. If the test uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfilled with <code>undefined</code> once the test completes.</li>
</ul>
<p>This function is used to create subtests under the current test. This function
behaves in the same fashion as the top level <a href="#all_test_testname-options-fn"><code>test()</code></a> function.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-title function_">async</span> (t) => {
<span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(
<span class="hljs-string">'This is a subtest'</span>,
{ <span class="hljs-attr">only</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">skip</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">concurrency</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">todo</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">plan</span>: <span class="hljs-number">1</span> },
<span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
t.<span class="hljs-property">assert</span>.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
},
);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>SuiteContext</code><span><a class="mark" href="#all_test_class-suitecontext" id="all_test_class-suitecontext">#</a></span><a aria-hidden="true" class="legacy" id="test_class_suitecontext"></a></h3>
<div class="api_metadata">
<span>Added in: v18.7.0, v16.17.0</span>
</div>
<p>An instance of <code>SuiteContext</code> is passed to each suite function in order to
interact with the test runner. However, the <code>SuiteContext</code> constructor is not
exposed as part of the API.</p>
<h4><code>context.name</code><span><a class="mark" href="#all_test_contextname_1" id="all_test_contextname_1">#</a></span><a aria-hidden="true" class="legacy" id="test_context_name_1"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<p>The name of the suite.</p>
<h4><code>context.signal</code><span><a class="mark" href="#all_test_contextsignal_1" id="all_test_contextsignal_1">#</a></span><a aria-hidden="true" class="legacy" id="test_context_signal_1"></a></h4>
<div class="api_metadata">
<span>Added in: v18.7.0, v16.17.0</span>
</div>
<ul>
<li>Type: <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a></li>
</ul>
<p>Can be used to abort test subtasks when the test has been aborted.</p></section>
</section>
<section><h2>Timers<span><a class="mark" href="#all_timers_timers" id="all_timers_timers">#</a></span><a aria-hidden="true" class="legacy" id="timers_timers"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/timers.js">lib/timers.js</a></p>
<p>The <code>timer</code> module exposes a global API for scheduling functions to
be called at some future period of time. Because the timer functions are
globals, there is no need to call <code>require('node:timers')</code> to use the API.</p>
<p>The timer functions within Node.js implement a similar API as the timers API
provided by Web Browsers but use a different internal implementation that is
built around the Node.js <a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout">Event Loop</a>.</p>
<section><h3>Class: <code>Immediate</code><span><a class="mark" href="#all_timers_class-immediate" id="all_timers_class-immediate">#</a></span><a aria-hidden="true" class="legacy" id="timers_class_immediate"></a></h3>
<p>This object is created internally and is returned from <a href="#all_timers_setimmediatecallback-args"><code>setImmediate()</code></a>. It
can be passed to <a href="#all_timers_clearimmediateimmediate"><code>clearImmediate()</code></a> in order to cancel the scheduled
actions.</p>
<p>By default, when an immediate is scheduled, the Node.js event loop will continue
running as long as the immediate is active. The <code>Immediate</code> object returned by
<a href="#all_timers_setimmediatecallback-args"><code>setImmediate()</code></a> exports both <code>immediate.ref()</code> and <code>immediate.unref()</code>
functions that can be used to control this default behavior.</p>
<h4><code>immediate.hasRef()</code><span><a class="mark" href="#all_timers_immediatehasref" id="all_timers_immediatehasref">#</a></span><a aria-hidden="true" class="legacy" id="timers_immediate_hasref"></a></h4>
<div class="api_metadata">
<span>Added in: v11.0.0</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>If true, the <code>Immediate</code> object will keep the Node.js event loop active.</p>
<h4><code>immediate.ref()</code><span><a class="mark" href="#all_timers_immediateref" id="all_timers_immediateref">#</a></span><a aria-hidden="true" class="legacy" id="timers_immediate_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v9.7.0</span>
</div>
<ul>
<li>Returns: <a href="#all_timers_class-immediate" class="type"><Immediate></a> a reference to <code>immediate</code></li>
</ul>
<p>When called, requests that the Node.js event loop <em>not</em> exit so long as the
<code>Immediate</code> is active. Calling <code>immediate.ref()</code> multiple times will have no
effect.</p>
<p>By default, all <code>Immediate</code> objects are "ref'ed", making it normally unnecessary
to call <code>immediate.ref()</code> unless <code>immediate.unref()</code> had been called previously.</p>
<h4><code>immediate.unref()</code><span><a class="mark" href="#all_timers_immediateunref" id="all_timers_immediateunref">#</a></span><a aria-hidden="true" class="legacy" id="timers_immediate_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v9.7.0</span>
</div>
<ul>
<li>Returns: <a href="#all_timers_class-immediate" class="type"><Immediate></a> a reference to <code>immediate</code></li>
</ul>
<p>When called, the active <code>Immediate</code> object will not require the Node.js event
loop to remain active. If there is no other activity keeping the event loop
running, the process may exit before the <code>Immediate</code> object's callback is
invoked. Calling <code>immediate.unref()</code> multiple times will have no effect.</p>
<h4><code>immediate[Symbol.dispose]()</code><span><a class="mark" href="#all_timers_immediatesymboldispose" id="all_timers_immediatesymboldispose">#</a></span><a aria-hidden="true" class="legacy" id="timers_immediate_symbol_dispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Cancels the immediate. This is similar to calling <code>clearImmediate()</code>.</p>
</section><section><h3>Class: <code>Timeout</code><span><a class="mark" href="#all_timers_class-timeout" id="all_timers_class-timeout">#</a></span><a aria-hidden="true" class="legacy" id="timers_class_timeout"></a></h3>
<p>This object is created internally and is returned from <a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a> and
<a href="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a>. It can be passed to either <a href="#all_timers_cleartimeouttimeout"><code>clearTimeout()</code></a> or
<a href="#all_timers_clearintervaltimeout"><code>clearInterval()</code></a> in order to cancel the scheduled actions.</p>
<p>By default, when a timer is scheduled using either <a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a> or
<a href="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a>, the Node.js event loop will continue running as long as the
timer is active. Each of the <code>Timeout</code> objects returned by these functions
export both <code>timeout.ref()</code> and <code>timeout.unref()</code> functions that can be used to
control this default behavior.</p>
<h4><code>timeout.close()</code><span><a class="mark" href="#all_timers_timeoutclose" id="all_timers_timeoutclose">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_close"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_timers_cleartimeouttimeout"><code>clearTimeout()</code></a> instead.</div><p></p>
<ul>
<li>Returns: <a href="#all_timers_class-timeout" class="type"><Timeout></a> a reference to <code>timeout</code></li>
</ul>
<p>Cancels the timeout.</p>
<h4><code>timeout.hasRef()</code><span><a class="mark" href="#all_timers_timeouthasref" id="all_timers_timeouthasref">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_hasref"></a></h4>
<div class="api_metadata">
<span>Added in: v11.0.0</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>If true, the <code>Timeout</code> object will keep the Node.js event loop active.</p>
<h4><code>timeout.ref()</code><span><a class="mark" href="#all_timers_timeoutref" id="all_timers_timeoutref">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_timers_class-timeout" class="type"><Timeout></a> a reference to <code>timeout</code></li>
</ul>
<p>When called, requests that the Node.js event loop <em>not</em> exit so long as the
<code>Timeout</code> is active. Calling <code>timeout.ref()</code> multiple times will have no effect.</p>
<p>By default, all <code>Timeout</code> objects are "ref'ed", making it normally unnecessary
to call <code>timeout.ref()</code> unless <code>timeout.unref()</code> had been called previously.</p>
<h4><code>timeout.refresh()</code><span><a class="mark" href="#all_timers_timeoutrefresh" id="all_timers_timeoutrefresh">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_refresh"></a></h4>
<div class="api_metadata">
<span>Added in: v10.2.0</span>
</div>
<ul>
<li>Returns: <a href="#all_timers_class-timeout" class="type"><Timeout></a> a reference to <code>timeout</code></li>
</ul>
<p>Sets the timer's start time to the current time, and reschedules the timer to
call its callback at the previously specified duration adjusted to the current
time. This is useful for refreshing a timer without allocating a new
JavaScript object.</p>
<p>Using this on a timer that has already called its callback will reactivate the
timer.</p>
<h4><code>timeout.unref()</code><span><a class="mark" href="#all_timers_timeoutunref" id="all_timers_timeoutunref">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_timers_class-timeout" class="type"><Timeout></a> a reference to <code>timeout</code></li>
</ul>
<p>When called, the active <code>Timeout</code> object will not require the Node.js event loop
to remain active. If there is no other activity keeping the event loop running,
the process may exit before the <code>Timeout</code> object's callback is invoked. Calling
<code>timeout.unref()</code> multiple times will have no effect.</p>
<h4><code>timeout[Symbol.toPrimitive]()</code><span><a class="mark" href="#all_timers_timeoutsymboltoprimitive" id="all_timers_timeoutsymboltoprimitive">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_symbol_toprimitive"></a></h4>
<div class="api_metadata">
<span>Added in: v14.9.0, v12.19.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> a number that can be used to reference this <code>timeout</code></li>
</ul>
<p>Coerce a <code>Timeout</code> to a primitive. The primitive can be used to
clear the <code>Timeout</code>. The primitive can only be used in the
same thread where the timeout was created. Therefore, to use it
across <a href="worker_threads.html"><code>worker_threads</code></a> it must first be passed to the correct
thread. This allows enhanced compatibility with browser
<code>setTimeout()</code> and <code>setInterval()</code> implementations.</p>
<h4><code>timeout[Symbol.dispose]()</code><span><a class="mark" href="#all_timers_timeoutsymboldispose" id="all_timers_timeoutsymboldispose">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_symbol_dispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Cancels the timeout.</p>
</section><section><h3>Scheduling timers<span><a class="mark" href="#all_timers_scheduling-timers" id="all_timers_scheduling-timers">#</a></span><a aria-hidden="true" class="legacy" id="timers_scheduling_timers"></a></h3>
<p>A timer in Node.js is an internal construct that calls a given function after
a certain period of time. When a timer's function is called varies depending on
which method was used to create the timer and what other work the Node.js
event loop is doing.</p>
<h4><code>setImmediate(callback[, ...args])</code><span><a class="mark" href="#all_timers_setimmediatecallback-args" id="all_timers_setimmediatecallback-args">#</a></span><a aria-hidden="true" class="legacy" id="timers_setimmediate_callback_args"></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</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>v0.9.1</td>
<td><p><span>Added in: v0.9.1</span></p></td></tr>
</tbody></table>
</details>
</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> The function to call at the end of this turn of
the Node.js <a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout">Event Loop</a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional arguments to pass when the <code>callback</code> is called.</li>
<li>Returns: <a href="#all_timers_class-immediate" class="type"><Immediate></a> for use with <a href="#all_timers_clearimmediateimmediate"><code>clearImmediate()</code></a></li>
</ul>
<p>Schedules the "immediate" execution of the <code>callback</code> after I/O events'
callbacks.</p>
<p>When multiple calls to <code>setImmediate()</code> are made, the <code>callback</code> functions are
queued for execution in the order in which they are created. The entire callback
queue is processed every event loop iteration. If an immediate timer is queued
from inside an executing callback, that timer will not be triggered until the
next event loop iteration.</p>
<p>If <code>callback</code> is not a function, a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> will be thrown.</p>
<p>This method has a custom variant for promises that is available using
<a href="#all_timers_timerspromisessetimmediatevalue-options"><code>timersPromises.setImmediate()</code></a>.</p>
<h4><code>setInterval(callback[, delay[, ...args]])</code><span><a class="mark" href="#all_timers_setintervalcallback-delay-args" id="all_timers_setintervalcallback-delay-args">#</a></span><a aria-hidden="true" class="legacy" id="timers_setinterval_callback_delay_args"></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</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>v0.0.1</td>
<td><p><span>Added in: v0.0.1</span></p></td></tr>
</tbody></table>
</details>
</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> The function to call when the timer elapses.</li>
<li><code>delay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds to wait before calling the
<code>callback</code>. <strong>Default:</strong> <code>1</code>.</li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional arguments to pass when the <code>callback</code> is called.</li>
<li>Returns: <a href="#all_timers_class-timeout" class="type"><Timeout></a> for use with <a href="#all_timers_clearintervaltimeout"><code>clearInterval()</code></a></li>
</ul>
<p>Schedules repeated execution of <code>callback</code> every <code>delay</code> milliseconds.</p>
<p>When <code>delay</code> is larger than <code>2147483647</code> or less than <code>1</code>, the <code>delay</code> will be
set to <code>1</code>. Non-integer delays are truncated to an integer.</p>
<p>If <code>callback</code> is not a function, a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> will be thrown.</p>
<p>This method has a custom variant for promises that is available using
<a href="#all_timers_timerspromisessetintervaldelay-value-options"><code>timersPromises.setInterval()</code></a>.</p>
<h4><code>setTimeout(callback[, delay[, ...args]])</code><span><a class="mark" href="#all_timers_settimeoutcallback-delay-args" id="all_timers_settimeoutcallback-delay-args">#</a></span><a aria-hidden="true" class="legacy" id="timers_settimeout_callback_delay_args"></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</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>v0.0.1</td>
<td><p><span>Added in: v0.0.1</span></p></td></tr>
</tbody></table>
</details>
</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> The function to call when the timer elapses.</li>
<li><code>delay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds to wait before calling the
<code>callback</code>. <strong>Default:</strong> <code>1</code>.</li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional arguments to pass when the <code>callback</code> is called.</li>
<li>Returns: <a href="#all_timers_class-timeout" class="type"><Timeout></a> for use with <a href="#all_timers_cleartimeouttimeout"><code>clearTimeout()</code></a></li>
</ul>
<p>Schedules execution of a one-time <code>callback</code> after <code>delay</code> milliseconds.</p>
<p>The <code>callback</code> will likely not be invoked in precisely <code>delay</code> milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.</p>
<p>When <code>delay</code> is larger than <code>2147483647</code> or less than <code>1</code>, the <code>delay</code>
will be set to <code>1</code>. Non-integer delays are truncated to an integer.</p>
<p>If <code>callback</code> is not a function, a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> will be thrown.</p>
<p>This method has a custom variant for promises that is available using
<a href="#all_timers_timerspromisessettimeoutdelay-value-options"><code>timersPromises.setTimeout()</code></a>.</p>
</section><section><h3>Cancelling timers<span><a class="mark" href="#all_timers_cancelling-timers" id="all_timers_cancelling-timers">#</a></span><a aria-hidden="true" class="legacy" id="timers_cancelling_timers"></a></h3>
<p>The <a href="#all_timers_setimmediatecallback-args"><code>setImmediate()</code></a>, <a href="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a>, and <a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a> methods
each return objects that represent the scheduled timers. These can be used to
cancel the timer and prevent it from triggering.</p>
<p>For the promisified variants of <a href="#all_timers_setimmediatecallback-args"><code>setImmediate()</code></a> and <a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a>,
an <a href="#all_globals_class-abortcontroller"><code>AbortController</code></a> may be used to cancel the timer. When canceled, the
returned Promises will be rejected with an <code>'AbortError'</code>.</p>
<p>For <code>setImmediate()</code>:</p>
<pre class="with-78-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> { setImmediate <span class="hljs-keyword">as</span> setImmediatePromise } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</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-comment">// We do not `await` the promise so `ac.abort()` is called concurrently.</span>
<span class="hljs-title function_">setImmediatePromise</span>(<span class="hljs-string">'foobar'</span>, { signal })
.<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>)
.<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'The immediate was aborted'</span>);
});
ac.<span class="hljs-title function_">abort</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-attr">setImmediate</span>: setImmediatePromise } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</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_">setImmediatePromise</span>(<span class="hljs-string">'foobar'</span>, { signal })
.<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>)
.<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'The immediate was aborted'</span>);
});
ac.<span class="hljs-title function_">abort</span>();</code><button class="copy-button">copy</button></pre>
<p>For <code>setTimeout()</code>:</p>
<pre class="with-74-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-built_in">setTimeout</span> <span class="hljs-keyword">as</span> setTimeoutPromise } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</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-comment">// We do not `await` the promise so `ac.abort()` is called concurrently.</span>
<span class="hljs-title function_">setTimeoutPromise</span>(<span class="hljs-number">1000</span>, <span class="hljs-string">'foobar'</span>, { signal })
.<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>)
.<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'The timeout was aborted'</span>);
});
ac.<span class="hljs-title function_">abort</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-attr">setTimeout</span>: setTimeoutPromise } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</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_">setTimeoutPromise</span>(<span class="hljs-number">1000</span>, <span class="hljs-string">'foobar'</span>, { signal })
.<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>)
.<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'The timeout was aborted'</span>);
});
ac.<span class="hljs-title function_">abort</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>clearImmediate(immediate)</code><span><a class="mark" href="#all_timers_clearimmediateimmediate" id="all_timers_clearimmediateimmediate">#</a></span><a aria-hidden="true" class="legacy" id="timers_clearimmediate_immediate"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li><code>immediate</code> <a href="#all_timers_class-immediate" class="type"><Immediate></a> An <code>Immediate</code> object as returned by
<a href="#all_timers_setimmediatecallback-args"><code>setImmediate()</code></a>.</li>
</ul>
<p>Cancels an <code>Immediate</code> object created by <a href="#all_timers_setimmediatecallback-args"><code>setImmediate()</code></a>.</p>
<h4><code>clearInterval(timeout)</code><span><a class="mark" href="#all_timers_clearintervaltimeout" id="all_timers_clearintervaltimeout">#</a></span><a aria-hidden="true" class="legacy" id="timers_clearinterval_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>
<ul>
<li><code>timeout</code> <a href="#all_timers_class-timeout" class="type"><Timeout></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#Number_type" class="type"><number></a> A <code>Timeout</code> object as returned by <a href="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a>
or the <a href="#all_timers_timeoutsymboltoprimitive">primitive</a> of the <code>Timeout</code> object as a string or a number.</li>
</ul>
<p>Cancels a <code>Timeout</code> object created by <a href="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a>.</p>
<h4><code>clearTimeout(timeout)</code><span><a class="mark" href="#all_timers_cleartimeouttimeout" id="all_timers_cleartimeouttimeout">#</a></span><a aria-hidden="true" class="legacy" id="timers_cleartimeout_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>
<ul>
<li><code>timeout</code> <a href="#all_timers_class-timeout" class="type"><Timeout></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#Number_type" class="type"><number></a> A <code>Timeout</code> object as returned by <a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a>
or the <a href="#all_timers_timeoutsymboltoprimitive">primitive</a> of the <code>Timeout</code> object as a string or a number.</li>
</ul>
<p>Cancels a <code>Timeout</code> object created by <a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a>.</p>
</section><section><h3>Timers Promises API<span><a class="mark" href="#all_timers_timers-promises-api" id="all_timers_timers-promises-api">#</a></span><a aria-hidden="true" class="legacy" id="timers_timers_promises_api"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Graduated from experimental.</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>
<p>The <code>timers/promises</code> API provides an alternative set of timer functions
that return <code>Promise</code> objects. The API is accessible via
<code>require('node:timers/promises')</code>.</p>
<pre class="with-13-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-built_in">setTimeout</span>,
setImmediate,
<span class="hljs-built_in">setInterval</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
<span class="hljs-built_in">setTimeout</span>,
setImmediate,
<span class="hljs-built_in">setInterval</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>timersPromises.setTimeout([delay[, value[, options]]])</code><span><a class="mark" href="#all_timers_timerspromisessettimeoutdelay-value-options" id="all_timers_timerspromisessettimeoutdelay-value-options">#</a></span><a aria-hidden="true" class="legacy" id="timers_timerspromises_settimeout_delay_value_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>delay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds to wait before fulfilling the
promise. <strong>Default:</strong> <code>1</code>.</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> A value with which the promise is fulfilled.</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>ref</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Set to <code>false</code> to indicate that the scheduled <code>Timeout</code>
should not require the Node.js event loop to remain active.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> An optional <code>AbortSignal</code> that can be used to
cancel the scheduled <code>Timeout</code>.</li>
</ul>
</li>
</ul>
<pre class="with-13-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-built_in">setTimeout</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;
<span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">100</span>, <span class="hljs-string">'result'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res); <span class="hljs-comment">// Prints 'result'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
<span class="hljs-built_in">setTimeout</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">100</span>, <span class="hljs-string">'result'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res); <span class="hljs-comment">// Prints 'result'</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>timersPromises.setImmediate([value[, options]])</code><span><a class="mark" href="#all_timers_timerspromisessetimmediatevalue-options" id="all_timers_timerspromisessetimmediatevalue-options">#</a></span><a aria-hidden="true" class="legacy" id="timers_timerspromises_setimmediate_value_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> A value with which the promise is fulfilled.</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>ref</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Set to <code>false</code> to indicate that the scheduled <code>Immediate</code>
should not require the Node.js event loop to remain active.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> An optional <code>AbortSignal</code> that can be used to
cancel the scheduled <code>Immediate</code>.</li>
</ul>
</li>
</ul>
<pre class="with-15-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> {
setImmediate,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;
<span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> <span class="hljs-title function_">setImmediate</span>(<span class="hljs-string">'result'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res); <span class="hljs-comment">// Prints 'result'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
setImmediate,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-string">'result'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res); <span class="hljs-comment">// Prints 'result'</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>timersPromises.setInterval([delay[, value[, options]]])</code><span><a class="mark" href="#all_timers_timerspromisessetintervaldelay-value-options" id="all_timers_timerspromisessetintervaldelay-value-options">#</a></span><a aria-hidden="true" class="legacy" id="timers_timerspromises_setinterval_delay_value_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0</span>
</div>
<p>Returns an async iterator that generates values in an interval of <code>delay</code> ms.
If <code>ref</code> is <code>true</code>, you need to call <code>next()</code> of async iterator explicitly
or implicitly to keep the event loop alive.</p>
<ul>
<li><code>delay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds to wait between iterations.
<strong>Default:</strong> <code>1</code>.</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> A value with which the iterator returns.</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>ref</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Set to <code>false</code> to indicate that the scheduled <code>Timeout</code>
between iterations should not require the Node.js event loop to
remain active.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> An optional <code>AbortSignal</code> that can be used to
cancel the scheduled <code>Timeout</code> between operations.</li>
</ul>
</li>
</ul>
<pre class="with-14-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-built_in">setInterval</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;
<span class="hljs-keyword">const</span> interval = <span class="hljs-number">100</span>;
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> startTime <span class="hljs-keyword">of</span> <span class="hljs-built_in">setInterval</span>(interval, <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>())) {
<span class="hljs-keyword">const</span> now = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(now);
<span class="hljs-keyword">if</span> ((now - startTime) > <span class="hljs-number">1000</span>)
<span class="hljs-keyword">break</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>());</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
<span class="hljs-built_in">setInterval</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);
<span class="hljs-keyword">const</span> interval = <span class="hljs-number">100</span>;
(<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> startTime <span class="hljs-keyword">of</span> <span class="hljs-built_in">setInterval</span>(interval, <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>())) {
<span class="hljs-keyword">const</span> now = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(now);
<span class="hljs-keyword">if</span> ((now - startTime) > <span class="hljs-number">1000</span>)
<span class="hljs-keyword">break</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>());
})();</code><button class="copy-button">copy</button></pre>
<h4><code>timersPromises.scheduler.wait(delay[, options])</code><span><a class="mark" href="#all_timers_timerspromisesschedulerwaitdelay-options" id="all_timers_timerspromisesschedulerwaitdelay-options">#</a></span><a aria-hidden="true" class="legacy" id="timers_timerspromises_scheduler_wait_delay_options"></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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>delay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds to wait before resolving the
promise.</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>ref</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Set to <code>false</code> to indicate that the scheduled <code>Timeout</code>
should not require the Node.js event loop to remain active.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> An optional <code>AbortSignal</code> that can be used to
cancel waiting.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>An experimental API defined by the <a href="https://github.com/WICG/scheduling-apis">Scheduling APIs</a> draft specification
being developed as a standard Web Platform API.</p>
<p>Calling <code>timersPromises.scheduler.wait(delay, options)</code> is equivalent
to calling <code>timersPromises.setTimeout(delay, undefined, options)</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { scheduler } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;
<span class="hljs-keyword">await</span> scheduler.<span class="hljs-title function_">wait</span>(<span class="hljs-number">1000</span>); <span class="hljs-comment">// Wait one second before continuing</span></code> <button class="copy-button">copy</button></pre>
<h4><code>timersPromises.scheduler.yield()</code><span><a class="mark" href="#all_timers_timerspromisesscheduleryield" id="all_timers_timerspromisesscheduleryield">#</a></span><a aria-hidden="true" class="legacy" id="timers_timerspromises_scheduler_yield"></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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>An experimental API defined by the <a href="https://github.com/WICG/scheduling-apis">Scheduling APIs</a> draft specification
being developed as a standard Web Platform API.</p>
<p>Calling <code>timersPromises.scheduler.yield()</code> is equivalent to calling
<code>timersPromises.setImmediate()</code> with no arguments.</p></section>
</section>
<section><h2>TLS (SSL)<span><a class="mark" href="#all_tls_tls-ssl" id="all_tls_tls-ssl">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_ssl"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/tls.js">lib/tls.js</a></p>
<p>The <code>node:tls</code> module provides an implementation of the Transport Layer Security
(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.
The module can be accessed using:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> tls = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:tls'</span>);</code> <button class="copy-button">copy</button></pre>
<section><h3>Determining if crypto support is unavailable<span><a class="mark" href="#all_tls_determining-if-crypto-support-is-unavailable" id="all_tls_determining-if-crypto-support-is-unavailable">#</a></span><a aria-hidden="true" class="legacy" id="tls_determining_if_crypto_support_is_unavailable"></a></h3>
<p>It is possible for Node.js to be built without including support for the
<code>node:crypto</code> module. In such cases, attempting to <code>import</code> from <code>tls</code> or
calling <code>require('node:tls')</code> will result in an error being thrown.</p>
<p>When using CommonJS, the error thrown can be caught using try/catch:</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">let</span> tls;
<span class="hljs-keyword">try</span> {
tls = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:tls'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'tls support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>When using the lexical ESM <code>import</code> keyword, the error can only be
caught if a handler for <code>process.on('uncaughtException')</code> is registered
<em>before</em> any attempt to load the module is made (using, for instance,
a preload module).</p>
<p>When using ESM, if there is a chance that the code may be run on a build
of Node.js where crypto support is not enabled, consider using the
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import"><code>import()</code></a> function instead of the lexical <code>import</code> keyword:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">let</span> tls;
<span class="hljs-keyword">try</span> {
tls = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:tls'</span>);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'tls support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>TLS/SSL concepts<span><a class="mark" href="#all_tls_tlsssl-concepts" id="all_tls_tlsssl-concepts">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_ssl_concepts"></a></h3>
<p>TLS/SSL is a set of protocols that rely on a public key infrastructure (PKI) to
enable secure communication between a client and a server. For most common
cases, each server must have a private key.</p>
<p>Private keys can be generated in multiple ways. The example below illustrates
use of the OpenSSL command-line interface to generate a 2048-bit RSA private
key:</p>
<pre><code class="language-bash">openssl genrsa -out ryans-key.pem 2048</code> <button class="copy-button">copy</button></pre>
<p>With TLS/SSL, all servers (and some clients) must have a <em>certificate</em>.
Certificates are <em>public keys</em> that correspond to a private key, and that are
digitally signed either by a Certificate Authority or by the owner of the
private key (such certificates are referred to as "self-signed"). The first
step to obtaining a certificate is to create a <em>Certificate Signing Request</em>
(CSR) file.</p>
<p>The OpenSSL command-line interface can be used to generate a CSR for a private
key:</p>
<pre><code class="language-bash">openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem</code> <button class="copy-button">copy</button></pre>
<p>Once the CSR file is generated, it can either be sent to a Certificate
Authority for signing or used to generate a self-signed certificate.</p>
<p>Creating a self-signed certificate using the OpenSSL command-line interface
is illustrated in the example below:</p>
<pre><code class="language-bash">openssl x509 -req -<span class="hljs-keyword">in</span> ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem</code> <button class="copy-button">copy</button></pre>
<p>Once the certificate is generated, it can be used to generate a <code>.pfx</code> or
<code>.p12</code> file:</p>
<pre><code class="language-bash">openssl pkcs12 -<span class="hljs-built_in">export</span> -<span class="hljs-keyword">in</span> ryans-cert.pem -inkey ryans-key.pem \
-certfile ca-cert.pem -out ryans.pfx</code> <button class="copy-button">copy</button></pre>
<p>Where:</p>
<ul>
<li><code>in</code>: is the signed certificate</li>
<li><code>inkey</code>: is the associated private key</li>
<li><code>certfile</code>: is a concatenation of all Certificate Authority (CA) certs into
a single file, e.g. <code>cat ca1-cert.pem ca2-cert.pem > ca-cert.pem</code></li>
</ul>
<h4>Perfect forward secrecy<span><a class="mark" href="#all_tls_perfect-forward-secrecy" id="all_tls_perfect-forward-secrecy">#</a></span><a aria-hidden="true" class="legacy" id="tls_perfect_forward_secrecy"></a></h4>
<p>The term <em><a href="https://en.wikipedia.org/wiki/Perfect_forward_secrecy">forward secrecy</a></em> or <em>perfect forward secrecy</em> describes a feature
of key-agreement (i.e., key-exchange) methods. That is, the server and client
keys are used to negotiate new temporary keys that are used specifically and
only for the current communication session. Practically, this means that even
if the server's private key is compromised, communication can only be decrypted
by eavesdroppers if the attacker manages to obtain the key-pair specifically
generated for the session.</p>
<p>Perfect forward secrecy is achieved by randomly generating a key pair for
key-agreement on every TLS/SSL handshake (in contrast to using the same key for
all sessions). Methods implementing this technique are called "ephemeral".</p>
<p>Currently two methods are commonly used to achieve perfect forward secrecy (note
the character "E" appended to the traditional abbreviations):</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman">ECDHE</a>: An ephemeral version of the Elliptic Curve Diffie-Hellman
key-agreement protocol.</li>
<li><a href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange">DHE</a>: An ephemeral version of the Diffie-Hellman key-agreement protocol.</li>
</ul>
<p>Perfect forward secrecy using ECDHE is enabled by default. The <code>ecdhCurve</code>
option can be used when creating a TLS server to customize the list of supported
ECDH curves to use. See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a> for more info.</p>
<p>DHE is disabled by default but can be enabled alongside ECDHE by setting the
<code>dhparam</code> option to <code>'auto'</code>. Custom DHE parameters are also supported but
discouraged in favor of automatically selected, well-known parameters.</p>
<p>Perfect forward secrecy was optional up to TLSv1.2. As of TLSv1.3, (EC)DHE is
always used (with the exception of PSK-only connections).</p>
<h4>ALPN and SNI<span><a class="mark" href="#all_tls_alpn-and-sni" id="all_tls_alpn-and-sni">#</a></span><a aria-hidden="true" class="legacy" id="tls_alpn_and_sni"></a></h4>
<p>ALPN (Application-Layer Protocol Negotiation Extension) and
SNI (Server Name Indication) are TLS handshake extensions:</p>
<ul>
<li>ALPN: Allows the use of one TLS server for multiple protocols (HTTP, HTTP/2)</li>
<li>SNI: Allows the use of one TLS server for multiple hostnames with different
certificates.</li>
</ul>
<h4>Pre-shared keys<span><a class="mark" href="#all_tls_pre-shared-keys" id="all_tls_pre-shared-keys">#</a></span><a aria-hidden="true" class="legacy" id="tls_pre_shared_keys"></a></h4>
<p>TLS-PSK support is available as an alternative to normal certificate-based
authentication. It uses a pre-shared key instead of certificates to
authenticate a TLS connection, providing mutual authentication.
TLS-PSK and public key infrastructure are not mutually exclusive. Clients and
servers can accommodate both, choosing either of them during the normal cipher
negotiation step.</p>
<p>TLS-PSK is only a good choice where means exist to securely share a
key with every connecting machine, so it does not replace the public key
infrastructure (PKI) for the majority of TLS uses.
The TLS-PSK implementation in OpenSSL has seen many security flaws in
recent years, mostly because it is used only by a minority of applications.
Please consider all alternative solutions before switching to PSK ciphers.
Upon generating PSK it is of critical importance to use sufficient entropy as
discussed in <a href="https://tools.ietf.org/html/rfc4086">RFC 4086</a>. Deriving a shared secret from a password or other
low-entropy sources is not secure.</p>
<p>PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly
specifying a cipher suite with the <code>ciphers</code> option. The list of available
ciphers can be retrieved via <code>openssl ciphers -v 'PSK'</code>. All TLS 1.3
ciphers are eligible for PSK and can be retrieved via
<code>openssl ciphers -v -s -tls1_3 -psk</code>.
On the client connection, a custom <code>checkServerIdentity</code> should be passed
because the default one will fail in the absence of a certificate.</p>
<p>According to the <a href="https://tools.ietf.org/html/rfc4279">RFC 4279</a>, PSK identities up to 128 bytes in length and
PSKs up to 64 bytes in length must be supported. As of OpenSSL 1.1.0
maximum identity size is 128 bytes, and maximum PSK length is 256 bytes.</p>
<p>The current implementation doesn't support asynchronous PSK callbacks due to the
limitations of the underlying OpenSSL API.</p>
<p>To use TLS-PSK, client and server must specify the <code>pskCallback</code> option,
a function that returns the PSK to use (which must be compatible with
the selected cipher's digest).</p>
<p>It will be called first on the client:</p>
<ul>
<li>hint: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> optional message sent from the server to help the client
decide which identity to use during negotiation.
Always <code>null</code> if TLS 1.3 is used.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> in the form
<code>{ psk: <Buffer|TypedArray|DataView>, identity: <string> }</code> or <code>null</code>.</li>
</ul>
<p>Then on the server:</p>
<ul>
<li>socket: <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a> the server socket instance, equivalent to <code>this</code>.</li>
<li>identity: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> identity parameter sent from the client.</li>
<li>Returns: <a href="#all_buffer_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> the PSK (or <code>null</code>).</li>
</ul>
<p>A return value of <code>null</code> stops the negotiation process and sends an
<code>unknown_psk_identity</code> alert message to the other party.
If the server wishes to hide the fact that the PSK identity was not known,
the callback must provide some random data as <code>psk</code> to make the connection
fail with <code>decrypt_error</code> before negotiation is finished.</p>
<h4>Client-initiated renegotiation attack mitigation<span><a class="mark" href="#all_tls_client-initiated-renegotiation-attack-mitigation" id="all_tls_client-initiated-renegotiation-attack-mitigation">#</a></span><a aria-hidden="true" class="legacy" id="tls_client_initiated_renegotiation_attack_mitigation"></a></h4>
<p>The TLS protocol allows clients to renegotiate certain aspects of the TLS
session. Unfortunately, session renegotiation requires a disproportionate amount
of server-side resources, making it a potential vector for denial-of-service
attacks.</p>
<p>To mitigate the risk, renegotiation is limited to three times every ten minutes.
An <code>'error'</code> event is emitted on the <a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a> instance when this
threshold is exceeded. The limits are configurable:</p>
<ul>
<li><code>tls.CLIENT_RENEG_LIMIT</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the number of renegotiation
requests. <strong>Default:</strong> <code>3</code>.</li>
<li><code>tls.CLIENT_RENEG_WINDOW</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the time renegotiation window
in seconds. <strong>Default:</strong> <code>600</code> (10 minutes).</li>
</ul>
<p>The default renegotiation limits should not be modified without a full
understanding of the implications and risks.</p>
<p>TLSv1.3 does not support renegotiation.</p>
<h4>Session resumption<span><a class="mark" href="#all_tls_session-resumption" id="all_tls_session-resumption">#</a></span><a aria-hidden="true" class="legacy" id="tls_session_resumption"></a></h4>
<p>Establishing a TLS session can be relatively slow. The process can be sped
up by saving and later reusing the session state. There are several mechanisms
to do so, discussed here from oldest to newest (and preferred).</p>
<h5>Session identifiers<span><a class="mark" href="#all_tls_session-identifiers" id="all_tls_session-identifiers">#</a></span><a aria-hidden="true" class="legacy" id="tls_session_identifiers"></a></h5>
<p>Servers generate a unique ID for new connections and
send it to the client. Clients and servers save the session state. When
reconnecting, clients send the ID of their saved session state and if the server
also has the state for that ID, it can agree to use it. Otherwise, the server
will create a new session. See <a href="https://www.ietf.org/rfc/rfc2246.txt">RFC 2246</a> for more information, page 23 and
30.</p>
<p>Resumption using session identifiers is supported by most web browsers when
making HTTPS requests.</p>
<p>For Node.js, clients wait for the <a href="#all_tls_event-session"><code>'session'</code></a> event to get the session data,
and provide the data to the <code>session</code> option of a subsequent <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>
to reuse the session. Servers must
implement handlers for the <a href="#all_tls_event-newsession"><code>'newSession'</code></a> and <a href="#all_tls_event-resumesession"><code>'resumeSession'</code></a> events
to save and restore the session data using the session ID as the lookup key to
reuse sessions. To reuse sessions across load balancers or cluster workers,
servers must use a shared session cache (such as Redis) in their session
handlers.</p>
<h5>Session tickets<span><a class="mark" href="#all_tls_session-tickets" id="all_tls_session-tickets">#</a></span><a aria-hidden="true" class="legacy" id="tls_session_tickets"></a></h5>
<p>The servers encrypt the entire session state and send it
to the client as a "ticket". When reconnecting, the state is sent to the server
in the initial connection. This mechanism avoids the need for a server-side
session cache. If the server doesn't use the ticket, for any reason (failure
to decrypt it, it's too old, etc.), it will create a new session and send a new
ticket. See <a href="https://tools.ietf.org/html/rfc5077">RFC 5077</a> for more information.</p>
<p>Resumption using session tickets is becoming commonly supported by many web
browsers when making HTTPS requests.</p>
<p>For Node.js, clients use the same APIs for resumption with session identifiers
as for resumption with session tickets. For debugging, if
<a href="#all_tls_tlssocketgettlsticket"><code>tls.TLSSocket.getTLSTicket()</code></a> returns a value, the session data contains a
ticket, otherwise it contains client-side session state.</p>
<p>With TLSv1.3, be aware that multiple tickets may be sent by the server,
resulting in multiple <code>'session'</code> events, see <a href="#all_tls_event-session"><code>'session'</code></a> for more
information.</p>
<p>Single process servers need no specific implementation to use session tickets.
To use session tickets across server restarts or load balancers, servers must
all have the same ticket keys. There are three 16-byte keys internally, but the
tls API exposes them as a single 48-byte buffer for convenience.</p>
<p>It's possible to get the ticket keys by calling <a href="#all_tls_servergetticketkeys"><code>server.getTicketKeys()</code></a> on
one server instance and then distribute them, but it is more reasonable to
securely generate 48 bytes of secure random data and set them with the
<code>ticketKeys</code> option of <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a>. The keys should be regularly
regenerated and server's keys can be reset with
<a href="#all_tls_serversetticketkeyskeys"><code>server.setTicketKeys()</code></a>.</p>
<p>Session ticket keys are cryptographic keys, and they <em><strong>must be stored
securely</strong></em>. With TLS 1.2 and below, if they are compromised all sessions that
used tickets encrypted with them can be decrypted. They should not be stored
on disk, and they should be regenerated regularly.</p>
<p>If clients advertise support for tickets, the server will send them. The
server can disable tickets by supplying
<code>require('node:constants').SSL_OP_NO_TICKET</code> in <code>secureOptions</code>.</p>
<p>Both session identifiers and session tickets timeout, causing the server to
create new sessions. The timeout can be configured with the <code>sessionTimeout</code>
option of <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a>.</p>
<p>For all the mechanisms, when resumption fails, servers will create new sessions.
Since failing to resume the session does not cause TLS/HTTPS connection
failures, it is easy to not notice unnecessarily poor TLS performance. The
OpenSSL CLI can be used to verify that servers are resuming sessions. Use the
<code>-reconnect</code> option to <code>openssl s_client</code>, for example:</p>
<pre><code class="language-bash">openssl s_client -connect localhost:443 -reconnect</code> <button class="copy-button">copy</button></pre>
<p>Read through the debug output. The first connection should say "New", for
example:</p>
<pre><code class="language-text">New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256</code> <button class="copy-button">copy</button></pre>
<p>Subsequent connections should say "Reused", for example:</p>
<pre><code class="language-text">Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Modifying the default TLS cipher suite<span><a class="mark" href="#all_tls_modifying-the-default-tls-cipher-suite" id="all_tls_modifying-the-default-tls-cipher-suite">#</a></span><a aria-hidden="true" class="legacy" id="tls_modifying_the_default_tls_cipher_suite"></a></h3>
<p>Node.js is built with a default suite of enabled and disabled TLS ciphers. This
default cipher list can be configured when building Node.js to allow
distributions to provide their own default list.</p>
<p>The following command can be used to show the default cipher suite:</p>
<pre><code class="language-console">node -p crypto.constants.defaultCoreCipherList | tr ':' '\n'
TLS_AES_256_GCM_SHA384
TLS_CHACHA20_POLY1305_SHA256
TLS_AES_128_GCM_SHA256
ECDHE-RSA-AES128-GCM-SHA256
ECDHE-ECDSA-AES128-GCM-SHA256
ECDHE-RSA-AES256-GCM-SHA384
ECDHE-ECDSA-AES256-GCM-SHA384
DHE-RSA-AES128-GCM-SHA256
ECDHE-RSA-AES128-SHA256
DHE-RSA-AES128-SHA256
ECDHE-RSA-AES256-SHA384
DHE-RSA-AES256-SHA384
ECDHE-RSA-AES256-SHA256
DHE-RSA-AES256-SHA256
HIGH
!aNULL
!eNULL
!EXPORT
!DES
!RC4
!MD5
!PSK
!SRP
!CAMELLIA</code> <button class="copy-button">copy</button></pre>
<p>This default can be replaced entirely using the <a href="#all_cli_--tls-cipher-listlist"><code>--tls-cipher-list</code></a>
command-line switch (directly, or via the <a href="#all_cli_node_optionsoptions"><code>NODE_OPTIONS</code></a> environment
variable). For instance, the following makes <code>ECDHE-RSA-AES128-GCM-SHA256:!RC4</code>
the default TLS cipher suite:</p>
<pre><code class="language-bash">node --tls-cipher-list=<span class="hljs-string">'ECDHE-RSA-AES128-GCM-SHA256:!RC4'</span> server.js
<span class="hljs-built_in">export</span> NODE_OPTIONS=--tls-cipher-list=<span class="hljs-string">'ECDHE-RSA-AES128-GCM-SHA256:!RC4'</span>
node server.js</code> <button class="copy-button">copy</button></pre>
<p>To verify, use the following command to show the set cipher list, note the
difference between <code>defaultCoreCipherList</code> and <code>defaultCipherList</code>:</p>
<pre><code class="language-bash">node --tls-cipher-list=<span class="hljs-string">'ECDHE-RSA-AES128-GCM-SHA256:!RC4'</span> -p crypto.constants.defaultCipherList | <span class="hljs-built_in">tr</span> <span class="hljs-string">':'</span> <span class="hljs-string">'\n'</span>
ECDHE-RSA-AES128-GCM-SHA256
!RC4</code> <button class="copy-button">copy</button></pre>
<p>i.e. the <code>defaultCoreCipherList</code> list is set at compilation time and the
<code>defaultCipherList</code> is set at runtime.</p>
<p>To modify the default cipher suites from within the runtime, modify the
<code>tls.DEFAULT_CIPHERS</code> variable, this must be performed before listening on any
sockets, it will not affect sockets already opened. For example:</p>
<pre><code class="language-js"><span class="hljs-comment">// Remove Obsolete CBC Ciphers and RSA Key Exchange based Ciphers as they don't provide Forward Secrecy</span>
tls.<span class="hljs-property">DEFAULT_CIPHERS</span> +=
<span class="hljs-string">':!ECDHE-RSA-AES128-SHA:!ECDHE-RSA-AES128-SHA256:!ECDHE-RSA-AES256-SHA:!ECDHE-RSA-AES256-SHA384'</span> +
<span class="hljs-string">':!ECDHE-ECDSA-AES128-SHA:!ECDHE-ECDSA-AES128-SHA256:!ECDHE-ECDSA-AES256-SHA:!ECDHE-ECDSA-AES256-SHA384'</span> +
<span class="hljs-string">':!kRSA'</span>;</code> <button class="copy-button">copy</button></pre>
<p>The default can also be replaced on a per client or server basis using the
<code>ciphers</code> option from <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>, which is also available
in <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a>, <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>, and when creating new
<a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a>s.</p>
<p>The ciphers list can contain a mixture of TLSv1.3 cipher suite names, the ones
that start with <code>'TLS_'</code>, and specifications for TLSv1.2 and below cipher
suites. The TLSv1.2 ciphers support a legacy specification format, consult
the OpenSSL <a href="https://www.openssl.org/docs/man1.1.1/man1/ciphers.html#CIPHER-LIST-FORMAT">cipher list format</a> documentation for details, but those
specifications do <em>not</em> apply to TLSv1.3 ciphers. The TLSv1.3 suites can only
be enabled by including their full name in the cipher list. They cannot, for
example, be enabled or disabled by using the legacy TLSv1.2 <code>'EECDH'</code> or
<code>'!EECDH'</code> specification.</p>
<p>Despite the relative order of TLSv1.3 and TLSv1.2 cipher suites, the TLSv1.3
protocol is significantly more secure than TLSv1.2, and will always be chosen
over TLSv1.2 if the handshake indicates it is supported, and if any TLSv1.3
cipher suites are enabled.</p>
<p>The default cipher suite included within Node.js has been carefully
selected to reflect current security best practices and risk mitigation.
Changing the default cipher suite can have a significant impact on the security
of an application. The <code>--tls-cipher-list</code> switch and <code>ciphers</code> option should by
used only if absolutely necessary.</p>
<p>The default cipher suite prefers GCM ciphers for <a href="https://www.chromium.org/Home/chromium-security/education/tls#TOC-Cipher-Suites">Chrome's 'modern
cryptography' setting</a> and also prefers ECDHE and DHE ciphers for perfect
forward secrecy, while offering <em>some</em> backward compatibility.</p>
<p>Old clients that rely on insecure and deprecated RC4 or DES-based ciphers
(like Internet Explorer 6) cannot complete the handshaking process with
the default configuration. If these clients <em>must</em> be supported, the
<a href="https://wiki.mozilla.org/Security/Server_Side_TLS">TLS recommendations</a> may offer a compatible cipher suite. For more details
on the format, see the OpenSSL <a href="https://www.openssl.org/docs/man1.1.1/man1/ciphers.html#CIPHER-LIST-FORMAT">cipher list format</a> documentation.</p>
<p>There are only five TLSv1.3 cipher suites:</p>
<ul>
<li><code>'TLS_AES_256_GCM_SHA384'</code></li>
<li><code>'TLS_CHACHA20_POLY1305_SHA256'</code></li>
<li><code>'TLS_AES_128_GCM_SHA256'</code></li>
<li><code>'TLS_AES_128_CCM_SHA256'</code></li>
<li><code>'TLS_AES_128_CCM_8_SHA256'</code></li>
</ul>
<p>The first three are enabled by default. The two <code>CCM</code>-based suites are supported
by TLSv1.3 because they may be more performant on constrained systems, but they
are not enabled by default since they offer less security.</p>
</section><section><h3>X509 certificate error codes<span><a class="mark" href="#all_tls_x509-certificate-error-codes" id="all_tls_x509-certificate-error-codes">#</a></span><a aria-hidden="true" class="legacy" id="tls_x509_certificate_error_codes"></a></h3>
<p>Multiple functions can fail due to certificate errors that are reported by
OpenSSL. In such a case, the function provides an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> via its callback that
has the property <code>code</code> which can take one of the following values:</p>
<!--
values are taken from src/crypto/crypto_common.cc
description are taken from deps/openssl/openssl/crypto/x509/x509_txt.c
-->
<ul>
<li><code>'UNABLE_TO_GET_ISSUER_CERT'</code>: Unable to get issuer certificate.</li>
<li><code>'UNABLE_TO_GET_CRL'</code>: Unable to get certificate CRL.</li>
<li><code>'UNABLE_TO_DECRYPT_CERT_SIGNATURE'</code>: Unable to decrypt certificate's
signature.</li>
<li><code>'UNABLE_TO_DECRYPT_CRL_SIGNATURE'</code>: Unable to decrypt CRL's signature.</li>
<li><code>'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY'</code>: Unable to decode issuer public key.</li>
<li><code>'CERT_SIGNATURE_FAILURE'</code>: Certificate signature failure.</li>
<li><code>'CRL_SIGNATURE_FAILURE'</code>: CRL signature failure.</li>
<li><code>'CERT_NOT_YET_VALID'</code>: Certificate is not yet valid.</li>
<li><code>'CERT_HAS_EXPIRED'</code>: Certificate has expired.</li>
<li><code>'CRL_NOT_YET_VALID'</code>: CRL is not yet valid.</li>
<li><code>'CRL_HAS_EXPIRED'</code>: CRL has expired.</li>
<li><code>'ERROR_IN_CERT_NOT_BEFORE_FIELD'</code>: Format error in certificate's notBefore
field.</li>
<li><code>'ERROR_IN_CERT_NOT_AFTER_FIELD'</code>: Format error in certificate's notAfter
field.</li>
<li><code>'ERROR_IN_CRL_LAST_UPDATE_FIELD'</code>: Format error in CRL's lastUpdate field.</li>
<li><code>'ERROR_IN_CRL_NEXT_UPDATE_FIELD'</code>: Format error in CRL's nextUpdate field.</li>
<li><code>'OUT_OF_MEM'</code>: Out of memory.</li>
<li><code>'DEPTH_ZERO_SELF_SIGNED_CERT'</code>: Self signed certificate.</li>
<li><code>'SELF_SIGNED_CERT_IN_CHAIN'</code>: Self signed certificate in certificate chain.</li>
<li><code>'UNABLE_TO_GET_ISSUER_CERT_LOCALLY'</code>: Unable to get local issuer certificate.</li>
<li><code>'UNABLE_TO_VERIFY_LEAF_SIGNATURE'</code>: Unable to verify the first certificate.</li>
<li><code>'CERT_CHAIN_TOO_LONG'</code>: Certificate chain too long.</li>
<li><code>'CERT_REVOKED'</code>: Certificate revoked.</li>
<li><code>'INVALID_CA'</code>: Invalid CA certificate.</li>
<li><code>'PATH_LENGTH_EXCEEDED'</code>: Path length constraint exceeded.</li>
<li><code>'INVALID_PURPOSE'</code>: Unsupported certificate purpose.</li>
<li><code>'CERT_UNTRUSTED'</code>: Certificate not trusted.</li>
<li><code>'CERT_REJECTED'</code>: Certificate rejected.</li>
<li><code>'HOSTNAME_MISMATCH'</code>: Hostname mismatch.</li>
</ul>
</section><section><h3>Class: <code>tls.CryptoStream</code><span><a class="mark" href="#all_tls_class-tlscryptostream" id="all_tls_class-tlscryptostream">#</a></span><a aria-hidden="true" class="legacy" id="tls_class_tls_cryptostream"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span><span>Deprecated since: v0.11.3</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a> instead.</div><p></p>
<p>The <code>tls.CryptoStream</code> class represents a stream of encrypted data. This class
is deprecated and should no longer be used.</p>
<h4><code>cryptoStream.bytesWritten</code><span><a class="mark" href="#all_tls_cryptostreambyteswritten" id="all_tls_cryptostreambyteswritten">#</a></span><a aria-hidden="true" class="legacy" id="tls_cryptostream_byteswritten"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.4</span><span>Deprecated since: v0.11.3</span>
</div>
<p>The <code>cryptoStream.bytesWritten</code> property returns the total number of bytes
written to the underlying socket <em>including</em> the bytes required for the
implementation of the TLS protocol.</p>
</section><section><h3>Class: <code>tls.SecurePair</code><span><a class="mark" href="#all_tls_class-tlssecurepair" id="all_tls_class-tlssecurepair">#</a></span><a aria-hidden="true" class="legacy" id="tls_class_tls_securepair"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.2</span><span>Deprecated since: v0.11.3</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a> instead.</div><p></p>
<p>Returned by <a href="#all_tls_tlscreatesecurepaircontext-isserver-requestcert-rejectunauthorized-options"><code>tls.createSecurePair()</code></a>.</p>
<h4>Event: <code>'secure'</code><span><a class="mark" href="#all_tls_event-secure" id="all_tls_event-secure">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_secure"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.2</span><span>Deprecated since: v0.11.3</span>
</div>
<p>The <code>'secure'</code> event is emitted by the <code>SecurePair</code> object once a secure
connection has been established.</p>
<p>As with checking for the server
<a href="#all_tls_event-secureconnection"><code>'secureConnection'</code></a>
event, <code>pair.cleartext.authorized</code> should be inspected to confirm whether the
certificate used is properly authorized.</p>
</section><section><h3>Class: <code>tls.Server</code><span><a class="mark" href="#all_tls_class-tlsserver" id="all_tls_class-tlsserver">#</a></span><a aria-hidden="true" class="legacy" id="tls_class_tls_server"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div>
<ul>
<li>Extends: <a href="#all_net_class-netserver" class="type"><net.Server></a></li>
</ul>
<p>Accepts encrypted connections using TLS or SSL.</p>
<h4>Event: <code>'connection'</code><span><a class="mark" href="#all_tls_event-connection" id="all_tls_event-connection">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>This event is emitted when a new TCP stream is established, before the TLS
handshake begins. <code>socket</code> is typically an object of type <a href="#all_net_class-netsocket"><code>net.Socket</code></a> but
will not receive events unlike the socket created from the <a href="#all_net_class-netserver"><code>net.Server</code></a>
<code>'connection'</code> event. Usually users will not want to access this event.</p>
<p>This event can also be explicitly emitted by users to inject connections
into the TLS server. In that case, any <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> stream can be passed.</p>
<h4>Event: <code>'keylog'</code><span><a class="mark" href="#all_tls_event-keylog" id="all_tls_event-keylog">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_keylog"></a></h4>
<div class="api_metadata">
<span>Added in: v12.3.0, v10.20.0</span>
</div>
<ul>
<li><code>line</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> Line of ASCII text, in NSS <code>SSLKEYLOGFILE</code> format.</li>
<li><code>tlsSocket</code> <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a> The <code>tls.TLSSocket</code> instance on which it was
generated.</li>
</ul>
<p>The <code>keylog</code> event is emitted when key material is generated or received by
a connection to this server (typically before handshake has completed, but not
necessarily). This keying material can be stored for debugging, as it allows
captured TLS traffic to be decrypted. It may be emitted multiple times for
each socket.</p>
<p>A typical use case is to append received lines to a common text file, which
is later used by software (such as Wireshark) to decrypt the traffic:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> logFile = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'/tmp/ssl-keys.log'</span>, { <span class="hljs-attr">flags</span>: <span class="hljs-string">'a'</span> });
<span class="hljs-comment">// ...</span>
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'keylog'</span>, <span class="hljs-function">(<span class="hljs-params">line, tlsSocket</span>) =></span> {
<span class="hljs-keyword">if</span> (tlsSocket.<span class="hljs-property">remoteAddress</span> !== <span class="hljs-string">'...'</span>)
<span class="hljs-keyword">return</span>; <span class="hljs-comment">// Only log keys for a particular IP</span>
logFile.<span class="hljs-title function_">write</span>(line);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'newSession'</code><span><a class="mark" href="#all_tls_event-newsession" id="all_tls_event-newsession">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_newsession"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v0.11.12</td>
<td><p>The <code>callback</code> argument is now supported.</p></td></tr>
<tr><td>v0.9.2</td>
<td><p><span>Added in: v0.9.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>'newSession'</code> event is emitted upon creation of a new TLS session. This may
be used to store sessions in external storage. The data should be provided to
the <a href="#all_tls_event-resumesession"><code>'resumeSession'</code></a> callback.</p>
<p>The listener callback is passed three arguments when called:</p>
<ul>
<li><code>sessionId</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The TLS session identifier</li>
<li><code>sessionData</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The TLS session data</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 taking no arguments that must be
invoked in order for data to be sent or received over the secure connection.</li>
</ul>
<p>Listening for this event will have an effect only on connections established
after the addition of the event listener.</p>
<h4>Event: <code>'OCSPRequest'</code><span><a class="mark" href="#all_tls_event-ocsprequest" id="all_tls_event-ocsprequest">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_ocsprequest"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div>
<p>The <code>'OCSPRequest'</code> event is emitted when the client sends a certificate status
request. The listener callback is passed three arguments when called:</p>
<ul>
<li><code>certificate</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The server certificate</li>
<li><code>issuer</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The issuer's certificate</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 must be invoked to provide
the results of the OCSP request.</li>
</ul>
<p>The server's current certificate can be parsed to obtain the OCSP URL
and certificate ID; after obtaining an OCSP response, <code>callback(null, resp)</code> is
then invoked, where <code>resp</code> is a <code>Buffer</code> instance containing the OCSP response.
Both <code>certificate</code> and <code>issuer</code> are <code>Buffer</code> DER-representations of the
primary and issuer's certificates. These can be used to obtain the OCSP
certificate ID and OCSP endpoint URL.</p>
<p>Alternatively, <code>callback(null, null)</code> may be called, indicating that there was
no OCSP response.</p>
<p>Calling <code>callback(err)</code> will result in a <code>socket.destroy(err)</code> call.</p>
<p>The typical flow of an OCSP request is as follows:</p>
<ol>
<li>Client connects to the server and sends an <code>'OCSPRequest'</code> (via the status
info extension in ClientHello).</li>
<li>Server receives the request and emits the <code>'OCSPRequest'</code> event, calling the
listener if registered.</li>
<li>Server extracts the OCSP URL from either the <code>certificate</code> or <code>issuer</code> and
performs an <a href="https://en.wikipedia.org/wiki/OCSP_stapling">OCSP request</a> to the CA.</li>
<li>Server receives <code>'OCSPResponse'</code> from the CA and sends it back to the client
via the <code>callback</code> argument</li>
<li>Client validates the response and either destroys the socket or performs a
handshake.</li>
</ol>
<p>The <code>issuer</code> can be <code>null</code> if the certificate is either self-signed or the
issuer is not in the root certificates list. (An issuer may be provided
via the <code>ca</code> option when establishing the TLS connection.)</p>
<p>Listening for this event will have an effect only on connections established
after the addition of the event listener.</p>
<p>An npm module like <a href="https://www.npmjs.com/package/asn1.js">asn1.js</a> may be used to parse the certificates.</p>
<h4>Event: <code>'resumeSession'</code><span><a class="mark" href="#all_tls_event-resumesession" id="all_tls_event-resumesession">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_resumesession"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.2</span>
</div>
<p>The <code>'resumeSession'</code> event is emitted when the client requests to resume a
previous TLS session. The listener callback is passed two arguments when
called:</p>
<ul>
<li><code>sessionId</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The TLS session identifier</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 to be called when the prior session
has been recovered: <code>callback([err[, sessionData]])</code>
<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>sessionData</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
</li>
</ul>
<p>The event listener should perform a lookup in external storage for the
<code>sessionData</code> saved by the <a href="#all_tls_event-newsession"><code>'newSession'</code></a> event handler using the given
<code>sessionId</code>. If found, call <code>callback(null, sessionData)</code> to resume the session.
If not found, the session cannot be resumed. <code>callback()</code> must be called
without <code>sessionData</code> so that the handshake can continue and a new session can
be created. It is possible to call <code>callback(err)</code> to terminate the incoming
connection and destroy the socket.</p>
<p>Listening for this event will have an effect only on connections established
after the addition of the event listener.</p>
<p>The following illustrates resuming a TLS session:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> tlsSessionStore = {};
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'newSession'</span>, <span class="hljs-function">(<span class="hljs-params">id, data, cb</span>) =></span> {
tlsSessionStore[id.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)] = data;
<span class="hljs-title function_">cb</span>();
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'resumeSession'</span>, <span class="hljs-function">(<span class="hljs-params">id, cb</span>) =></span> {
<span class="hljs-title function_">cb</span>(<span class="hljs-literal">null</span>, tlsSessionStore[id.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)] || <span class="hljs-literal">null</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'secureConnection'</code><span><a class="mark" href="#all_tls_event-secureconnection" id="all_tls_event-secureconnection">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_secureconnection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div>
<p>The <code>'secureConnection'</code> event is emitted after the handshaking process for a
new connection has successfully completed. The listener callback is passed a
single argument when called:</p>
<ul>
<li><code>tlsSocket</code> <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a> The established TLS socket.</li>
</ul>
<p>The <code>tlsSocket.authorized</code> property is a <code>boolean</code> indicating whether the
client has been verified by one of the supplied Certificate Authorities for the
server. If <code>tlsSocket.authorized</code> is <code>false</code>, then <code>socket.authorizationError</code>
is set to describe how authorization failed. Depending on the settings
of the TLS server, unauthorized connections may still be accepted.</p>
<p>The <code>tlsSocket.alpnProtocol</code> property is a string that contains the selected
ALPN protocol. When ALPN has no selected protocol because the client or the
server did not send an ALPN extension, <code>tlsSocket.alpnProtocol</code> equals <code>false</code>.</p>
<p>The <code>tlsSocket.servername</code> property is a string containing the server name
requested via SNI.</p>
<h4>Event: <code>'tlsClientError'</code><span><a class="mark" href="#all_tls_event-tlsclienterror" id="all_tls_event-tlsclienterror">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_tlsclienterror"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<p>The <code>'tlsClientError'</code> event is emitted when an error occurs before a secure
connection is established. The listener callback is passed two arguments when
called:</p>
<ul>
<li><code>exception</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The <code>Error</code> object describing the error</li>
<li><code>tlsSocket</code> <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a> The <code>tls.TLSSocket</code> instance from which the
error originated.</li>
</ul>
<h4><code>server.addContext(hostname, context)</code><span><a class="mark" href="#all_tls_serveraddcontexthostname-context" id="all_tls_serveraddcontexthostname-context">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_addcontext_hostname_context"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.3</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A SNI host name or wildcard (e.g. <code>'*'</code>)</li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="#all_tls_tlscreatesecurecontextoptions" class="type"><tls.SecureContext></a> An object containing any of the possible
properties from the <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> <code>options</code> arguments
(e.g. <code>key</code>, <code>cert</code>, <code>ca</code>, etc), or a TLS context object created with
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> itself.</li>
</ul>
<p>The <code>server.addContext()</code> method adds a secure context that will be used if
the client request's SNI name matches the supplied <code>hostname</code> (or wildcard).</p>
<p>When there are multiple matching contexts, the most recently added one is
used.</p>
<h4><code>server.address()</code><span><a class="mark" href="#all_tls_serveraddress" id="all_tls_serveraddress">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_address"></a></h4>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns the bound address, the address family name, and port of the
server as reported by the operating system. See <a href="#all_net_serveraddress"><code>net.Server.address()</code></a> for
more information.</p>
<h4><code>server.close([callback])</code><span><a class="mark" href="#all_tls_serverclosecallback" id="all_tls_serverclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_close_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.2</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> A listener callback that will be registered to listen
for the server instance's <code>'close'</code> event.</li>
<li>Returns: <a href="#all_tls_class-tlsserver" class="type"><tls.Server></a></li>
</ul>
<p>The <code>server.close()</code> method stops the server from accepting new connections.</p>
<p>This function operates asynchronously. The <code>'close'</code> event will be emitted
when the server has no more open connections.</p>
<h4><code>server.getTicketKeys()</code><span><a class="mark" href="#all_tls_servergetticketkeys" id="all_tls_servergetticketkeys">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_getticketkeys"></a></h4>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> A 48-byte buffer containing the session ticket keys.</li>
</ul>
<p>Returns the session ticket keys.</p>
<p>See <a href="#all_tls_session-resumption">Session Resumption</a> for more information.</p>
<h4><code>server.listen()</code><span><a class="mark" href="#all_tls_serverlisten" id="all_tls_serverlisten">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_listen"></a></h4>
<p>Starts the server listening for encrypted connections.
This method is identical to <a href="#all_net_serverlisten"><code>server.listen()</code></a> from <a href="#all_net_class-netserver"><code>net.Server</code></a>.</p>
<h4><code>server.setSecureContext(options)</code><span><a class="mark" href="#all_tls_serversetsecurecontextoptions" id="all_tls_serversetsecurecontextoptions">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_setsecurecontext_options"></a></h4>
<div class="api_metadata">
<span>Added in: v11.0.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> An object containing any of the possible properties from
the <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> <code>options</code> arguments (e.g. <code>key</code>, <code>cert</code>,
<code>ca</code>, etc).</li>
</ul>
<p>The <code>server.setSecureContext()</code> method replaces the secure context of an
existing server. Existing connections to the server are not interrupted.</p>
<h4><code>server.setTicketKeys(keys)</code><span><a class="mark" href="#all_tls_serversetticketkeyskeys" id="all_tls_serversetticketkeyskeys">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_setticketkeys_keys"></a></h4>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div>
<ul>
<li><code>keys</code> <a href="#all_buffer_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 48-byte buffer containing the session
ticket keys.</li>
</ul>
<p>Sets the session ticket keys.</p>
<p>Changes to the ticket keys are effective only for future server connections.
Existing or currently pending server connections will use the previous keys.</p>
<p>See <a href="#all_tls_session-resumption">Session Resumption</a> for more information.</p>
</section><section><h3>Class: <code>tls.TLSSocket</code><span><a class="mark" href="#all_tls_class-tlstlssocket" id="all_tls_class-tlstlssocket">#</a></span><a aria-hidden="true" class="legacy" id="tls_class_tls_tlssocket"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li>Extends: <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
</ul>
<p>Performs transparent encryption of written data and all required TLS
negotiation.</p>
<p>Instances of <code>tls.TLSSocket</code> implement the duplex <a href="#all_stream_stream">Stream</a> interface.</p>
<p>Methods that return TLS connection metadata (e.g.
<a href="#all_tls_tlssocketgetpeercertificatedetailed"><code>tls.TLSSocket.getPeerCertificate()</code></a>) will only return data while the
connection is open.</p>
<h4><code>new tls.TLSSocket(socket[, options])</code><span><a class="mark" href="#all_tls_new-tlstlssocketsocket-options" id="all_tls_new-tlstlssocketsocket-options">#</a></span><a aria-hidden="true" class="legacy" id="tls_new_tls_tlssocket_socket_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>v12.2.0</td>
<td><p>The <code>enableTrace</code> option is now supported.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>ALPN options are supported now.</p></td></tr>
<tr><td>v0.11.4</td>
<td><p><span>Added in: v0.11.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>socket</code> <a href="#all_net_class-netsocket" class="type"><net.Socket></a> | <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a>
On the server side, any <code>Duplex</code> stream. On the client side, any
instance of <a href="#all_net_class-netsocket"><code>net.Socket</code></a> (for generic <code>Duplex</code> stream support
on the client side, <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> must be used).</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>enableTrace</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>isServer</code>: The SSL/TLS protocol is asymmetrical, TLSSockets must know if
they are to behave as a server or a client. If <code>true</code> the TLS socket will be
instantiated as a server. <strong>Default:</strong> <code>false</code>.</li>
<li><code>server</code> <a href="#all_net_class-netserver" class="type"><net.Server></a> A <a href="#all_net_class-netserver"><code>net.Server</code></a> instance.</li>
<li><code>requestCert</code>: Whether to authenticate the remote peer by requesting a
certificate. Clients always request a server certificate. Servers
(<code>isServer</code> is true) may set <code>requestCert</code> to true to request a client
certificate.</li>
<li><code>rejectUnauthorized</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>ALPNProtocols</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>SNICallback</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>session</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> A <code>Buffer</code> instance containing a TLS session.</li>
<li><code>requestOCSP</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, specifies that the OCSP status request
extension will be added to the client hello and an <code>'OCSPResponse'</code> event
will be emitted on the socket before establishing a secure communication</li>
<li><code>secureContext</code>: TLS context object created with
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>. If a <code>secureContext</code> is <em>not</em> provided, one
will be created by passing the entire <code>options</code> object to
<code>tls.createSecureContext()</code>.</li>
<li>...: <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> options that are used if the
<code>secureContext</code> option is missing. Otherwise, they are ignored.</li>
</ul>
</li>
</ul>
<p>Construct a new <code>tls.TLSSocket</code> object from an existing TCP socket.</p>
<h4>Event: <code>'keylog'</code><span><a class="mark" href="#all_tls_event-keylog_1" id="all_tls_event-keylog_1">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_keylog_1"></a></h4>
<div class="api_metadata">
<span>Added in: v12.3.0, v10.20.0</span>
</div>
<ul>
<li><code>line</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> Line of ASCII text, in NSS <code>SSLKEYLOGFILE</code> format.</li>
</ul>
<p>The <code>keylog</code> event is emitted on a <code>tls.TLSSocket</code> when key material
is generated or received by the socket. This keying material can be stored
for debugging, as it allows captured TLS traffic to be decrypted. It may
be emitted multiple times, before or after the handshake completes.</p>
<p>A typical use case is to append received lines to a common text file, which
is later used by software (such as Wireshark) to decrypt the traffic:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> logFile = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'/tmp/ssl-keys.log'</span>, { <span class="hljs-attr">flags</span>: <span class="hljs-string">'a'</span> });
<span class="hljs-comment">// ...</span>
tlsSocket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'keylog'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> logFile.<span class="hljs-title function_">write</span>(line));</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'OCSPResponse'</code><span><a class="mark" href="#all_tls_event-ocspresponse" id="all_tls_event-ocspresponse">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_ocspresponse"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div>
<p>The <code>'OCSPResponse'</code> event is emitted if the <code>requestOCSP</code> option was set
when the <code>tls.TLSSocket</code> was created and an OCSP response has been received.
The listener callback is passed a single argument when called:</p>
<ul>
<li><code>response</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The server's OCSP response</li>
</ul>
<p>Typically, the <code>response</code> is a digitally signed object from the server's CA that
contains information about server's certificate revocation status.</p>
<h4>Event: <code>'secureConnect'</code><span><a class="mark" href="#all_tls_event-secureconnect" id="all_tls_event-secureconnect">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_secureconnect"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<p>The <code>'secureConnect'</code> event is emitted after the handshaking process for a new
connection has successfully completed. The listener callback will be called
regardless of whether or not the server's certificate has been authorized. It
is the client's responsibility to check the <code>tlsSocket.authorized</code> property to
determine if the server certificate was signed by one of the specified CAs. If
<code>tlsSocket.authorized === false</code>, then the error can be found by examining the
<code>tlsSocket.authorizationError</code> property. If ALPN was used, the
<code>tlsSocket.alpnProtocol</code> property can be checked to determine the negotiated
protocol.</p>
<p>The <code>'secureConnect'</code> event is not emitted when a <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a> is created
using the <code>new tls.TLSSocket()</code> constructor.</p>
<h4>Event: <code>'session'</code><span><a class="mark" href="#all_tls_event-session" id="all_tls_event-session">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_session"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><code>session</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>The <code>'session'</code> event is emitted on a client <code>tls.TLSSocket</code> when a new session
or TLS ticket is available. This may or may not be before the handshake is
complete, depending on the TLS protocol version that was negotiated. The event
is not emitted on the server, or if a new session was not created, for example,
when the connection was resumed. For some TLS protocol versions the event may be
emitted multiple times, in which case all the sessions can be used for
resumption.</p>
<p>On the client, the <code>session</code> can be provided to the <code>session</code> option of
<a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> to resume the connection.</p>
<p>See <a href="#all_tls_session-resumption">Session Resumption</a> for more information.</p>
<p>For TLSv1.2 and below, <a href="#all_tls_tlssocketgetsession"><code>tls.TLSSocket.getSession()</code></a> can be called once
the handshake is complete. For TLSv1.3, only ticket-based resumption is allowed
by the protocol, multiple tickets are sent, and the tickets aren't sent until
after the handshake completes. So it is necessary to wait for the
<code>'session'</code> event to get a resumable session. Applications
should use the <code>'session'</code> event instead of <code>getSession()</code> to ensure
they will work for all TLS versions. Applications that only expect to
get or use one session should listen for this event only once:</p>
<pre><code class="language-js">tlsSocket.<span class="hljs-title function_">once</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {
<span class="hljs-comment">// The session can be used immediately or later.</span>
tls.<span class="hljs-title function_">connect</span>({
<span class="hljs-attr">session</span>: session,
<span class="hljs-comment">// Other connect options...</span>
});
});</code> <button class="copy-button">copy</button></pre>
<h4><code>tlsSocket.address()</code><span><a class="mark" href="#all_tls_tlssocketaddress" id="all_tls_tlssocketaddress">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_address"></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.4.0</td>
<td><p>The <code>family</code> property now returns a string instead of a number.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>family</code> property now returns a number instead of a string.</p></td></tr>
<tr><td>v0.11.4</td>
<td><p><span>Added in: v0.11.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns the bound <code>address</code>, the address <code>family</code> name, and <code>port</code> of the
underlying socket as reported by the operating system:
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code>.</p>
<h4><code>tlsSocket.authorizationError</code><span><a class="mark" href="#all_tls_tlssocketauthorizationerror" id="all_tls_tlssocketauthorizationerror">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_authorizationerror"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<p>Returns the reason why the peer's certificate was not been verified. This
property is set only when <code>tlsSocket.authorized === false</code>.</p>
<h4><code>tlsSocket.authorized</code><span><a class="mark" href="#all_tls_tlssocketauthorized" id="all_tls_tlssocketauthorized">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_authorized"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.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>This property is <code>true</code> if the peer certificate was signed by one of the CAs
specified when creating the <code>tls.TLSSocket</code> instance, otherwise <code>false</code>.</p>
<h4><code>tlsSocket.disableRenegotiation()</code><span><a class="mark" href="#all_tls_tlssocketdisablerenegotiation" id="all_tls_tlssocketdisablerenegotiation">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_disablerenegotiation"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>Disables TLS renegotiation for this <code>TLSSocket</code> instance. Once called, attempts
to renegotiate will trigger an <code>'error'</code> event on the <code>TLSSocket</code>.</p>
<h4><code>tlsSocket.enableTrace()</code><span><a class="mark" href="#all_tls_tlssocketenabletrace" id="all_tls_tlssocketenabletrace">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_enabletrace"></a></h4>
<div class="api_metadata">
<span>Added in: v12.2.0</span>
</div>
<p>When enabled, TLS packet trace information is written to <code>stderr</code>. This can be
used to debug TLS connection problems.</p>
<p>The format of the output is identical to the output of
<code>openssl s_client -trace</code> or <code>openssl s_server -trace</code>. While it is produced by
OpenSSL's <code>SSL_trace()</code> function, the format is undocumented, can change
without notice, and should not be relied on.</p>
<h4><code>tlsSocket.encrypted</code><span><a class="mark" href="#all_tls_tlssocketencrypted" id="all_tls_tlssocketencrypted">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_encrypted"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<p>Always returns <code>true</code>. This may be used to distinguish TLS sockets from regular
<code>net.Socket</code> instances.</p>
<h4><code>tlsSocket.exportKeyingMaterial(length, label[, context])</code><span><a class="mark" href="#all_tls_tlssocketexportkeyingmateriallength-label-context" id="all_tls_tlssocketexportkeyingmateriallength-label-context">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_exportkeyingmaterial_length_label_context"></a></h4>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<ul>
<li>
<p><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> number of bytes to retrieve from keying material</p>
</li>
<li>
<p><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> an application specific label, typically this will be a
value from the
<a href="https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels">IANA Exporter Label Registry</a>.</p>
</li>
<li>
<p><code>context</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> Optionally provide a context.</p>
</li>
<li>
<p>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> requested bytes of the keying material</p>
</li>
</ul>
<p>Keying material is used for validations to prevent different kind of attacks in
network protocols, for example in the specifications of IEEE 802.1X.</p>
<p>Example</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> keyingMaterial = tlsSocket.<span class="hljs-title function_">exportKeyingMaterial</span>(
<span class="hljs-number">128</span>,
<span class="hljs-string">'client finished'</span>);
<span class="hljs-comment">/*
Example return value of keyingMaterial:
<Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
74 ef 2c ... 78 more bytes>
*/</span></code> <button class="copy-button">copy</button></pre>
<p>See the OpenSSL <a href="https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html"><code>SSL_export_keying_material</code></a> documentation for more
information.</p>
<h4><code>tlsSocket.getCertificate()</code><span><a class="mark" href="#all_tls_tlssocketgetcertificate" id="all_tls_tlssocketgetcertificate">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getcertificate"></a></h4>
<div class="api_metadata">
<span>Added in: v11.2.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns an object representing the local certificate. The returned object has
some properties corresponding to the fields of the certificate.</p>
<p>See <a href="#all_tls_tlssocketgetpeercertificatedetailed"><code>tls.TLSSocket.getPeerCertificate()</code></a> for an example of the certificate
structure.</p>
<p>If there is no local certificate, an empty object will be returned. If the
socket has been destroyed, <code>null</code> will be returned.</p>
<h4><code>tlsSocket.getCipher()</code><span><a class="mark" href="#all_tls_tlssocketgetcipher" id="all_tls_tlssocketgetcipher">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getcipher"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.4.0, v12.16.0</td>
<td><p>Return the IETF cipher name as <code>standardName</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Return the minimum cipher version, instead of a fixed string (<code>'TLSv1/SSLv3'</code>).</p></td></tr>
<tr><td>v0.11.4</td>
<td><p><span>Added in: v0.11.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> OpenSSL name for the cipher suite.</li>
<li><code>standardName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> IETF name for the cipher suite.</li>
<li><code>version</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The minimum TLS protocol version supported by this cipher
suite. For the actual negotiated protocol, see <a href="#all_tls_tlssocketgetprotocol"><code>tls.TLSSocket.getProtocol()</code></a>.</li>
</ul>
</li>
</ul>
<p>Returns an object containing information on the negotiated cipher suite.</p>
<p>For example, a TLSv1.2 protocol with AES256-SHA cipher:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"AES256-SHA"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"standardName"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"TLS_RSA_WITH_AES_256_CBC_SHA"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"version"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"SSLv3"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>See
<a href="https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html">SSL_CIPHER_get_name</a>
for more information.</p>
<h4><code>tlsSocket.getEphemeralKeyInfo()</code><span><a class="mark" href="#all_tls_tlssocketgetephemeralkeyinfo" id="all_tls_tlssocketgetephemeralkeyinfo">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getephemeralkeyinfo"></a></h4>
<div class="api_metadata">
<span>Added in: v5.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns an object representing the type, name, and size of parameter of
an ephemeral key exchange in <a href="#all_tls_perfect-forward-secrecy">perfect forward secrecy</a> on a client
connection. It returns an empty object when the key exchange is not
ephemeral. As this is only supported on a client socket; <code>null</code> is returned
if called on a server socket. The supported types are <code>'DH'</code> and <code>'ECDH'</code>. The
<code>name</code> property is available only when type is <code>'ECDH'</code>.</p>
<p>For example: <code>{ type: 'ECDH', name: 'prime256v1', size: 256 }</code>.</p>
<h4><code>tlsSocket.getFinished()</code><span><a class="mark" href="#all_tls_tlssocketgetfinished" id="all_tls_tlssocketgetfinished">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getfinished"></a></h4>
<div class="api_metadata">
<span>Added in: v9.9.0</span>
</div>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The latest <code>Finished</code> message that has been
sent to the socket as part of a SSL/TLS handshake, or <code>undefined</code> if
no <code>Finished</code> message has been sent yet.</li>
</ul>
<p>As the <code>Finished</code> messages are message digests of the complete handshake
(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can
be used for external authentication procedures when the authentication
provided by SSL/TLS is not desired or is not enough.</p>
<p>Corresponds to the <code>SSL_get_finished</code> routine in OpenSSL and may be used
to implement the <code>tls-unique</code> channel binding from <a href="https://tools.ietf.org/html/rfc5929">RFC 5929</a>.</p>
<h4><code>tlsSocket.getPeerCertificate([detailed])</code><span><a class="mark" href="#all_tls_tlssocketgetpeercertificatedetailed" id="all_tls_tlssocketgetpeercertificatedetailed">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getpeercertificate_detailed"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><code>detailed</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Include the full certificate chain if <code>true</code>, otherwise
include just the peer's certificate.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A certificate object.</li>
</ul>
<p>Returns an object representing the peer's certificate. If the peer does not
provide a certificate, an empty object will be returned. If the socket has been
destroyed, <code>null</code> will be returned.</p>
<p>If the full certificate chain was requested, each certificate will include an
<code>issuerCertificate</code> property containing an object representing its issuer's
certificate.</p>
<h5>Certificate object<span><a class="mark" href="#all_tls_certificate-object" id="all_tls_certificate-object">#</a></span><a aria-hidden="true" class="legacy" id="tls_certificate_object"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.1.0, v18.13.0</td>
<td><p>Add "ca" property.</p></td></tr>
<tr><td>v17.2.0, v16.14.0</td>
<td><p>Add fingerprint512.</p></td></tr>
<tr><td>v11.4.0</td>
<td><p>Support Elliptic Curve public key info.</p></td></tr>
</tbody></table>
</details>
</div>
<p>A certificate object has properties corresponding to the fields of the
certificate.</p>
<ul>
<li><code>ca</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if a Certificate Authority (CA), <code>false</code> otherwise.</li>
<li><code>raw</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The DER encoded X.509 certificate data.</li>
<li><code>subject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The certificate subject, described in terms of
Country (<code>C</code>), StateOrProvince (<code>ST</code>), Locality (<code>L</code>), Organization (<code>O</code>),
OrganizationalUnit (<code>OU</code>), and CommonName (<code>CN</code>). The CommonName is typically
a DNS name with TLS certificates. Example:
<code>{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}</code>.</li>
<li><code>issuer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The certificate issuer, described in the same terms as the
<code>subject</code>.</li>
<li><code>valid_from</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The date-time the certificate is valid from.</li>
<li><code>valid_to</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The date-time the certificate is valid to.</li>
<li><code>serialNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The certificate serial number, as a hex string.
Example: <code>'B9B0D332A1AA5635'</code>.</li>
<li><code>fingerprint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The SHA-1 digest of the DER encoded certificate. It is
returned as a <code>:</code> separated hexadecimal string. Example: <code>'2A:7A:C2:DD:...'</code>.</li>
<li><code>fingerprint256</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The SHA-256 digest of the DER encoded certificate.
It is returned as a <code>:</code> separated hexadecimal string. Example:
<code>'2A:7A:C2:DD:...'</code>.</li>
<li><code>fingerprint512</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The SHA-512 digest of the DER encoded certificate.
It is returned as a <code>:</code> separated hexadecimal string. Example:
<code>'2A:7A:C2:DD:...'</code>.</li>
<li><code>ext_key_usage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> (Optional) The extended key usage, a set of OIDs.</li>
<li><code>subjectaltname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> (Optional) A string containing concatenated names
for the subject, an alternative to the <code>subject</code> names.</li>
<li><code>infoAccess</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> (Optional) An array describing the AuthorityInfoAccess,
used with OCSP.</li>
<li><code>issuerCertificate</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> (Optional) The issuer certificate object. For
self-signed certificates, this may be a circular reference.</li>
</ul>
<p>The certificate may contain information about the public key, depending on
the key type.</p>
<p>For RSA keys, the following properties may be defined:</p>
<ul>
<li><code>bits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The RSA bit size. Example: <code>1024</code>.</li>
<li><code>exponent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The RSA exponent, as a string in hexadecimal number
notation. Example: <code>'0x010001'</code>.</li>
<li><code>modulus</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The RSA modulus, as a hexadecimal string. Example:
<code>'B56CE45CB7...'</code>.</li>
<li><code>pubkey</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The public key.</li>
</ul>
<p>For EC keys, the following properties may be defined:</p>
<ul>
<li><code>pubkey</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The public key.</li>
<li><code>bits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The key size in bits. Example: <code>256</code>.</li>
<li><code>asn1Curve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> (Optional) The ASN.1 name of the OID of the elliptic
curve. Well-known curves are identified by an OID. While it is unusual, it is
possible that the curve is identified by its mathematical properties, in which
case it will not have an OID. Example: <code>'prime256v1'</code>.</li>
<li><code>nistCurve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> (Optional) The NIST name for the elliptic curve, if it
has one (not all well-known curves have been assigned names by NIST). Example:
<code>'P-256'</code>.</li>
</ul>
<p>Example certificate:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{ <span class="hljs-attr">subject</span>:
{ <span class="hljs-attr">OU</span>: [ <span class="hljs-string">'Domain Control Validated'</span>, <span class="hljs-string">'PositiveSSL Wildcard'</span> ],
<span class="hljs-attr">CN</span>: <span class="hljs-string">'*.nodejs.org'</span> },
<span class="hljs-attr">issuer</span>:
{ <span class="hljs-attr">C</span>: <span class="hljs-string">'GB'</span>,
<span class="hljs-attr">ST</span>: <span class="hljs-string">'Greater Manchester'</span>,
<span class="hljs-attr">L</span>: <span class="hljs-string">'Salford'</span>,
<span class="hljs-attr">O</span>: <span class="hljs-string">'COMODO CA Limited'</span>,
<span class="hljs-attr">CN</span>: <span class="hljs-string">'COMODO RSA Domain Validation Secure Server CA'</span> },
<span class="hljs-attr">subjectaltname</span>: <span class="hljs-string">'DNS:*.nodejs.org, DNS:nodejs.org'</span>,
<span class="hljs-attr">infoAccess</span>:
{ <span class="hljs-string">'CA Issuers - URI'</span>:
[ <span class="hljs-string">'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt'</span> ],
<span class="hljs-string">'OCSP - URI'</span>: [ <span class="hljs-string">'http://ocsp.comodoca.com'</span> ] },
<span class="hljs-attr">modulus</span>: <span class="hljs-string">'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1'</span>,
<span class="hljs-attr">exponent</span>: <span class="hljs-string">'0x10001'</span>,
<span class="hljs-attr">pubkey</span>: <Buffer ... >,
valid_from: 'Aug 14 00:00:00 2017 GMT',
valid_to: 'Nov 20 23:59:59 2019 GMT',
fingerprint: '01:02:59:D9:C3:D2:0D:08:F7:82:4E:44:A4:B4:53:C5:E2:3A:87:4D',
fingerprint256: '69:AE:1A:6A:D4:3D:C6:C1:1B:EA:C6:23:DE:BA:2A:14:62:62:93:5C:7A:EA:06:41:9B:0B:BC:87:CE:48:4E:02',
fingerprint512: '19:2B:3E:C3:B3:5B:32:E8:AE:BB:78:97:27:E4:BA:6C:39:C9:92:79:4F:31:46:39:E2:70:E5:5F:89:42:17:C9:E8:64:CA:FF:BB:72:56:73:6E:28:8A:92:7E:A3:2A:15:8B:C2:E0:45:CA:C3:BC:EA:40:52:EC:CA:A2:68:CB:32',
ext_key_usage: [ '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' ],
serialNumber: '66593D57F20CBC573E433381B5FEC280',
raw: <Buffer ... > }</code> <button class="copy-button">copy</button></pre>
<h4><code>tlsSocket.getPeerFinished()</code><span><a class="mark" href="#all_tls_tlssocketgetpeerfinished" id="all_tls_tlssocketgetpeerfinished">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getpeerfinished"></a></h4>
<div class="api_metadata">
<span>Added in: v9.9.0</span>
</div>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The latest <code>Finished</code> message that is expected
or has actually been received from the socket as part of a SSL/TLS handshake,
or <code>undefined</code> if there is no <code>Finished</code> message so far.</li>
</ul>
<p>As the <code>Finished</code> messages are message digests of the complete handshake
(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can
be used for external authentication procedures when the authentication
provided by SSL/TLS is not desired or is not enough.</p>
<p>Corresponds to the <code>SSL_get_peer_finished</code> routine in OpenSSL and may be used
to implement the <code>tls-unique</code> channel binding from <a href="https://tools.ietf.org/html/rfc5929">RFC 5929</a>.</p>
<h4><code>tlsSocket.getPeerX509Certificate()</code><span><a class="mark" href="#all_tls_tlssocketgetpeerx509certificate" id="all_tls_tlssocketgetpeerx509certificate">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getpeerx509certificate"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0</span>
</div>
<ul>
<li>Returns: <a href="#all_crypto_class-x509certificate" class="type"><X509Certificate></a></li>
</ul>
<p>Returns the peer certificate as an <a href="#all_crypto_class-x509certificate" class="type"><X509Certificate></a> object.</p>
<p>If there is no peer certificate, or the socket has been destroyed,
<code>undefined</code> will be returned.</p>
<h4><code>tlsSocket.getProtocol()</code><span><a class="mark" href="#all_tls_tlssocketgetprotocol" id="all_tls_tlssocketgetprotocol">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getprotocol"></a></h4>
<div class="api_metadata">
<span>Added in: v5.7.0</span>
</div>
<ul>
<li>Returns: <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></li>
</ul>
<p>Returns a string containing the negotiated SSL/TLS protocol version of the
current connection. The value <code>'unknown'</code> will be returned for connected
sockets that have not completed the handshaking process. The value <code>null</code> will
be returned for server sockets or disconnected client sockets.</p>
<p>Protocol versions are:</p>
<ul>
<li><code>'SSLv3'</code></li>
<li><code>'TLSv1'</code></li>
<li><code>'TLSv1.1'</code></li>
<li><code>'TLSv1.2'</code></li>
<li><code>'TLSv1.3'</code></li>
</ul>
<p>See the OpenSSL <a href="https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html"><code>SSL_get_version</code></a> documentation for more information.</p>
<h4><code>tlsSocket.getSession()</code><span><a class="mark" href="#all_tls_tlssocketgetsession" id="all_tls_tlssocketgetsession">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getsession"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Returns the TLS session data or <code>undefined</code> if no session was
negotiated. On the client, the data can be provided to the <code>session</code> option of
<a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> to resume the connection. On the server, it may be useful
for debugging.</p>
<p>See <a href="#all_tls_session-resumption">Session Resumption</a> for more information.</p>
<p>Note: <code>getSession()</code> works only for TLSv1.2 and below. For TLSv1.3, applications
must use the <a href="#all_tls_event-session"><code>'session'</code></a> event (it also works for TLSv1.2 and below).</p>
<h4><code>tlsSocket.getSharedSigalgs()</code><span><a class="mark" href="#all_tls_tlssocketgetsharedsigalgs" id="all_tls_tlssocketgetsharedsigalgs">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getsharedsigalgs"></a></h4>
<div class="api_metadata">
<span>Added in: v12.11.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> List of signature algorithms shared between the server and
the client in the order of decreasing preference.</li>
</ul>
<p>See
<a href="https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html">SSL_get_shared_sigalgs</a>
for more information.</p>
<h4><code>tlsSocket.getTLSTicket()</code><span><a class="mark" href="#all_tls_tlssocketgettlsticket" id="all_tls_tlssocketgettlsticket">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_gettlsticket"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>For a client, returns the TLS session ticket if one is available, or
<code>undefined</code>. For a server, always returns <code>undefined</code>.</p>
<p>It may be useful for debugging.</p>
<p>See <a href="#all_tls_session-resumption">Session Resumption</a> for more information.</p>
<h4><code>tlsSocket.getX509Certificate()</code><span><a class="mark" href="#all_tls_tlssocketgetx509certificate" id="all_tls_tlssocketgetx509certificate">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getx509certificate"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0</span>
</div>
<ul>
<li>Returns: <a href="#all_crypto_class-x509certificate" class="type"><X509Certificate></a></li>
</ul>
<p>Returns the local certificate as an <a href="#all_crypto_class-x509certificate" class="type"><X509Certificate></a> object.</p>
<p>If there is no local certificate, or the socket has been destroyed,
<code>undefined</code> will be returned.</p>
<h4><code>tlsSocket.isSessionReused()</code><span><a class="mark" href="#all_tls_tlssocketissessionreused" id="all_tls_tlssocketissessionreused">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_issessionreused"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.6</span>
</div>
<ul>
<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 the session was reused, <code>false</code> otherwise.</li>
</ul>
<p>See <a href="#all_tls_session-resumption">Session Resumption</a> for more information.</p>
<h4><code>tlsSocket.localAddress</code><span><a class="mark" href="#all_tls_tlssocketlocaladdress" id="all_tls_tlssocketlocaladdress">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_localaddress"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the string representation of the local IP address.</p>
<h4><code>tlsSocket.localPort</code><span><a class="mark" href="#all_tls_tlssocketlocalport" id="all_tls_tlssocketlocalport">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_localport"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</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>Returns the numeric representation of the local port.</p>
<h4><code>tlsSocket.remoteAddress</code><span><a class="mark" href="#all_tls_tlssocketremoteaddress" id="all_tls_tlssocketremoteaddress">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_remoteaddress"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the string representation of the remote IP address. For example,
<code>'74.125.127.100'</code> or <code>'2001:4860:a005::68'</code>.</p>
<h4><code>tlsSocket.remoteFamily</code><span><a class="mark" href="#all_tls_tlssocketremotefamily" id="all_tls_tlssocketremotefamily">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_remotefamily"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the string representation of the remote IP family. <code>'IPv4'</code> or <code>'IPv6'</code>.</p>
<h4><code>tlsSocket.remotePort</code><span><a class="mark" href="#all_tls_tlssocketremoteport" id="all_tls_tlssocketremoteport">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_remoteport"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</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>Returns the numeric representation of the remote port. For example, <code>443</code>.</p>
<h4><code>tlsSocket.renegotiate(options, callback)</code><span><a class="mark" href="#all_tls_tlssocketrenegotiateoptions-callback" id="all_tls_tlssocketrenegotiateoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_renegotiate_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>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>v0.11.8</td>
<td><p><span>Added in: v0.11.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p>
<ul>
<li><code>rejectUnauthorized</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If not <code>false</code>, the server certificate is
verified against the list of supplied CAs. An <code>'error'</code> event is emitted if
verification fails; <code>err.code</code> contains the OpenSSL error code. <strong>Default:</strong>
<code>true</code>.</li>
<li><code>requestCert</code></li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> If <code>renegotiate()</code> returned <code>true</code>, callback is
attached once to the <code>'secure'</code> event. If <code>renegotiate()</code> returned <code>false</code>,
<code>callback</code> will be called in the next tick with an error, unless the
<code>tlsSocket</code> has been destroyed, in which case <code>callback</code> will not be called
at all.</p>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if renegotiation was initiated, <code>false</code> otherwise.</p>
</li>
</ul>
<p>The <code>tlsSocket.renegotiate()</code> method initiates a TLS renegotiation process.
Upon completion, the <code>callback</code> function will be passed a single argument
that is either an <code>Error</code> (if the request failed) or <code>null</code>.</p>
<p>This method can be used to request a peer's certificate after the secure
connection has been established.</p>
<p>When running as the server, the socket will be destroyed with an error after
<code>handshakeTimeout</code> timeout.</p>
<p>For TLSv1.3, renegotiation cannot be initiated, it is not supported by the
protocol.</p>
<h4><code>tlsSocket.setKeyCert(context)</code><span><a class="mark" href="#all_tls_tlssocketsetkeycertcontext" id="all_tls_tlssocketsetkeycertcontext">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_setkeycert_context"></a></h4>
<div class="api_metadata">
<span>Added in: v20.17.0</span>
</div>
<ul>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="#all_tls_tlscreatesecurecontextoptions" class="type"><tls.SecureContext></a> An object containing at least <code>key</code> and
<code>cert</code> properties from the <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> <code>options</code>, or a
TLS context object created with <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> itself.</li>
</ul>
<p>The <code>tlsSocket.setKeyCert()</code> method sets the private key and certificate to use
for the socket. This is mainly useful if you wish to select a server certificate
from a TLS server's <code>ALPNCallback</code>.</p>
<h4><code>tlsSocket.setMaxSendFragment(size)</code><span><a class="mark" href="#all_tls_tlssocketsetmaxsendfragmentsize" id="all_tls_tlssocketsetmaxsendfragmentsize">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_setmaxsendfragment_size"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.11</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> The maximum TLS fragment size. The maximum value is <code>16384</code>.
<strong>Default:</strong> <code>16384</code>.</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>The <code>tlsSocket.setMaxSendFragment()</code> method sets the maximum TLS fragment size.
Returns <code>true</code> if setting the limit succeeded; <code>false</code> otherwise.</p>
<p>Smaller fragment sizes decrease the buffering latency on the client: larger
fragments are buffered by the TLS layer until the entire fragment is received
and its integrity is verified; large fragments can span multiple roundtrips
and their processing can be delayed due to packet loss or reordering. However,
smaller fragments add extra TLS framing bytes and CPU overhead, which may
decrease overall server throughput.</p>
</section><section><h3><code>tls.checkServerIdentity(hostname, cert)</code><span><a class="mark" href="#all_tls_tlscheckserveridentityhostname-cert" id="all_tls_tlscheckserveridentityhostname-cert">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_checkserveridentity_hostname_cert"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.3.1, v16.13.2, v14.18.3, v12.22.9</td>
<td><p>Support for <code>uniformResourceIdentifier</code> subject alternative names has been disabled in response to CVE-2021-44531.</p></td></tr>
<tr><td>v0.8.4</td>
<td><p><span>Added in: v0.8.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The host name or IP address to verify the certificate
against.</li>
<li><code>cert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A <a href="#all_tls_certificate-object">certificate object</a> representing the peer's certificate.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>Verifies the certificate <code>cert</code> is issued to <code>hostname</code>.</p>
<p>Returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> object, populating it with <code>reason</code>, <code>host</code>, and <code>cert</code> on
failure. On success, returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a>.</p>
<p>This function is intended to be used in combination with the
<code>checkServerIdentity</code> option that can be passed to <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> and as
such operates on a <a href="#all_tls_certificate-object">certificate object</a>. For other purposes, consider using
<a href="#all_crypto_x509checkhostname-options"><code>x509.checkHost()</code></a> instead.</p>
<p>This function can be overwritten by providing an alternative function as the
<code>options.checkServerIdentity</code> option that is passed to <code>tls.connect()</code>. The
overwriting function can call <code>tls.checkServerIdentity()</code> of course, to augment
the checks done with additional verification.</p>
<p>This function is only called if the certificate passed all other checks, such as
being issued by trusted CA (<code>options.ca</code>).</p>
<p>Earlier versions of Node.js incorrectly accepted certificates for a given
<code>hostname</code> if a matching <code>uniformResourceIdentifier</code> subject alternative name
was present (see <a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531">CVE-2021-44531</a>). Applications that wish to accept
<code>uniformResourceIdentifier</code> subject alternative names can use a custom
<code>options.checkServerIdentity</code> function that implements the desired behavior.</p>
</section><section><h3><code>tls.connect(options[, callback])</code><span><a class="mark" href="#all_tls_tlsconnectoptions-callback" id="all_tls_tlsconnectoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_connect_options_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.1.0, v14.18.0</td>
<td><p>Added <code>onread</code> option.</p></td></tr>
<tr><td>v14.1.0, v13.14.0</td>
<td><p>The <code>highWaterMark</code> option is accepted now.</p></td></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p>The <code>pskCallback</code> option is now supported.</p></td></tr>
<tr><td>v12.9.0</td>
<td><p>Support the <code>allowHalfOpen</code> option.</p></td></tr>
<tr><td>v12.4.0</td>
<td><p>The <code>hints</code> option is now supported.</p></td></tr>
<tr><td>v12.2.0</td>
<td><p>The <code>enableTrace</code> option is now supported.</p></td></tr>
<tr><td>v11.8.0, v10.16.0</td>
<td><p>The <code>timeout</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>lookup</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>ALPNProtocols</code> option can be a <code>TypedArray</code> or <code>DataView</code> now.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>ALPN options are supported now.</p></td></tr>
<tr><td>v5.3.0, v4.7.0</td>
<td><p>The <code>secureContext</code> option is supported now.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p><span>Added in: v0.11.3</span></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>enableTrace</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host the client should connect to. <strong>Default:</strong>
<code>'localhost'</code>.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port the client should connect to.</li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Creates Unix socket connection to path. If this option is
specified, <code>host</code> and <code>port</code> are ignored.</li>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type"><stream.Duplex></a> Establish secure connection on a given socket
rather than creating a new socket. Typically, this is an instance of
<a href="#all_net_class-netsocket"><code>net.Socket</code></a>, but any <code>Duplex</code> stream is allowed.
If this option is specified, <code>path</code>, <code>host</code>, and <code>port</code> are ignored,
except for certificate validation. Usually, a socket is already connected
when passed to <code>tls.connect()</code>, but it can be connected later.
Connection/disconnection/destruction of <code>socket</code> is the user's
responsibility; calling <code>tls.connect()</code> will not cause <code>net.connect()</code> to be
called.</li>
<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 socket will
automatically end the writable side when the readable side ends. If the
<code>socket</code> option is set, this option has no effect. See the <code>allowHalfOpen</code>
option of <a href="#all_net_class-netsocket"><code>net.Socket</code></a> for details. <strong>Default:</strong> <code>false</code>.</li>
<li><code>rejectUnauthorized</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If not <code>false</code>, the server certificate is
verified against the list of supplied CAs. An <code>'error'</code> event is emitted if
verification fails; <code>err.code</code> contains the OpenSSL error code. <strong>Default:</strong>
<code>true</code>.</li>
<li><code>pskCallback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> For TLS-PSK negotiation, see <a href="#all_tls_pre-shared-keys">Pre-shared keys</a>.</li>
<li><code>ALPNProtocols</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#all_buffer_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="#all_buffer_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>
An array of strings, <code>Buffer</code>s, <code>TypedArray</code>s, or <code>DataView</code>s, or a
single <code>Buffer</code>, <code>TypedArray</code>, or <code>DataView</code> containing the supported ALPN
protocols. <code>Buffer</code>s should have the format <code>[len][name][len][name]...</code>
e.g. <code>'\x08http/1.1\x08http/1.0'</code>, where the <code>len</code> byte is the length of the
next protocol name. Passing an array is usually much simpler, e.g.
<code>['http/1.1', 'http/1.0']</code>. Protocols earlier in the list have higher
preference than those later.</li>
<li><code>servername</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Server name for the SNI (Server Name Indication) TLS
extension. It is the name of the host being connected to, and must be a host
name, and not an IP address. It can be used by a multi-homed server to
choose the correct certificate to present to the client, see the
<code>SNICallback</code> option to <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a>.</li>
<li><code>checkServerIdentity(servername, cert)</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function
to be used (instead of the builtin <code>tls.checkServerIdentity()</code> function)
when checking the server's host name (or the provided <code>servername</code> when
explicitly set) against the certificate. This should return an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> if
verification fails. The method should return <code>undefined</code> if the <code>servername</code>
and <code>cert</code> are verified.</li>
<li><code>session</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> A <code>Buffer</code> instance, containing TLS session.</li>
<li><code>minDHSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Minimum size of the DH parameter in bits to accept a
TLS connection. When a server offers a DH parameter with a size less
than <code>minDHSize</code>, the TLS connection is destroyed and an error is thrown.
<strong>Default:</strong> <code>1024</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> Consistent with the readable stream <code>highWaterMark</code> parameter.
<strong>Default:</strong> <code>16 * 1024</code>.</li>
<li><code>secureContext</code>: TLS context object created with
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>. If a <code>secureContext</code> is <em>not</em> provided, one
will be created by passing the entire <code>options</code> object to
<code>tls.createSecureContext()</code>.</li>
<li><code>onread</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> If the <code>socket</code> option is missing, incoming data is
stored in a single <code>buffer</code> and passed to the supplied <code>callback</code> when
data arrives on the socket, otherwise the option is ignored. See the
<code>onread</code> option of <a href="#all_net_class-netsocket"><code>net.Socket</code></a> for details.</li>
<li>...: <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> options that are used if the
<code>secureContext</code> option is missing, otherwise they are ignored.</li>
<li>...: Any <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect()</code></a> option not already listed.</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></li>
<li>Returns: <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a></li>
</ul>
<p>The <code>callback</code> function, if specified, will be added as a listener for the
<a href="#all_tls_event-secureconnect"><code>'secureConnect'</code></a> event.</p>
<p><code>tls.connect()</code> returns a <a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a> object.</p>
<p>Unlike the <code>https</code> API, <code>tls.connect()</code> does not enable the
SNI (Server Name Indication) extension by default, which may cause some
servers to return an incorrect certificate or reject the connection
altogether. To enable SNI, set the <code>servername</code> option in addition
to <code>host</code>.</p>
<p>The following illustrates a client for the echo server example from
<a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a>:</p>
<pre><code class="language-js"><span class="hljs-comment">// Assumes an echo server that is listening on port 8000.</span>
<span class="hljs-keyword">const</span> tls = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:tls'</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> options = {
<span class="hljs-comment">// Necessary only if the server requires client certificate authentication.</span>
<span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'client-key.pem'</span>),
<span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'client-cert.pem'</span>),
<span class="hljs-comment">// Necessary only if the server uses a self-signed certificate.</span>
<span class="hljs-attr">ca</span>: [ fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-cert.pem'</span>) ],
<span class="hljs-comment">// Necessary only if the server's cert isn't for "localhost".</span>
<span class="hljs-attr">checkServerIdentity</span>: <span class="hljs-function">() =></span> { <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>; },
};
<span class="hljs-keyword">const</span> socket = tls.<span class="hljs-title function_">connect</span>(<span class="hljs-number">8000</span>, options, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'client connected'</span>,
socket.<span class="hljs-property">authorized</span> ? <span class="hljs-string">'authorized'</span> : <span class="hljs-string">'unauthorized'</span>);
process.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">pipe</span>(socket);
process.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">resume</span>();
});
socket.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
});
socket.<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">'server ends connection'</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>tls.connect(path[, options][, callback])</code><span><a class="mark" href="#all_tls_tlsconnectpath-options-callback" id="all_tls_tlsconnectpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_connect_path_options_callback"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.3</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Default value for <code>options.path</code>.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> See <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>.</li>
<li>Returns: <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a></li>
</ul>
<p>Same as <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> except that <code>path</code> can be provided
as an argument instead of an option.</p>
<p>A path option, if specified, will take precedence over the path argument.</p>
</section><section><h3><code>tls.connect(port[, host][, options][, callback])</code><span><a class="mark" href="#all_tls_tlsconnectport-host-options-callback" id="all_tls_tlsconnectport-host-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_connect_port_host_options_callback"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.3</span>
</div>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Default value for <code>options.port</code>.</li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Default value for <code>options.host</code>.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> See <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>.</li>
<li>Returns: <a href="#all_tls_class-tlstlssocket" class="type"><tls.TLSSocket></a></li>
</ul>
<p>Same as <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> except that <code>port</code> and <code>host</code> can be provided
as arguments instead of options.</p>
<p>A port or host option, if specified, will take precedence over any port or host
argument.</p>
</section><section><h3><code>tls.createSecureContext([options])</code><span><a class="mark" href="#all_tls_tlscreatesecurecontextoptions" id="all_tls_tlscreatesecurecontextoptions">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_createsecurecontext_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>The <code>allowPartialTrustChain</code> option has been added.</p></td></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>clientCertEngine</code>, <code>privateKeyEngine</code> and <code>privateKeyIdentifier</code> options depend on custom engine support in OpenSSL which is deprecated in OpenSSL 3.</p></td></tr>
<tr><td>v19.8.0, v18.16.0</td>
<td><p>The <code>dhparam</code> option can now be set to <code>'auto'</code> to enable DHE with appropriate well-known parameters.</p></td></tr>
<tr><td>v12.12.0</td>
<td><p>Added <code>privateKeyIdentifier</code> and <code>privateKeyEngine</code> options to get private key from an OpenSSL engine.</p></td></tr>
<tr><td>v12.11.0</td>
<td><p>Added <code>sigalgs</code> option to override supported signature algorithms.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>TLSv1.3 support added.</p></td></tr>
<tr><td>v11.5.0</td>
<td><p>The <code>ca:</code> option now supports <code>BEGIN TRUSTED CERTIFICATE</code>.</p></td></tr>
<tr><td>v11.4.0, v10.16.0</td>
<td><p>The <code>minVersion</code> and <code>maxVersion</code> can be used to restrict the allowed TLS protocol versions.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>ecdhCurve</code> cannot be set to <code>false</code> anymore due to a change in OpenSSL.</p></td></tr>
<tr><td>v9.3.0</td>
<td><p>The <code>options</code> parameter can now include <code>clientCertEngine</code>.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>ecdhCurve</code> option can now be multiple <code>':'</code> separated curve names or <code>'auto'</code>.</p></td></tr>
<tr><td>v7.3.0</td>
<td><p>If the <code>key</code> option is an array, individual entries do not need a <code>passphrase</code> property anymore. <code>Array</code> entries can also just be <code>string</code>s or <code>Buffer</code>s now.</p></td></tr>
<tr><td>v5.2.0</td>
<td><p>The <code>ca</code> option can now be a single string containing multiple CA certificates.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></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>allowPartialTrustChain</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Treat intermediate (non-self-signed)
certificates in the trust CA certificate list as trusted.</li>
<li><code>ca</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#String_type" class="type"><string[]></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer[]></a> Optionally override the trusted CA
certificates. Default is to trust the well-known CAs curated by Mozilla.
Mozilla's CAs are completely replaced when CAs are explicitly specified
using this option. The value can be a string or <code>Buffer</code>, or an <code>Array</code> of
strings and/or <code>Buffer</code>s. Any string or <code>Buffer</code> can contain multiple PEM
CAs concatenated together. The peer's certificate must be chainable to a CA
trusted by the server for the connection to be authenticated. When using
certificates that are not chainable to a well-known CA, the certificate's CA
must be explicitly specified as a trusted or the connection will fail to
authenticate.
If the peer uses a certificate that doesn't match or chain to one of the
default CAs, use the <code>ca</code> option to provide a CA certificate that the peer's
certificate can match or chain to.
For self-signed certificates, the certificate is its own CA, and must be
provided.
For PEM encoded certificates, supported types are "TRUSTED CERTIFICATE",
"X509 CERTIFICATE", and "CERTIFICATE".
See also <a href="#all_tls_tlsrootcertificates"><code>tls.rootCertificates</code></a>.</li>
<li><code>cert</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#String_type" class="type"><string[]></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer[]></a> Cert chains in PEM format. One
cert chain should be provided per private key. Each cert chain should
consist of the PEM formatted certificate for a provided private <code>key</code>,
followed by the PEM formatted intermediate certificates (if any), in order,
and not including the root CA (the root CA must be pre-known to the peer,
see <code>ca</code>). When providing multiple cert chains, they do not have to be in
the same order as their private keys in <code>key</code>. If the intermediate
certificates are not provided, the peer will not be able to validate the
certificate, and the handshake will fail.</li>
<li><code>sigalgs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Colon-separated list of supported signature algorithms.
The list can contain digest algorithms (<code>SHA256</code>, <code>MD5</code> etc.), public key
algorithms (<code>RSA-PSS</code>, <code>ECDSA</code> etc.), combination of both (e.g
'RSA+SHA384') or TLS v1.3 scheme names (e.g. <code>rsa_pss_pss_sha512</code>).
See <a href="https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set1_sigalgs_list.html">OpenSSL man pages</a>
for more info.</li>
<li><code>ciphers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Cipher suite specification, replacing the default. For
more information, see <a href="#all_tls_modifying-the-default-tls-cipher-suite">Modifying the default TLS cipher suite</a>. Permitted
ciphers can be obtained via <a href="#all_tls_tlsgetciphers"><code>tls.getCiphers()</code></a>. Cipher names must be
uppercased in order for OpenSSL to accept them.</li>
<li><code>clientCertEngine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of an OpenSSL engine which can provide the
client certificate. <strong>Deprecated.</strong></li>
<li><code>crl</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#String_type" class="type"><string[]></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer[]></a> PEM formatted CRLs (Certificate
Revocation Lists).</li>
<li><code>dhparam</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> <code>'auto'</code> or custom Diffie-Hellman parameters,
required for non-ECDHE <a href="#all_tls_perfect-forward-secrecy">perfect forward secrecy</a>. If omitted or invalid,
the parameters are silently discarded and DHE ciphers will not be available.
<a href="https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman">ECDHE</a>-based <a href="#all_tls_perfect-forward-secrecy">perfect forward secrecy</a> will still be available.</li>
<li><code>ecdhCurve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string describing a named curve or a colon separated
list of curve NIDs or names, for example <code>P-521:P-384:P-256</code>, to use for
ECDH key agreement. Set to <code>auto</code> to select the
curve automatically. Use <a href="#all_crypto_cryptogetcurves"><code>crypto.getCurves()</code></a> to obtain a list of
available curve names. On recent releases, <code>openssl ecparam -list_curves</code>
will also display the name and description of each available elliptic curve.
<strong>Default:</strong> <a href="#all_tls_tlsdefault_ecdh_curve"><code>tls.DEFAULT_ECDH_CURVE</code></a>.</li>
<li><code>honorCipherOrder</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Attempt to use the server's cipher suite
preferences instead of the client's. When <code>true</code>, causes
<code>SSL_OP_CIPHER_SERVER_PREFERENCE</code> to be set in <code>secureOptions</code>, see
<a href="#all_crypto_openssl-options">OpenSSL Options</a> for more information.</li>
<li><code>key</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#String_type" class="type"><string[]></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> Private keys in PEM
format. PEM allows the option of private keys being encrypted. Encrypted
keys will be decrypted with <code>options.passphrase</code>. Multiple keys using
different algorithms can be provided either as an array of unencrypted key
strings or buffers, or an array of objects in the form
<code>{pem: <string|buffer>[, passphrase: <string>]}</code>. The object form can only
occur in an array. <code>object.passphrase</code> is optional. Encrypted keys will be
decrypted with <code>object.passphrase</code> if provided, or <code>options.passphrase</code> if
it is not.</li>
<li><code>privateKeyEngine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of an OpenSSL engine to get private key
from. Should be used together with <code>privateKeyIdentifier</code>. <strong>Deprecated.</strong></li>
<li><code>privateKeyIdentifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Identifier of a private key managed by
an OpenSSL engine. Should be used together with <code>privateKeyEngine</code>.
Should not be set together with <code>key</code>, because both options define a
private key in different ways. <strong>Deprecated.</strong></li>
<li><code>maxVersion</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optionally set the maximum TLS version to allow. One
of <code>'TLSv1.3'</code>, <code>'TLSv1.2'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1'</code>. Cannot be specified
along with the <code>secureProtocol</code> option; use one or the other.
<strong>Default:</strong> <a href="#all_tls_tlsdefault_max_version"><code>tls.DEFAULT_MAX_VERSION</code></a>.</li>
<li><code>minVersion</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optionally set the minimum TLS version to allow. One
of <code>'TLSv1.3'</code>, <code>'TLSv1.2'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1'</code>. Cannot be specified
along with the <code>secureProtocol</code> option; use one or the other. Avoid
setting to less than TLSv1.2, but it may be required for
interoperability.
<strong>Default:</strong> <a href="#all_tls_tlsdefault_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a>.</li>
<li><code>passphrase</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Shared passphrase used for a single private key and/or
a PFX.</li>
<li><code>pfx</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#String_type" class="type"><string[]></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="#all_buffer_class-buffer" class="type"><Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> PFX or PKCS12 encoded
private key and certificate chain. <code>pfx</code> is an alternative to providing
<code>key</code> and <code>cert</code> individually. PFX is usually encrypted, if it is,
<code>passphrase</code> will be used to decrypt it. Multiple PFX can be provided either
as an array of unencrypted PFX buffers, or an array of objects in the form
<code>{buf: <string|buffer>[, passphrase: <string>]}</code>. The object form can only
occur in an array. <code>object.passphrase</code> is optional. Encrypted PFX will be
decrypted with <code>object.passphrase</code> if provided, or <code>options.passphrase</code> if
it is not.</li>
<li><code>secureOptions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optionally affect the OpenSSL protocol behavior,
which is not usually necessary. This should be used carefully if at all!
Value is a numeric bitmask of the <code>SSL_OP_*</code> options from
<a href="#all_crypto_openssl-options">OpenSSL Options</a>.</li>
<li><code>secureProtocol</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Legacy mechanism to select the TLS protocol
version to use, it does not support independent control of the minimum and
maximum version, and does not support limiting the protocol to TLSv1.3. Use
<code>minVersion</code> and <code>maxVersion</code> instead. The possible values are listed as
<a href="https://www.openssl.org/docs/man1.1.1/man7/ssl.html#Dealing-with-Protocol-Methods">SSL_METHODS</a>, use the function names as strings. For example,
use <code>'TLSv1_1_method'</code> to force TLS version 1.1, or <code>'TLS_method'</code> to allow
any TLS protocol version up to TLSv1.3. It is not recommended to use TLS
versions less than 1.2, but it may be required for interoperability.
<strong>Default:</strong> none, see <code>minVersion</code>.</li>
<li><code>sessionIdContext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Opaque identifier used by servers to ensure
session state is not shared between applications. Unused by clients.</li>
<li><code>ticketKeys</code>: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> 48-bytes of cryptographically strong pseudorandom
data. See <a href="#all_tls_session-resumption">Session Resumption</a> for more information.</li>
<li><code>sessionTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of seconds after which a TLS session
created by the server will no longer be resumable. See
<a href="#all_tls_session-resumption">Session Resumption</a> for more information. <strong>Default:</strong> <code>300</code>.</li>
</ul>
</li>
</ul>
<p><a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a> sets the default value of the <code>honorCipherOrder</code> option
to <code>true</code>, other APIs that create secure contexts leave it unset.</p>
<p><a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a> uses a 128 bit truncated SHA1 hash value generated
from <code>process.argv</code> as the default value of the <code>sessionIdContext</code> option, other
APIs that create secure contexts have no default value.</p>
<p>The <code>tls.createSecureContext()</code> method creates a <code>SecureContext</code> object. It is
usable as an argument to several <code>tls</code> APIs, such as <a href="#all_tls_serveraddcontexthostname-context"><code>server.addContext()</code></a>,
but has no public methods. The <a href="#all_tls_class-tlsserver"><code>tls.Server</code></a> constructor and the
<a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a> method do not support the <code>secureContext</code> option.</p>
<p>A key is <em>required</em> for ciphers that use certificates. Either <code>key</code> or
<code>pfx</code> can be used to provide it.</p>
<p>If the <code>ca</code> option is not given, then Node.js will default to using
<a href="https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt">Mozilla's publicly trusted list of CAs</a>.</p>
<p>Custom DHE parameters are discouraged in favor of the new <code>dhparam: 'auto'</code>
option. When set to <code>'auto'</code>, well-known DHE parameters of sufficient strength
will be selected automatically. Otherwise, if necessary, <code>openssl dhparam</code> can
be used to create custom parameters. The key length must be greater than or
equal to 1024 bits or else an error will be thrown. Although 1024 bits is
permissible, use 2048 bits or larger for stronger security.</p>
</section><section><h3><code>tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])</code><span><a class="mark" href="#all_tls_tlscreatesecurepaircontext-isserver-requestcert-rejectunauthorized-options" id="all_tls_tlscreatesecurepaircontext-isserver-requestcert-rejectunauthorized-options">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.0.0</td>
<td><p>ALPN options are supported now.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p><span>Deprecated since: v0.11.3</span></p></td></tr>
<tr><td>v0.3.2</td>
<td><p><span>Added in: v0.3.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a> instead.</div><p></p>
<ul>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A secure context object as returned by
<code>tls.createSecureContext()</code></li>
<li><code>isServer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> to specify that this TLS connection should be
opened as a server.</li>
<li><code>requestCert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> to specify whether a server should request a
certificate from a connecting client. Only applies when <code>isServer</code> is <code>true</code>.</li>
<li><code>rejectUnauthorized</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If not <code>false</code> a server automatically reject
clients with invalid certificates. Only applies when <code>isServer</code> is <code>true</code>.</li>
<li><code>options</code>
<ul>
<li><code>enableTrace</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>secureContext</code>: A TLS context object from <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a></li>
<li><code>isServer</code>: If <code>true</code> the TLS socket will be instantiated in server-mode.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>server</code> <a href="#all_net_class-netserver" class="type"><net.Server></a> A <a href="#all_net_class-netserver"><code>net.Server</code></a> instance</li>
<li><code>requestCert</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>rejectUnauthorized</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>ALPNProtocols</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>SNICallback</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>session</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> A <code>Buffer</code> instance containing a TLS session.</li>
<li><code>requestOCSP</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, specifies that the OCSP status request
extension will be added to the client hello and an <code>'OCSPResponse'</code> event
will be emitted on the socket before establishing a secure communication.</li>
</ul>
</li>
</ul>
<p>Creates a new secure pair object with two streams, one of which reads and writes
the encrypted data and the other of which reads and writes the cleartext data.
Generally, the encrypted stream is piped to/from an incoming encrypted data
stream and the cleartext one is used as a replacement for the initial encrypted
stream.</p>
<p><code>tls.createSecurePair()</code> returns a <code>tls.SecurePair</code> object with <code>cleartext</code> and
<code>encrypted</code> stream properties.</p>
<p>Using <code>cleartext</code> has the same API as <a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a>.</p>
<p>The <code>tls.createSecurePair()</code> method is now deprecated in favor of
<code>tls.TLSSocket()</code>. For example, the code:</p>
<pre><code class="language-js">pair = tls.<span class="hljs-title function_">createSecurePair</span>(<span class="hljs-comment">/* ... */</span>);
pair.<span class="hljs-property">encrypted</span>.<span class="hljs-title function_">pipe</span>(socket);
socket.<span class="hljs-title function_">pipe</span>(pair.<span class="hljs-property">encrypted</span>);</code> <button class="copy-button">copy</button></pre>
<p>can be replaced by:</p>
<pre><code class="language-js">secureSocket = tls.<span class="hljs-title class_">TLSSocket</span>(socket, options);</code> <button class="copy-button">copy</button></pre>
<p>where <code>secureSocket</code> has the same API as <code>pair.cleartext</code>.</p>
</section><section><h3><code>tls.createServer([options][, secureConnectionListener])</code><span><a class="mark" href="#all_tls_tlscreateserveroptions-secureconnectionlistener" id="all_tls_tlscreateserveroptions-secureconnectionlistener">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_createserver_options_secureconnectionlistener"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>clientCertEngine</code> option depends on custom engine support in OpenSSL which is deprecated in OpenSSL 3.</p></td></tr>
<tr><td>v19.0.0</td>
<td><p>If <code>ALPNProtocols</code> is set, incoming connections that send an ALPN extension with no supported protocols are terminated with a fatal <code>no_application_protocol</code> alert.</p></td></tr>
<tr><td>v20.4.0, v18.19.0</td>
<td><p>The <code>options</code> parameter can now include <code>ALPNCallback</code>.</p></td></tr>
<tr><td>v12.3.0</td>
<td><p>The <code>options</code> parameter now supports <code>net.createServer()</code> options.</p></td></tr>
<tr><td>v9.3.0</td>
<td><p>The <code>options</code> parameter can now include <code>clientCertEngine</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>ALPNProtocols</code> option can be a <code>TypedArray</code> or <code>DataView</code> now.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>ALPN options are supported now.</p></td></tr>
<tr><td>v0.3.2</td>
<td><p><span>Added in: v0.3.2</span></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>ALPNProtocols</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#all_buffer_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="#all_buffer_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>
An array of strings, <code>Buffer</code>s, <code>TypedArray</code>s, or <code>DataView</code>s, or a single
<code>Buffer</code>, <code>TypedArray</code>, or <code>DataView</code> containing the supported ALPN
protocols. <code>Buffer</code>s should have the format <code>[len][name][len][name]...</code>
e.g. <code>0x05hello0x05world</code>, where the first byte is the length of the next
protocol name. Passing an array is usually much simpler, e.g.
<code>['hello', 'world']</code>. (Protocols should be ordered by their priority.)</li>
<li><code>ALPNCallback</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> If set, this will be called when a
client opens a connection using the ALPN extension. One argument will
be passed to the callback: an object containing <code>servername</code> and
<code>protocols</code> fields, respectively containing the server name from
the SNI extension (if any) and an array of ALPN protocol name strings. The
callback must return either one of the strings listed in
<code>protocols</code>, which will be returned to the client as the selected
ALPN protocol, or <code>undefined</code>, to reject the connection with a fatal alert.
If a string is returned that does not match one of the client's ALPN
protocols, an error will be thrown. This option cannot be used with the
<code>ALPNProtocols</code> option, and setting both options will throw an error.</li>
<li><code>clientCertEngine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of an OpenSSL engine which can provide the
client certificate. <strong>Deprecated.</strong></li>
<li><code>enableTrace</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, <a href="#all_tls_tlssocketenabletrace"><code>tls.TLSSocket.enableTrace()</code></a> will be
called on new connections. Tracing can be enabled after the secure
connection is established, but this option must be used to trace the secure
connection setup. <strong>Default:</strong> <code>false</code>.</li>
<li><code>handshakeTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Abort the connection if the SSL/TLS handshake
does not finish in the specified number of milliseconds.
A <code>'tlsClientError'</code> is emitted on the <code>tls.Server</code> object whenever
a handshake times out. <strong>Default:</strong> <code>120000</code> (120 seconds).</li>
<li><code>rejectUnauthorized</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If not <code>false</code> the server will reject any
connection which is not authorized with the list of supplied CAs. This
option only has an effect if <code>requestCert</code> is <code>true</code>. <strong>Default:</strong> <code>true</code>.</li>
<li><code>requestCert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code> the server will request a certificate from
clients that connect and attempt to verify that certificate. <strong>Default:</strong>
<code>false</code>.</li>
<li><code>sessionTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of seconds after which a TLS session
created by the server will no longer be resumable. See
<a href="#all_tls_session-resumption">Session Resumption</a> for more information. <strong>Default:</strong> <code>300</code>.</li>
<li><code>SNICallback(servername, callback)</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A function that will be
called if the client supports SNI TLS extension. Two arguments will be
passed when called: <code>servername</code> and <code>callback</code>. <code>callback</code> is an
error-first callback that takes two optional arguments: <code>error</code> and <code>ctx</code>.
<code>ctx</code>, if provided, is a <code>SecureContext</code> instance.
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> can be used to get a proper <code>SecureContext</code>.
If <code>callback</code> is called with a falsy <code>ctx</code> argument, the default secure
context of the server will be used. If <code>SNICallback</code> wasn't provided the
default callback with high-level API will be used (see below).</li>
<li><code>ticketKeys</code>: <a href="#all_buffer_class-buffer" class="type"><Buffer></a> 48-bytes of cryptographically strong pseudorandom
data. See <a href="#all_tls_session-resumption">Session Resumption</a> for more information.</li>
<li><code>pskCallback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> For TLS-PSK negotiation, see <a href="#all_tls_pre-shared-keys">Pre-shared keys</a>.</li>
<li><code>pskIdentityHint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> optional hint to send to a client to help
with selecting the identity during TLS-PSK negotiation. Will be ignored
in TLS 1.3. Upon failing to set pskIdentityHint <code>'tlsClientError'</code> will be
emitted with <code>'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED'</code> code.</li>
<li>...: Any <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> option can be provided. For
servers, the identity options (<code>pfx</code>, <code>key</code>/<code>cert</code>, or <code>pskCallback</code>)
are usually required.</li>
<li>...: Any <a href="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer()</code></a> option can be provided.</li>
</ul>
</li>
<li><code>secureConnectionListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="#all_tls_class-tlsserver" class="type"><tls.Server></a></li>
</ul>
<p>Creates a new <a href="#all_tls_class-tlsserver"><code>tls.Server</code></a>. The <code>secureConnectionListener</code>, if provided, is
automatically set as a listener for the <a href="#all_tls_event-secureconnection"><code>'secureConnection'</code></a> event.</p>
<p>The <code>ticketKeys</code> options is automatically shared between <code>node:cluster</code> module
workers.</p>
<p>The following illustrates a simple echo server:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> tls = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:tls'</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> options = {
<span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-key.pem'</span>),
<span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-cert.pem'</span>),
<span class="hljs-comment">// This is necessary only if using client certificate authentication.</span>
<span class="hljs-attr">requestCert</span>: <span class="hljs-literal">true</span>,
<span class="hljs-comment">// This is necessary only if the client uses a self-signed certificate.</span>
<span class="hljs-attr">ca</span>: [ fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'client-cert.pem'</span>) ],
};
<span class="hljs-keyword">const</span> server = tls.<span class="hljs-title function_">createServer</span>(options, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server connected'</span>,
socket.<span class="hljs-property">authorized</span> ? <span class="hljs-string">'authorized'</span> : <span class="hljs-string">'unauthorized'</span>);
socket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'welcome!\n'</span>);
socket.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
socket.<span class="hljs-title function_">pipe</span>(socket);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server bound'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>The server can be tested by connecting to it using the example client from
<a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>.</p>
</section><section><h3><code>tls.getCiphers()</code><span><a class="mark" href="#all_tls_tlsgetciphers" id="all_tls_tlsgetciphers">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_getciphers"></a></h3>
<div class="api_metadata">
<span>Added in: v0.10.2</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>Returns an array with the names of the supported TLS ciphers. The names are
lower-case for historical reasons, but must be uppercased to be used in
the <code>ciphers</code> option of <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>.</p>
<p>Not all supported ciphers are enabled by default. See
<a href="#all_tls_modifying-the-default-tls-cipher-suite">Modifying the default TLS cipher suite</a>.</p>
<p>Cipher names that start with <code>'tls_'</code> are for TLSv1.3, all the others are for
TLSv1.2 and below.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(tls.<span class="hljs-title function_">getCiphers</span>()); <span class="hljs-comment">// ['aes128-gcm-sha256', 'aes128-sha', ...]</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>tls.rootCertificates</code><span><a class="mark" href="#all_tls_tlsrootcertificates" id="all_tls_tlsrootcertificates">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_rootcertificates"></a></h3>
<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#String_type" class="type"><string[]></a></li>
</ul>
<p>An immutable array of strings representing the root certificates (in PEM format)
from the bundled Mozilla CA store as supplied by the current Node.js version.</p>
<p>The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store
that is fixed at release time. It is identical on all supported platforms.</p>
</section><section><h3><code>tls.DEFAULT_ECDH_CURVE</code><span><a class="mark" href="#all_tls_tlsdefault_ecdh_curve" id="all_tls_tlsdefault_ecdh_curve">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_default_ecdh_curve"></a></h3>
<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>Default value changed to <code>'auto'</code>.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The default curve name to use for ECDH key agreement in a tls server. The
default value is <code>'auto'</code>. See <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> for further
information.</p>
</section><section><h3><code>tls.DEFAULT_MAX_VERSION</code><span><a class="mark" href="#all_tls_tlsdefault_max_version" id="all_tls_tlsdefault_max_version">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_default_max_version"></a></h3>
<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#String_type" class="type"><string></a> The default value of the <code>maxVersion</code> option of
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>. It can be assigned any of the supported TLS
protocol versions, <code>'TLSv1.3'</code>, <code>'TLSv1.2'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1'</code>.
<strong>Default:</strong> <code>'TLSv1.3'</code>, unless changed using CLI options. Using
<code>--tls-max-v1.2</code> sets the default to <code>'TLSv1.2'</code>. Using <code>--tls-max-v1.3</code> sets
the default to <code>'TLSv1.3'</code>. If multiple of the options are provided, the
highest maximum is used.</li>
</ul>
</section><section><h3><code>tls.DEFAULT_MIN_VERSION</code><span><a class="mark" href="#all_tls_tlsdefault_min_version" id="all_tls_tlsdefault_min_version">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_default_min_version"></a></h3>
<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#String_type" class="type"><string></a> The default value of the <code>minVersion</code> option of
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>. It can be assigned any of the supported TLS
protocol versions, <code>'TLSv1.3'</code>, <code>'TLSv1.2'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1'</code>.
<strong>Default:</strong> <code>'TLSv1.2'</code>, unless changed using CLI options. Using
<code>--tls-min-v1.0</code> sets the default to <code>'TLSv1'</code>. Using <code>--tls-min-v1.1</code> sets
the default to <code>'TLSv1.1'</code>. Using <code>--tls-min-v1.3</code> sets the default to
<code>'TLSv1.3'</code>. If multiple of the options are provided, the lowest minimum is
used.</li>
</ul>
</section><section><h3><code>tls.DEFAULT_CIPHERS</code><span><a class="mark" href="#all_tls_tlsdefault_ciphers" id="all_tls_tlsdefault_ciphers">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_default_ciphers"></a></h3>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The default value of the <code>ciphers</code> option of
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>. It can be assigned any of the supported
OpenSSL ciphers. Defaults to the content of
<code>crypto.constants.defaultCoreCipherList</code>, unless changed using CLI options
using <code>--tls-default-ciphers</code>.</li>
</ul></section>
</section>
<section><h2>Trace events<span><a class="mark" href="#all_tracing_trace-events" id="all_tracing_trace-events">#</a></span><a aria-hidden="true" class="legacy" id="tracing_trace_events"></a></h2>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/trace_events.js">lib/trace_events.js</a></p>
<p>The <code>node:trace_events</code> module provides a mechanism to centralize tracing
information generated by V8, Node.js core, and userspace code.</p>
<p>Tracing can be enabled with the <code>--trace-event-categories</code> command-line flag
or by using the <code>node:trace_events</code> module. The <code>--trace-event-categories</code> flag
accepts a list of comma-separated category names.</p>
<p>The available categories are:</p>
<ul>
<li><code>node</code>: An empty placeholder.</li>
<li><code>node.async_hooks</code>: Enables capture of detailed <a href="async_hooks.html"><code>async_hooks</code></a> trace data.
The <a href="async_hooks.html"><code>async_hooks</code></a> events have a unique <code>asyncId</code> and a special <code>triggerId</code>
<code>triggerAsyncId</code> property.</li>
<li><code>node.bootstrap</code>: Enables capture of Node.js bootstrap milestones.</li>
<li><code>node.console</code>: Enables capture of <code>console.time()</code> and <code>console.count()</code>
output.</li>
<li><code>node.threadpoolwork.sync</code>: Enables capture of trace data for threadpool
synchronous operations, such as <code>blob</code>, <code>zlib</code>, <code>crypto</code> and <code>node_api</code>.</li>
<li><code>node.threadpoolwork.async</code>: Enables capture of trace data for threadpool
asynchronous operations, such as <code>blob</code>, <code>zlib</code>, <code>crypto</code> and <code>node_api</code>.</li>
<li><code>node.dns.native</code>: Enables capture of trace data for DNS queries.</li>
<li><code>node.net.native</code>: Enables capture of trace data for network.</li>
<li><code>node.environment</code>: Enables capture of Node.js Environment milestones.</li>
<li><code>node.fs.sync</code>: Enables capture of trace data for file system sync methods.</li>
<li><code>node.fs_dir.sync</code>: Enables capture of trace data for file system sync
directory methods.</li>
<li><code>node.fs.async</code>: Enables capture of trace data for file system async methods.</li>
<li><code>node.fs_dir.async</code>: Enables capture of trace data for file system async
directory methods.</li>
<li><code>node.perf</code>: Enables capture of <a href="perf_hooks.html">Performance API</a> measurements.
<ul>
<li><code>node.perf.usertiming</code>: Enables capture of only Performance API User Timing
measures and marks.</li>
<li><code>node.perf.timerify</code>: Enables capture of only Performance API timerify
measurements.</li>
</ul>
</li>
<li><code>node.promises.rejections</code>: Enables capture of trace data tracking the number
of unhandled Promise rejections and handled-after-rejections.</li>
<li><code>node.vm.script</code>: Enables capture of trace data for the <code>node:vm</code> module's
<code>runInNewContext()</code>, <code>runInContext()</code>, and <code>runInThisContext()</code> methods.</li>
<li><code>v8</code>: The <a href="v8.html">V8</a> events are GC, compiling, and execution related.</li>
<li><code>node.http</code>: Enables capture of trace data for http request / response.</li>
<li><code>node.module_timer</code>: Enables capture of trace data for CJS Module loading.</li>
</ul>
<p>By default the <code>node</code>, <code>node.async_hooks</code>, and <code>v8</code> categories are enabled.</p>
<pre><code class="language-bash">node --trace-event-categories v8,node,node.async_hooks server.js</code> <button class="copy-button">copy</button></pre>
<p>Prior versions of Node.js required the use of the <code>--trace-events-enabled</code>
flag to enable trace events. This requirement has been removed. However, the
<code>--trace-events-enabled</code> flag <em>may</em> still be used and will enable the
<code>node</code>, <code>node.async_hooks</code>, and <code>v8</code> trace event categories by default.</p>
<pre><code class="language-bash">node --trace-events-enabled
<span class="hljs-comment"># is equivalent to</span>
node --trace-event-categories v8,node,node.async_hooks</code> <button class="copy-button">copy</button></pre>
<p>Alternatively, trace events may be enabled using the <code>node:trace_events</code> module:</p>
<pre class="with-61-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> { createTracing } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:trace_events'</span>;
<span class="hljs-keyword">const</span> tracing = <span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node.perf'</span>] });
tracing.<span class="hljs-title function_">enable</span>(); <span class="hljs-comment">// Enable trace event capture for the 'node.perf' category</span>
<span class="hljs-comment">// do work</span>
tracing.<span class="hljs-title function_">disable</span>(); <span class="hljs-comment">// Disable trace event capture for the 'node.perf' category</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createTracing } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:trace_events'</span>);
<span class="hljs-keyword">const</span> tracing = <span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node.perf'</span>] });
tracing.<span class="hljs-title function_">enable</span>(); <span class="hljs-comment">// Enable trace event capture for the 'node.perf' category</span>
<span class="hljs-comment">// do work</span>
tracing.<span class="hljs-title function_">disable</span>(); <span class="hljs-comment">// Disable trace event capture for the 'node.perf' category</span></code><button class="copy-button">copy</button></pre>
<p>Running Node.js with tracing enabled will produce log files that can be opened
in the <a href="https://www.chromium.org/developers/how-tos/trace-event-profiling-tool"><code>chrome://tracing</code></a>
tab of Chrome.</p>
<p>The logging file is by default called <code>node_trace.${rotation}.log</code>, where
<code>${rotation}</code> is an incrementing log-rotation id. The filepath pattern can
be specified with <code>--trace-event-file-pattern</code> that accepts a template
string that supports <code>${rotation}</code> and <code>${pid}</code>:</p>
<pre><code class="language-bash">node --trace-event-categories v8 --trace-event-file-pattern <span class="hljs-string">'${pid}-${rotation}.log'</span> server.js</code> <button class="copy-button">copy</button></pre>
<p>To guarantee that the log file is properly generated after signal events like
<code>SIGINT</code>, <code>SIGTERM</code>, or <code>SIGBREAK</code>, make sure to have the appropriate handlers
in your code, such as:</p>
<pre><code class="language-js">process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">onSigint</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">info</span>(<span class="hljs-string">'Received SIGINT.'</span>);
process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">130</span>); <span class="hljs-comment">// Or applicable exit code depending on OS and signal</span>
});</code> <button class="copy-button">copy</button></pre>
<p>The tracing system uses the same time source
as the one used by <code>process.hrtime()</code>.
However the trace-event timestamps are expressed in microseconds,
unlike <code>process.hrtime()</code> which returns nanoseconds.</p>
<p>The features from this module are not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
<section><h3>The <code>node:trace_events</code> module<span><a class="mark" href="#all_tracing_the-nodetrace_events-module" id="all_tracing_the-nodetrace_events-module">#</a></span><a aria-hidden="true" class="legacy" id="tracing_the_node_trace_events_module"></a></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<h4><code>Tracing</code> object<span><a class="mark" href="#all_tracing_tracing-object" id="all_tracing_tracing-object">#</a></span><a aria-hidden="true" class="legacy" id="tracing_tracing_object"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>The <code>Tracing</code> object is used to enable or disable tracing for sets of
categories. Instances are created using the <code>trace_events.createTracing()</code>
method.</p>
<p>When created, the <code>Tracing</code> object is disabled. Calling the
<code>tracing.enable()</code> method adds the categories to the set of enabled trace event
categories. Calling <code>tracing.disable()</code> will remove the categories from the
set of enabled trace event categories.</p>
<h5><code>tracing.categories</code><span><a class="mark" href="#all_tracing_tracingcategories" id="all_tracing_tracingcategories">#</a></span><a aria-hidden="true" class="legacy" id="tracing_tracing_categories"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>A comma-separated list of the trace event categories covered by this
<code>Tracing</code> object.</p>
<h5><code>tracing.disable()</code><span><a class="mark" href="#all_tracing_tracingdisable" id="all_tracing_tracingdisable">#</a></span><a aria-hidden="true" class="legacy" id="tracing_tracing_disable"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>Disables this <code>Tracing</code> object.</p>
<p>Only trace event categories <em>not</em> covered by other enabled <code>Tracing</code> objects
and <em>not</em> specified by the <code>--trace-event-categories</code> flag will be disabled.</p>
<pre class="with-77-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> { createTracing, getEnabledCategories } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:trace_events'</span>;
<span class="hljs-keyword">const</span> t1 = <span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node'</span>, <span class="hljs-string">'v8'</span>] });
<span class="hljs-keyword">const</span> t2 = <span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node.perf'</span>, <span class="hljs-string">'node'</span>] });
t1.<span class="hljs-title function_">enable</span>();
t2.<span class="hljs-title function_">enable</span>();
<span class="hljs-comment">// Prints 'node,node.perf,v8'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEnabledCategories</span>());
t2.<span class="hljs-title function_">disable</span>(); <span class="hljs-comment">// Will only disable emission of the 'node.perf' category</span>
<span class="hljs-comment">// Prints 'node,v8'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEnabledCategories</span>());</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createTracing, getEnabledCategories } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:trace_events'</span>);
<span class="hljs-keyword">const</span> t1 = <span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node'</span>, <span class="hljs-string">'v8'</span>] });
<span class="hljs-keyword">const</span> t2 = <span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node.perf'</span>, <span class="hljs-string">'node'</span>] });
t1.<span class="hljs-title function_">enable</span>();
t2.<span class="hljs-title function_">enable</span>();
<span class="hljs-comment">// Prints 'node,node.perf,v8'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEnabledCategories</span>());
t2.<span class="hljs-title function_">disable</span>(); <span class="hljs-comment">// Will only disable emission of the 'node.perf' category</span>
<span class="hljs-comment">// Prints 'node,v8'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEnabledCategories</span>());</code><button class="copy-button">copy</button></pre>
<h5><code>tracing.enable()</code><span><a class="mark" href="#all_tracing_tracingenable" id="all_tracing_tracingenable">#</a></span><a aria-hidden="true" class="legacy" id="tracing_tracing_enable"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>Enables this <code>Tracing</code> object for the set of categories covered by the
<code>Tracing</code> object.</p>
<h5><code>tracing.enabled</code><span><a class="mark" href="#all_tracing_tracingenabled" id="all_tracing_tracingenabled">#</a></span><a aria-hidden="true" class="legacy" id="tracing_tracing_enabled"></a></h5>
<div class="api_metadata">
<span>Added in: v10.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> <code>true</code> only if the <code>Tracing</code> object has been enabled.</li>
</ul>
<h4><code>trace_events.createTracing(options)</code><span><a class="mark" href="#all_tracing_trace_eventscreatetracingoptions" id="all_tracing_trace_eventscreatetracingoptions">#</a></span><a aria-hidden="true" class="legacy" id="tracing_trace_events_createtracing_options"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.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>
<ul>
<li><code>categories</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array of trace category names. Values included
in the array are coerced to a string when possible. An error will be
thrown if the value cannot be coerced.</li>
</ul>
</li>
<li>Returns: <a href="#all_tracing_tracing-object" class="type"><Tracing></a>.</li>
</ul>
<p>Creates and returns a <code>Tracing</code> object for the given set of <code>categories</code>.</p>
<pre class="with-55-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> { createTracing } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:trace_events'</span>;
<span class="hljs-keyword">const</span> categories = [<span class="hljs-string">'node.perf'</span>, <span class="hljs-string">'node.async_hooks'</span>];
<span class="hljs-keyword">const</span> tracing = <span class="hljs-title function_">createTracing</span>({ categories });
tracing.<span class="hljs-title function_">enable</span>();
<span class="hljs-comment">// do stuff</span>
tracing.<span class="hljs-title function_">disable</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createTracing } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:trace_events'</span>);
<span class="hljs-keyword">const</span> categories = [<span class="hljs-string">'node.perf'</span>, <span class="hljs-string">'node.async_hooks'</span>];
<span class="hljs-keyword">const</span> tracing = <span class="hljs-title function_">createTracing</span>({ categories });
tracing.<span class="hljs-title function_">enable</span>();
<span class="hljs-comment">// do stuff</span>
tracing.<span class="hljs-title function_">disable</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>trace_events.getEnabledCategories()</code><span><a class="mark" href="#all_tracing_trace_eventsgetenabledcategories" id="all_tracing_trace_eventsgetenabledcategories">#</a></span><a aria-hidden="true" class="legacy" id="tracing_trace_events_getenabledcategories"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns a comma-separated list of all currently-enabled trace event
categories. The current set of enabled trace event categories is determined
by the <em>union</em> of all currently-enabled <code>Tracing</code> objects and any categories
enabled using the <code>--trace-event-categories</code> flag.</p>
<p>Given the file <code>test.js</code> below, the command
<code>node --trace-event-categories node.perf test.js</code> will print
<code>'node.async_hooks,node.perf'</code> to the console.</p>
<pre class="with-77-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> { createTracing, getEnabledCategories } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:trace_events'</span>;
<span class="hljs-keyword">const</span> t1 = <span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node.async_hooks'</span>] });
<span class="hljs-keyword">const</span> t2 = <span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node.perf'</span>] });
<span class="hljs-keyword">const</span> t3 = <span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'v8'</span>] });
t1.<span class="hljs-title function_">enable</span>();
t2.<span class="hljs-title function_">enable</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEnabledCategories</span>());</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createTracing, getEnabledCategories } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:trace_events'</span>);
<span class="hljs-keyword">const</span> t1 = <span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node.async_hooks'</span>] });
<span class="hljs-keyword">const</span> t2 = <span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node.perf'</span>] });
<span class="hljs-keyword">const</span> t3 = <span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'v8'</span>] });
t1.<span class="hljs-title function_">enable</span>();
t2.<span class="hljs-title function_">enable</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEnabledCategories</span>());</code><button class="copy-button">copy</button></pre>
</section><section><h3>Examples<span><a class="mark" href="#all_tracing_examples" id="all_tracing_examples">#</a></span><a aria-hidden="true" class="legacy" id="tracing_examples"></a></h3>
<h4>Collect trace events data by inspector<span><a class="mark" href="#all_tracing_collect-trace-events-data-by-inspector" id="all_tracing_collect-trace-events-data-by-inspector">#</a></span><a aria-hidden="true" class="legacy" id="tracing_collect_trace_events_data_by_inspector"></a></h4>
<pre class="with-41-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_">Session</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:inspector'</span>;
<span class="hljs-keyword">const</span> session = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Session</span>();
session.<span class="hljs-title function_">connect</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">post</span>(<span class="hljs-params">message, data</span>) {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
session.<span class="hljs-title function_">post</span>(message, data, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =></span> {
<span class="hljs-keyword">if</span> (err)
<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(err)));
<span class="hljs-keyword">else</span>
<span class="hljs-title function_">resolve</span>(result);
});
});
}
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">collect</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> data = [];
session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'NodeTracing.dataCollected'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> data.<span class="hljs-title function_">push</span>(chunk));
session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'NodeTracing.tracingComplete'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// done</span>
});
<span class="hljs-keyword">const</span> traceConfig = { <span class="hljs-attr">includedCategories</span>: [<span class="hljs-string">'v8'</span>] };
<span class="hljs-keyword">await</span> <span class="hljs-title function_">post</span>(<span class="hljs-string">'NodeTracing.start'</span>, { traceConfig });
<span class="hljs-comment">// do something</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
<span class="hljs-title function_">post</span>(<span class="hljs-string">'NodeTracing.stop'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
session.<span class="hljs-title function_">disconnect</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
});
}, <span class="hljs-number">1000</span>);
}
<span class="hljs-title function_">collect</span>();</code><code class="language-js cjs"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Session</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'inspector'</span>);
<span class="hljs-keyword">const</span> session = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Session</span>();
session.<span class="hljs-title function_">connect</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">post</span>(<span class="hljs-params">message, data</span>) {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
session.<span class="hljs-title function_">post</span>(message, data, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =></span> {
<span class="hljs-keyword">if</span> (err)
<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(err)));
<span class="hljs-keyword">else</span>
<span class="hljs-title function_">resolve</span>(result);
});
});
}
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">collect</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> data = [];
session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'NodeTracing.dataCollected'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> data.<span class="hljs-title function_">push</span>(chunk));
session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'NodeTracing.tracingComplete'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// done</span>
});
<span class="hljs-keyword">const</span> traceConfig = { <span class="hljs-attr">includedCategories</span>: [<span class="hljs-string">'v8'</span>] };
<span class="hljs-keyword">await</span> <span class="hljs-title function_">post</span>(<span class="hljs-string">'NodeTracing.start'</span>, { traceConfig });
<span class="hljs-comment">// do something</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
<span class="hljs-title function_">post</span>(<span class="hljs-string">'NodeTracing.stop'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
session.<span class="hljs-title function_">disconnect</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
});
}, <span class="hljs-number">1000</span>);
}
<span class="hljs-title function_">collect</span>();</code><button class="copy-button">copy</button></pre></section>
</section>
<section><h2>TTY<span><a class="mark" href="#all_tty_tty" id="all_tty_tty">#</a></span><a aria-hidden="true" class="legacy" id="tty_tty"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/tty.js">lib/tty.js</a></p>
<p>The <code>node:tty</code> module provides the <code>tty.ReadStream</code> and <code>tty.WriteStream</code>
classes. In most cases, it will not be necessary or possible to use this module
directly. However, it can be accessed using:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> tty = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:tty'</span>);</code> <button class="copy-button">copy</button></pre>
<p>When Node.js detects that it is being run with a text terminal ("TTY")
attached, <a href="#all_process_processstdin"><code>process.stdin</code></a> will, by default, be initialized as an instance of
<code>tty.ReadStream</code> and both <a href="#all_process_processstdout"><code>process.stdout</code></a> and <a href="#all_process_processstderr"><code>process.stderr</code></a> will, by
default, be instances of <code>tty.WriteStream</code>. The preferred method of determining
whether Node.js is being run within a TTY context is to check that the value of
the <code>process.stdout.isTTY</code> property is <code>true</code>:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p -e <span class="hljs-string">"Boolean(process.stdout.isTTY)"</span></span>
true
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p -e <span class="hljs-string">"Boolean(process.stdout.isTTY)"</span> | <span class="hljs-built_in">cat</span></span>
false</code> <button class="copy-button">copy</button></pre>
<p>In most cases, there should be little to no reason for an application to
manually create instances of the <code>tty.ReadStream</code> and <code>tty.WriteStream</code>
classes.</p>
<section><h3>Class: <code>tty.ReadStream</code><span><a class="mark" href="#all_tty_class-ttyreadstream" id="all_tty_class-ttyreadstream">#</a></span><a aria-hidden="true" class="legacy" id="tty_class_tty_readstream"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li>Extends: <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
</ul>
<p>Represents the readable side of a TTY. In normal circumstances
<a href="#all_process_processstdin"><code>process.stdin</code></a> will be the only <code>tty.ReadStream</code> instance in a Node.js
process and there should be no reason to create additional instances.</p>
<h4><code>readStream.isRaw</code><span><a class="mark" href="#all_tty_readstreamisraw" id="all_tty_readstreamisraw">#</a></span><a aria-hidden="true" class="legacy" id="tty_readstream_israw"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<p>A <code>boolean</code> that is <code>true</code> if the TTY is currently configured to operate as a
raw device.</p>
<p>This flag is always <code>false</code> when a process starts, even if the terminal is
operating in raw mode. Its value will change with subsequent calls to
<code>setRawMode</code>.</p>
<h4><code>readStream.isTTY</code><span><a class="mark" href="#all_tty_readstreamistty" id="all_tty_readstreamistty">#</a></span><a aria-hidden="true" class="legacy" id="tty_readstream_istty"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<p>A <code>boolean</code> that is always <code>true</code> for <code>tty.ReadStream</code> instances.</p>
<h4><code>readStream.setRawMode(mode)</code><span><a class="mark" href="#all_tty_readstreamsetrawmodemode" id="all_tty_readstreamsetrawmodemode">#</a></span><a aria-hidden="true" class="legacy" id="tty_readstream_setrawmode_mode"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<ul>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, configures the <code>tty.ReadStream</code> to operate as a
raw device. If <code>false</code>, configures the <code>tty.ReadStream</code> to operate in its
default mode. The <code>readStream.isRaw</code> property will be set to the resulting
mode.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a> The read stream instance.</li>
</ul>
<p>Allows configuration of <code>tty.ReadStream</code> so that it operates as a raw device.</p>
<p>When in raw mode, input is always available character-by-character, not
including modifiers. Additionally, all special processing of characters by the
terminal is disabled, including echoing input
characters. <kbd>Ctrl</kbd>+<kbd>C</kbd> will no longer cause a <code>SIGINT</code> when
in this mode.</p>
</section><section><h3>Class: <code>tty.WriteStream</code><span><a class="mark" href="#all_tty_class-ttywritestream" id="all_tty_class-ttywritestream">#</a></span><a aria-hidden="true" class="legacy" id="tty_class_tty_writestream"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li>Extends: <a href="#all_net_class-netsocket" class="type"><net.Socket></a></li>
</ul>
<p>Represents the writable side of a TTY. In normal circumstances,
<a href="#all_process_processstdout"><code>process.stdout</code></a> and <a href="#all_process_processstderr"><code>process.stderr</code></a> will be the only
<code>tty.WriteStream</code> instances created for a Node.js process and there
should be no reason to create additional instances.</p>
<h4><code>new tty.ReadStream(fd[, options])</code><span><a class="mark" href="#all_tty_new-ttyreadstreamfd-options" id="all_tty_new-ttyreadstreamfd-options">#</a></span><a aria-hidden="true" class="legacy" id="tty_new_tty_readstream_fd_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>v0.9.4</td>
<td><p>The <code>options</code> argument is supported.</p></td></tr>
<tr><td>v0.5.8</td>
<td><p><span>Added in: v0.5.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A file descriptor associated with a TTY.</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 passed to parent <code>net.Socket</code>,
see <code>options</code> of <a href="#all_net_new-netsocketoptions"><code>net.Socket</code> constructor</a>.</li>
<li>Returns <a href="#all_tty_class-ttyreadstream" class="type"><tty.ReadStream></a></li>
</ul>
<p>Creates a <code>ReadStream</code> for <code>fd</code> associated with a TTY.</p>
<h4><code>new tty.WriteStream(fd)</code><span><a class="mark" href="#all_tty_new-ttywritestreamfd" id="all_tty_new-ttywritestreamfd">#</a></span><a aria-hidden="true" class="legacy" id="tty_new_tty_writestream_fd"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A file descriptor associated with a TTY.</li>
<li>Returns <a href="#all_tty_class-ttywritestream" class="type"><tty.WriteStream></a></li>
</ul>
<p>Creates a <code>WriteStream</code> for <code>fd</code> associated with a TTY.</p>
<h4>Event: <code>'resize'</code><span><a class="mark" href="#all_tty_event-resize" id="all_tty_event-resize">#</a></span><a aria-hidden="true" class="legacy" id="tty_event_resize"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<p>The <code>'resize'</code> event is emitted whenever either of the <code>writeStream.columns</code>
or <code>writeStream.rows</code> properties have changed. No arguments are passed to the
listener callback when called.</p>
<pre><code class="language-js">process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'resize'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'screen size has changed!'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${process.stdout.columns}</span>x<span class="hljs-subst">${process.stdout.rows}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>writeStream.clearLine(dir[, callback])</code><span><a class="mark" href="#all_tty_writestreamclearlinedir-callback" id="all_tty_writestreamclearlinedir-callback">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_clearline_dir_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>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a>
<ul>
<li><code>-1</code>: to the left from cursor</li>
<li><code>1</code>: to the right from cursor</li>
<li><code>0</code>: the entire line</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> Invoked once the operation completes.</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><code>writeStream.clearLine()</code> clears the current line of this <code>WriteStream</code> in a
direction identified by <code>dir</code>.</p>
<h4><code>writeStream.clearScreenDown([callback])</code><span><a class="mark" href="#all_tty_writestreamclearscreendowncallback" id="all_tty_writestreamclearscreendowncallback">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_clearscreendown_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>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</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> Invoked once the operation completes.</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><code>writeStream.clearScreenDown()</code> clears this <code>WriteStream</code> from the current
cursor down.</p>
<h4><code>writeStream.columns</code><span><a class="mark" href="#all_tty_writestreamcolumns" id="all_tty_writestreamcolumns">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_columns"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<p>A <code>number</code> specifying the number of columns the TTY currently has. This property
is updated whenever the <code>'resize'</code> event is emitted.</p>
<h4><code>writeStream.cursorTo(x[, y][, callback])</code><span><a class="mark" href="#all_tty_writestreamcursortox-y-callback" id="all_tty_writestreamcursortox-y-callback">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_cursorto_x_y_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>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>x</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>y</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Invoked once the operation completes.</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><code>writeStream.cursorTo()</code> moves this <code>WriteStream</code>'s cursor to the specified
position.</p>
<h4><code>writeStream.getColorDepth([env])</code><span><a class="mark" href="#all_tty_writestreamgetcolordepthenv" id="all_tty_writestreamgetcolordepthenv">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_getcolordepth_env"></a></h4>
<div class="api_metadata">
<span>Added in: v9.9.0</span>
</div>
<ul>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing the environment variables to check. This
enables simulating the usage of a specific terminal. <strong>Default:</strong>
<code>process.env</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Returns:</p>
<ul>
<li><code>1</code> for 2,</li>
<li><code>4</code> for 16,</li>
<li><code>8</code> for 256,</li>
<li><code>24</code> for 16,777,216 colors supported.</li>
</ul>
<p>Use this to determine what colors the terminal supports. Due to the nature of
colors in terminals it is possible to either have false positives or false
negatives. It depends on process information and the environment variables that
may lie about what terminal is used.
It is possible to pass in an <code>env</code> object to simulate the usage of a specific
terminal. This can be useful to check how specific environment settings behave.</p>
<p>To enforce a specific color support, use one of the below environment settings.</p>
<ul>
<li>2 colors: <code>FORCE_COLOR = 0</code> (Disables colors)</li>
<li>16 colors: <code>FORCE_COLOR = 1</code></li>
<li>256 colors: <code>FORCE_COLOR = 2</code></li>
<li>16,777,216 colors: <code>FORCE_COLOR = 3</code></li>
</ul>
<p>Disabling color support is also possible by using the <code>NO_COLOR</code> and
<code>NODE_DISABLE_COLORS</code> environment variables.</p>
<h4><code>writeStream.getWindowSize()</code><span><a class="mark" href="#all_tty_writestreamgetwindowsize" id="all_tty_writestreamgetwindowsize">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_getwindowsize"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number[]></a></li>
</ul>
<p><code>writeStream.getWindowSize()</code> returns the size of the TTY
corresponding to this <code>WriteStream</code>. The array is of the type
<code>[numColumns, numRows]</code> where <code>numColumns</code> and <code>numRows</code> represent the number
of columns and rows in the corresponding TTY.</p>
<h4><code>writeStream.hasColors([count][, env])</code><span><a class="mark" href="#all_tty_writestreamhascolorscount-env" id="all_tty_writestreamhascolorscount-env">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_hascolors_count_env"></a></h4>
<div class="api_metadata">
<span>Added in: v11.13.0, v10.16.0</span>
</div>
<ul>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of colors that are requested (minimum 2).
<strong>Default:</strong> 16.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing the environment variables to check. This
enables simulating the usage of a specific terminal. <strong>Default:</strong>
<code>process.env</code>.</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 <code>true</code> if the <code>writeStream</code> supports at least as many colors as provided
in <code>count</code>. Minimum support is 2 (black and white).</p>
<p>This has the same false positives and negatives as described in
<a href="#all_tty_writestreamgetcolordepthenv"><code>writeStream.getColorDepth()</code></a>.</p>
<pre><code class="language-js">process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">hasColors</span>();
<span class="hljs-comment">// Returns true or false depending on if `stdout` supports at least 16 colors.</span>
process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">hasColors</span>(<span class="hljs-number">256</span>);
<span class="hljs-comment">// Returns true or false depending on if `stdout` supports at least 256 colors.</span>
process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">hasColors</span>({ <span class="hljs-attr">TMUX</span>: <span class="hljs-string">'1'</span> });
<span class="hljs-comment">// Returns true.</span>
process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">hasColors</span>(<span class="hljs-number">2</span> ** <span class="hljs-number">24</span>, { <span class="hljs-attr">TMUX</span>: <span class="hljs-string">'1'</span> });
<span class="hljs-comment">// Returns false (the environment setting pretends to support 2 ** 8 colors).</span></code> <button class="copy-button">copy</button></pre>
<h4><code>writeStream.isTTY</code><span><a class="mark" href="#all_tty_writestreamistty" id="all_tty_writestreamistty">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_istty"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<p>A <code>boolean</code> that is always <code>true</code>.</p>
<h4><code>writeStream.moveCursor(dx, dy[, callback])</code><span><a class="mark" href="#all_tty_writestreammovecursordx-dy-callback" id="all_tty_writestreammovecursordx-dy-callback">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_movecursor_dx_dy_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>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>dx</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>dy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Invoked once the operation completes.</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><code>writeStream.moveCursor()</code> moves this <code>WriteStream</code>'s cursor <em>relative</em> to its
current position.</p>
<h4><code>writeStream.rows</code><span><a class="mark" href="#all_tty_writestreamrows" id="all_tty_writestreamrows">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_rows"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<p>A <code>number</code> specifying the number of rows the TTY currently has. This property
is updated whenever the <code>'resize'</code> event is emitted.</p>
</section><section><h3><code>tty.isatty(fd)</code><span><a class="mark" href="#all_tty_ttyisattyfd" id="all_tty_ttyisattyfd">#</a></span><a aria-hidden="true" class="legacy" id="tty_tty_isatty_fd"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A numeric file descriptor</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>The <code>tty.isatty()</code> method returns <code>true</code> if the given <code>fd</code> is associated with
a TTY and <code>false</code> if it is not, including whenever <code>fd</code> is not a non-negative
integer.</p></section>
</section>
<section><h2>UDP/datagram sockets<span><a class="mark" href="#all_dgram_udpdatagram-sockets" id="all_dgram_udpdatagram-sockets">#</a></span><a aria-hidden="true" class="legacy" id="dgram_udp_datagram_sockets"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/dgram.js">lib/dgram.js</a></p>
<p>The <code>node:dgram</code> module provides an implementation of UDP datagram sockets.</p>
<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> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>;
<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>);
server.<span class="hljs-title function_">close</span>();
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server listening <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>);
});
server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>);
<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>);
<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>);
server.<span class="hljs-title function_">close</span>();
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server listening <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>);
});
server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>);
<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code><button class="copy-button">copy</button></pre>
<section><h3>Class: <code>dgram.Socket</code><span><a class="mark" href="#all_dgram_class-dgramsocket" id="all_dgram_class-dgramsocket">#</a></span><a aria-hidden="true" class="legacy" id="dgram_class_dgram_socket"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>Encapsulates the datagram functionality.</p>
<p>New instances of <code>dgram.Socket</code> are created using <a href="#all_dgram_dgramcreatesocketoptions-callback"><code>dgram.createSocket()</code></a>.
The <code>new</code> keyword is not to be used to create <code>dgram.Socket</code> instances.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_dgram_event-close" id="all_dgram_event-close">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_close"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<p>The <code>'close'</code> event is emitted after a socket is closed with <a href="#all_dgram_socketclosecallback"><code>close()</code></a>.
Once triggered, no new <code>'message'</code> events will be emitted on this socket.</p>
<h4>Event: <code>'connect'</code><span><a class="mark" href="#all_dgram_event-connect" id="all_dgram_event-connect">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_connect"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>The <code>'connect'</code> event is emitted after a socket is associated to a remote
address as a result of a successful <a href="#all_dgram_socketconnectport-address-callback"><code>connect()</code></a> call.</p>
<h4>Event: <code>'error'</code><span><a class="mark" href="#all_dgram_event-error" id="all_dgram_event-error">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_error"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<ul>
<li><code>exception</code> <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 whenever any error occurs. The event handler
function is passed a single <code>Error</code> object.</p>
<h4>Event: <code>'listening'</code><span><a class="mark" href="#all_dgram_event-listening" id="all_dgram_event-listening">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_listening"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<p>The <code>'listening'</code> event is emitted once the <code>dgram.Socket</code> is addressable and
can receive data. This happens either explicitly with <code>socket.bind()</code> or
implicitly the first time data is sent using <code>socket.send()</code>.
Until the <code>dgram.Socket</code> is listening, the underlying system resources do not
exist and calls such as <code>socket.address()</code> and <code>socket.setTTL()</code> will fail.</p>
<h4>Event: <code>'message'</code><span><a class="mark" href="#all_dgram_event-message" id="all_dgram_event-message">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_message"></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.4.0</td>
<td><p>The <code>family</code> property now returns a string instead of a number.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>family</code> property now returns a number instead of a string.</p></td></tr>
<tr><td>v0.1.99</td>
<td><p><span>Added in: v0.1.99</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>'message'</code> event is emitted when a new datagram is available on a socket.
The event handler function is passed two arguments: <code>msg</code> and <code>rinfo</code>.</p>
<ul>
<li><code>msg</code> <a href="#all_buffer_class-buffer" class="type"><Buffer></a> The message.</li>
<li><code>rinfo</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Remote address information.
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The sender address.</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The address family (<code>'IPv4'</code> or <code>'IPv6'</code>).</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The sender port.</li>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The message size.</li>
</ul>
</li>
</ul>
<p>If the source address of the incoming packet is an IPv6 link-local
address, the interface name is added to the <code>address</code>. For
example, a packet received on the <code>en0</code> interface might have the
address field set to <code>'fe80::2618:1234:ab11:3b9c%en0'</code>, where <code>'%en0'</code>
is the interface name as a zone ID suffix.</p>
<h4><code>socket.addMembership(multicastAddress[, multicastInterface])</code><span><a class="mark" href="#all_dgram_socketaddmembershipmulticastaddress-multicastinterface" id="all_dgram_socketaddmembershipmulticastaddress-multicastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_addmembership_multicastaddress_multicastinterface"></a></h4>
<div class="api_metadata">
<span>Added in: v0.6.9</span>
</div>
<ul>
<li><code>multicastAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Tells the kernel to join a multicast group at the given <code>multicastAddress</code> and
<code>multicastInterface</code> using the <code>IP_ADD_MEMBERSHIP</code> socket option. If the
<code>multicastInterface</code> argument is not specified, the operating system will choose
one interface and will add membership to it. To add membership to every
available interface, call <code>addMembership</code> multiple times, once per interface.</p>
<p>When called on an unbound socket, this method will implicitly bind to a random
port, listening on all interfaces.</p>
<p>When sharing a UDP socket across multiple <code>cluster</code> workers, the
<code>socket.addMembership()</code> function must be called only once or an
<code>EADDRINUSE</code> error will occur:</p>
<pre class="with-40-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> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
<span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>;
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Works ok.</span>
cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Fails with EADDRINUSE.</span>
} <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">const</span> s = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
s.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
s.<span class="hljs-title function_">addMembership</span>(<span class="hljs-string">'224.0.0.114'</span>);
});
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
<span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>);
<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Works ok.</span>
cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Fails with EADDRINUSE.</span>
} <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">const</span> s = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
s.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
s.<span class="hljs-title function_">addMembership</span>(<span class="hljs-string">'224.0.0.114'</span>);
});
}</code><button class="copy-button">copy</button></pre>
<h4><code>socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code><span><a class="mark" href="#all_dgram_socketaddsourcespecificmembershipsourceaddress-groupaddress-multicastinterface" id="all_dgram_socketaddsourcespecificmembershipsourceaddress-groupaddress-multicastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface"></a></h4>
<div class="api_metadata">
<span>Added in: v13.1.0, v12.16.0</span>
</div>
<ul>
<li><code>sourceAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>groupAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Tells the kernel to join a source-specific multicast channel at the given
<code>sourceAddress</code> and <code>groupAddress</code>, using the <code>multicastInterface</code> with the
<code>IP_ADD_SOURCE_MEMBERSHIP</code> socket option. If the <code>multicastInterface</code> argument
is not specified, the operating system will choose one interface and will add
membership to it. To add membership to every available interface, call
<code>socket.addSourceSpecificMembership()</code> multiple times, once per interface.</p>
<p>When called on an unbound socket, this method will implicitly bind to a random
port, listening on all interfaces.</p>
<h4><code>socket.address()</code><span><a class="mark" href="#all_dgram_socketaddress" id="all_dgram_socketaddress">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_address"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns an object containing the address information for a socket.
For UDP sockets, this object will contain <code>address</code>, <code>family</code>, and <code>port</code>
properties.</p>
<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
<h4><code>socket.bind([port][, address][, callback])</code><span><a class="mark" href="#all_dgram_socketbindport-address-callback" id="all_dgram_socketbindport-address-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_bind_port_address_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>v0.9.1</td>
<td><p>The method was changed to an asynchronous execution model. Legacy code would need to be changed to pass a callback function to the method call.</p></td></tr>
<tr><td>v0.1.99</td>
<td><p><span>Added in: v0.1.99</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> with no parameters. Called when binding is complete.</li>
</ul>
<p>For UDP sockets, causes the <code>dgram.Socket</code> to listen for datagram
messages on a named <code>port</code> and optional <code>address</code>. If <code>port</code> is not
specified or is <code>0</code>, the operating system will attempt to bind to a
random port. If <code>address</code> is not specified, the operating system will
attempt to listen on all addresses. Once binding is complete, a
<code>'listening'</code> event is emitted and the optional <code>callback</code> function is
called.</p>
<p>Specifying both a <code>'listening'</code> event listener and passing a
<code>callback</code> to the <code>socket.bind()</code> method is not harmful but not very
useful.</p>
<p>A bound datagram socket keeps the Node.js process running to receive
datagram messages.</p>
<p>If binding fails, an <code>'error'</code> event is generated. In rare case (e.g.
attempting to bind with a closed socket), an <a href="#all_errors_class-error"><code>Error</code></a> may be thrown.</p>
<p>Example of a UDP server listening on port 41234:</p>
<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> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>;
<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>);
server.<span class="hljs-title function_">close</span>();
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server listening <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>);
});
server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>);
<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>);
<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</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>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>);
server.<span class="hljs-title function_">close</span>();
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server listening <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>);
});
server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>);
<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code><button class="copy-button">copy</button></pre>
<h4><code>socket.bind(options[, callback])</code><span><a class="mark" href="#all_dgram_socketbindoptions-callback" id="all_dgram_socketbindoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_bind_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</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> Required. Supports the following properties:
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></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></li>
</ul>
<p>For UDP sockets, causes the <code>dgram.Socket</code> to listen for datagram
messages on a named <code>port</code> and optional <code>address</code> that are passed as
properties of an <code>options</code> object passed as the first argument. If
<code>port</code> is not specified or is <code>0</code>, the operating system will attempt
to bind to a random port. If <code>address</code> is not specified, the operating
system will attempt to listen on all addresses. Once binding is
complete, a <code>'listening'</code> event is emitted and the optional <code>callback</code>
function is called.</p>
<p>The <code>options</code> object may contain a <code>fd</code> property. When a <code>fd</code> greater
than <code>0</code> is set, it will wrap around an existing socket with the given
file descriptor. In this case, the properties of <code>port</code> and <code>address</code>
will be ignored.</p>
<p>Specifying both a <code>'listening'</code> event listener and passing a
<code>callback</code> to the <code>socket.bind()</code> method is not harmful but not very
useful.</p>
<p>The <code>options</code> object may contain an additional <code>exclusive</code> property that is
used when using <code>dgram.Socket</code> objects with the <a href="cluster.html"><code>cluster</code></a> module. When
<code>exclusive</code> is set to <code>false</code> (the default), cluster workers will use the same
underlying socket handle allowing connection handling duties to be shared.
When <code>exclusive</code> is <code>true</code>, however, the handle is not shared and attempted
port sharing results in an error.</p>
<p>A bound datagram socket keeps the Node.js process running to receive
datagram messages.</p>
<p>If binding fails, an <code>'error'</code> event is generated. In rare case (e.g.
attempting to bind with a closed socket), an <a href="#all_errors_class-error"><code>Error</code></a> may be thrown.</p>
<p>An example socket listening on an exclusive port is shown below.</p>
<pre><code class="language-js">socket.<span class="hljs-title function_">bind</span>({
<span class="hljs-attr">address</span>: <span class="hljs-string">'localhost'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">8000</span>,
<span class="hljs-attr">exclusive</span>: <span class="hljs-literal">true</span>,
});</code> <button class="copy-button">copy</button></pre>
<h4><code>socket.close([callback])</code><span><a class="mark" href="#all_dgram_socketclosecallback" id="all_dgram_socketclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_close_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.99</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> Called when the socket has been closed.</li>
</ul>
<p>Close the underlying socket and stop listening for data on it. If a callback is
provided, it is added as a listener for the <a href="#all_dgram_event-close"><code>'close'</code></a> event.</p>
<h4><code>socket[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_dgram_socketsymbolasyncdispose" id="all_dgram_socketsymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_symbol_asyncdispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_dgram_socketclosecallback"><code>socket.close()</code></a> and returns a promise that fulfills when the
socket has closed.</p>
<h4><code>socket.connect(port[, address][, callback])</code><span><a class="mark" href="#all_dgram_socketconnectport-address-callback" id="all_dgram_socketconnectport-address-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_connect_port_address_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></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 connection is completed or on error.</li>
</ul>
<p>Associates the <code>dgram.Socket</code> to a remote address and port. Every
message sent by this handle is automatically sent to that destination. Also,
the socket will only receive messages from that remote peer.
Trying to call <code>connect()</code> on an already connected socket will result
in an <a href="#all_errors_err_socket_dgram_is_connected"><code>ERR_SOCKET_DGRAM_IS_CONNECTED</code></a> exception. If <code>address</code> is not
provided, <code>'127.0.0.1'</code> (for <code>udp4</code> sockets) or <code>'::1'</code> (for <code>udp6</code> sockets)
will be used by default. Once the connection is complete, a <code>'connect'</code> event
is emitted and the optional <code>callback</code> function is called. In case of failure,
the <code>callback</code> is called or, failing this, an <code>'error'</code> event is emitted.</p>
<h4><code>socket.disconnect()</code><span><a class="mark" href="#all_dgram_socketdisconnect" id="all_dgram_socketdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_disconnect"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>A synchronous function that disassociates a connected <code>dgram.Socket</code> from
its remote address. Trying to call <code>disconnect()</code> on an unbound or already
disconnected socket will result in an <a href="#all_errors_err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a>
exception.</p>
<h4><code>socket.dropMembership(multicastAddress[, multicastInterface])</code><span><a class="mark" href="#all_dgram_socketdropmembershipmulticastaddress-multicastinterface" id="all_dgram_socketdropmembershipmulticastaddress-multicastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_dropmembership_multicastaddress_multicastinterface"></a></h4>
<div class="api_metadata">
<span>Added in: v0.6.9</span>
</div>
<ul>
<li><code>multicastAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Instructs the kernel to leave a multicast group at <code>multicastAddress</code> using the
<code>IP_DROP_MEMBERSHIP</code> socket option. This method is automatically called by the
kernel when the socket is closed or the process terminates, so most apps will
never have reason to call this.</p>
<p>If <code>multicastInterface</code> is not specified, the operating system will attempt to
drop membership on all valid interfaces.</p>
<h4><code>socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code><span><a class="mark" href="#all_dgram_socketdropsourcespecificmembershipsourceaddress-groupaddress-multicastinterface" id="all_dgram_socketdropsourcespecificmembershipsourceaddress-groupaddress-multicastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface"></a></h4>
<div class="api_metadata">
<span>Added in: v13.1.0, v12.16.0</span>
</div>
<ul>
<li><code>sourceAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>groupAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Instructs the kernel to leave a source-specific multicast channel at the given
<code>sourceAddress</code> and <code>groupAddress</code> using the <code>IP_DROP_SOURCE_MEMBERSHIP</code>
socket option. This method is automatically called by the kernel when the
socket is closed or the process terminates, so most apps will never have
reason to call this.</p>
<p>If <code>multicastInterface</code> is not specified, the operating system will attempt to
drop membership on all valid interfaces.</p>
<h4><code>socket.getRecvBufferSize()</code><span><a class="mark" href="#all_dgram_socketgetrecvbuffersize" id="all_dgram_socketgetrecvbuffersize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_getrecvbuffersize"></a></h4>
<div class="api_metadata">
<span>Added in: v8.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the <code>SO_RCVBUF</code> socket receive buffer size in bytes.</li>
</ul>
<p>This method throws <a href="#all_errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p>
<h4><code>socket.getSendBufferSize()</code><span><a class="mark" href="#all_dgram_socketgetsendbuffersize" id="all_dgram_socketgetsendbuffersize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_getsendbuffersize"></a></h4>
<div class="api_metadata">
<span>Added in: v8.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the <code>SO_SNDBUF</code> socket send buffer size in bytes.</li>
</ul>
<p>This method throws <a href="#all_errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p>
<h4><code>socket.getSendQueueSize()</code><span><a class="mark" href="#all_dgram_socketgetsendqueuesize" id="all_dgram_socketgetsendqueuesize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_getsendqueuesize"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.19.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of bytes queued for sending.</li>
</ul>
<h4><code>socket.getSendQueueCount()</code><span><a class="mark" href="#all_dgram_socketgetsendqueuecount" id="all_dgram_socketgetsendqueuecount">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_getsendqueuecount"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.19.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of send requests currently in the queue awaiting
to be processed.</li>
</ul>
<h4><code>socket.ref()</code><span><a class="mark" href="#all_dgram_socketref" id="all_dgram_socketref">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_dgram_class-dgramsocket" class="type"><dgram.Socket></a></li>
</ul>
<p>By default, binding a socket will cause it to block the Node.js process from
exiting as long as the socket is open. The <code>socket.unref()</code> method can be used
to exclude the socket from the reference counting that keeps the Node.js
process active. The <code>socket.ref()</code> method adds the socket back to the reference
counting and restores the default behavior.</p>
<p>Calling <code>socket.ref()</code> multiples times will have no additional effect.</p>
<p>The <code>socket.ref()</code> method returns a reference to the socket so calls can be
chained.</p>
<h4><code>socket.remoteAddress()</code><span><a class="mark" href="#all_dgram_socketremoteaddress" id="all_dgram_socketremoteaddress">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_remoteaddress"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns an object containing the <code>address</code>, <code>family</code>, and <code>port</code> of the remote
endpoint. This method throws an <a href="#all_errors_err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a> exception
if the socket is not connected.</p>
<h4><code>socket.send(msg[, offset, length][, port][, address][, callback])</code><span><a class="mark" href="#all_dgram_socketsendmsg-offset-length-port-address-callback" id="all_dgram_socketsendmsg-offset-length-port-address-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_send_msg_offset_length_port_address_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>v17.0.0</td>
<td><p>The <code>address</code> parameter now only accepts a <code>string</code>, <code>null</code> or <code>undefined</code>.</p></td></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>The <code>msg</code> parameter can now be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Added support for sending data on connected sockets.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>msg</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>address</code> parameter is always optional now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>On success, <code>callback</code> will now be called with an <code>error</code> argument of <code>null</code> rather than <code>0</code>.</p></td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>msg</code> parameter can be an array now. Also, the <code>offset</code> and <code>length</code> parameters are optional now.</p></td></tr>
<tr><td>v0.1.99</td>
<td><p><span>Added in: v0.1.99</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>msg</code> <a href="#all_buffer_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/Reference/Global_Objects/Array" class="type"><Array></a> Message to be sent.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Offset in the buffer where the message starts.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes in the message.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Destination port.</li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Destination host name or IP address.</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 message has been sent.</li>
</ul>
<p>Broadcasts a datagram on the socket.
For connectionless sockets, the destination <code>port</code> and <code>address</code> must be
specified. Connected sockets, on the other hand, will use their associated
remote endpoint, so the <code>port</code> and <code>address</code> arguments must not be set.</p>
<p>The <code>msg</code> argument contains the message to be sent.
Depending on its type, different behavior can apply. If <code>msg</code> is a <code>Buffer</code>,
any <code>TypedArray</code> or a <code>DataView</code>,
the <code>offset</code> and <code>length</code> specify the offset within the <code>Buffer</code> where the
message begins and the number of bytes in the message, respectively.
If <code>msg</code> is a <code>String</code>, then it is automatically converted to a <code>Buffer</code>
with <code>'utf8'</code> encoding. With messages that
contain multi-byte characters, <code>offset</code> and <code>length</code> will be calculated with
respect to <a href="#all_buffer_static-method-bufferbytelengthstring-encoding">byte length</a> and not the character position.
If <code>msg</code> is an array, <code>offset</code> and <code>length</code> must not be specified.</p>
<p>The <code>address</code> argument is a string. If the value of <code>address</code> is a host name,
DNS will be used to resolve the address of the host. If <code>address</code> is not
provided or otherwise nullish, <code>'127.0.0.1'</code> (for <code>udp4</code> sockets) or <code>'::1'</code>
(for <code>udp6</code> sockets) will be used by default.</p>
<p>If the socket has not been previously bound with a call to <code>bind</code>, the socket
is assigned a random port number and is bound to the "all interfaces" address
(<code>'0.0.0.0'</code> for <code>udp4</code> sockets, <code>'::0'</code> for <code>udp6</code> sockets.)</p>
<p>An optional <code>callback</code> function may be specified to as a way of reporting
DNS errors or for determining when it is safe to reuse the <code>buf</code> object.
DNS lookups delay the time to send for at least one tick of the
Node.js event loop.</p>
<p>The only way to know for sure that the datagram has been sent is by using a
<code>callback</code>. If an error occurs and a <code>callback</code> is given, the error will be
passed as the first argument to the <code>callback</code>. If a <code>callback</code> is not given,
the error is emitted as an <code>'error'</code> event on the <code>socket</code> object.</p>
<p>Offset and length are optional but both <em>must</em> be set if either are used.
They are supported only when the first argument is a <code>Buffer</code>, a <code>TypedArray</code>,
or a <code>DataView</code>.</p>
<p>This method throws <a href="#all_errors_err_socket_bad_port"><code>ERR_SOCKET_BAD_PORT</code></a> if called on an unbound socket.</p>
<p>Example of sending a UDP packet to a port on <code>localhost</code>;</p>
<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> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> message = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some bytes'</span>);
<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
client.<span class="hljs-title function_">send</span>(message, <span class="hljs-number">41234</span>, <span class="hljs-string">'localhost'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
client.<span class="hljs-title function_">close</span>();
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> message = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some bytes'</span>);
<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
client.<span class="hljs-title function_">send</span>(message, <span class="hljs-number">41234</span>, <span class="hljs-string">'localhost'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
client.<span class="hljs-title function_">close</span>();
});</code><button class="copy-button">copy</button></pre>
<p>Example of sending a UDP packet composed of multiple buffers to a port on
<code>127.0.0.1</code>;</p>
<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> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some '</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'bytes'</span>);
<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
client.<span class="hljs-title function_">send</span>([buf1, buf2], <span class="hljs-number">41234</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
client.<span class="hljs-title function_">close</span>();
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some '</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'bytes'</span>);
<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
client.<span class="hljs-title function_">send</span>([buf1, buf2], <span class="hljs-number">41234</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
client.<span class="hljs-title function_">close</span>();
});</code><button class="copy-button">copy</button></pre>
<p>Sending multiple buffers might be faster or slower depending on the
application and operating system. Run benchmarks to
determine the optimal strategy on a case-by-case basis. Generally speaking,
however, sending multiple buffers is faster.</p>
<p>Example of sending a UDP packet using a socket connected to a port on
<code>localhost</code>:</p>
<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> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> message = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some bytes'</span>);
<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
client.<span class="hljs-title function_">connect</span>(<span class="hljs-number">41234</span>, <span class="hljs-string">'localhost'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
client.<span class="hljs-title function_">send</span>(message, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
client.<span class="hljs-title function_">close</span>();
});
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> message = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some bytes'</span>);
<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
client.<span class="hljs-title function_">connect</span>(<span class="hljs-number">41234</span>, <span class="hljs-string">'localhost'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
client.<span class="hljs-title function_">send</span>(message, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
client.<span class="hljs-title function_">close</span>();
});
});</code><button class="copy-button">copy</button></pre>
<h5>Note about UDP datagram size<span><a class="mark" href="#all_dgram_note-about-udp-datagram-size" id="all_dgram_note-about-udp-datagram-size">#</a></span><a aria-hidden="true" class="legacy" id="dgram_note_about_udp_datagram_size"></a></h5>
<p>The maximum size of an IPv4/v6 datagram depends on the <code>MTU</code>
(Maximum Transmission Unit) and on the <code>Payload Length</code> field size.</p>
<ul>
<li>
<p>The <code>Payload Length</code> field is 16 bits wide, which means that a normal
payload cannot exceed 64K octets including the internet header and data
(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);
this is generally true for loopback interfaces, but such long datagram
messages are impractical for most hosts and networks.</p>
</li>
<li>
<p>The <code>MTU</code> is the largest size a given link layer technology can support for
datagram messages. For any link, IPv4 mandates a minimum <code>MTU</code> of 68
octets, while the recommended <code>MTU</code> for IPv4 is 576 (typically recommended
as the <code>MTU</code> for dial-up type applications), whether they arrive whole or in
fragments.</p>
<p>For IPv6, the minimum <code>MTU</code> is 1280 octets. However, the mandatory minimum
fragment reassembly buffer size is 1500 octets. The value of 68 octets is
very small, since most current link layer technologies, like Ethernet, have a
minimum <code>MTU</code> of 1500.</p>
</li>
</ul>
<p>It is impossible to know in advance the MTU of each link through which
a packet might travel. Sending a datagram greater than the receiver <code>MTU</code> will
not work because the packet will get silently dropped without informing the
source that the data did not reach its intended recipient.</p>
<h4><code>socket.setBroadcast(flag)</code><span><a class="mark" href="#all_dgram_socketsetbroadcastflag" id="all_dgram_socketsetbroadcastflag">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setbroadcast_flag"></a></h4>
<div class="api_metadata">
<span>Added in: v0.6.9</span>
</div>
<ul>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Sets or clears the <code>SO_BROADCAST</code> socket option. When set to <code>true</code>, UDP
packets may be sent to a local interface's broadcast address.</p>
<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
<h4><code>socket.setMulticastInterface(multicastInterface)</code><span><a class="mark" href="#all_dgram_socketsetmulticastinterfacemulticastinterface" id="all_dgram_socketsetmulticastinterfacemulticastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setmulticastinterface_multicastinterface"></a></h4>
<div class="api_metadata">
<span>Added in: v8.6.0</span>
</div>
<ul>
<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p><em>All references to scope in this section are referring to
<a href="https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses">IPv6 Zone Indexes</a>, which are defined by <a href="https://tools.ietf.org/html/rfc4007">RFC 4007</a>. In string form, an IP
with a scope index is written as <code>'IP%scope'</code> where scope is an interface name
or interface number.</em></p>
<p>Sets the default outgoing multicast interface of the socket to a chosen
interface or back to system interface selection. The <code>multicastInterface</code> must
be a valid string representation of an IP from the socket's family.</p>
<p>For IPv4 sockets, this should be the IP configured for the desired physical
interface. All packets sent to multicast on the socket will be sent on the
interface determined by the most recent successful use of this call.</p>
<p>For IPv6 sockets, <code>multicastInterface</code> should include a scope to indicate the
interface as in the examples that follow. In IPv6, individual <code>send</code> calls can
also use explicit scope in addresses, so only packets sent to a multicast
address without specifying an explicit scope are affected by the most recent
successful use of this call.</p>
<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
<h5>Example: IPv6 outgoing multicast interface<span><a class="mark" href="#all_dgram_example-ipv6-outgoing-multicast-interface" id="all_dgram_example-ipv6-outgoing-multicast-interface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_example_ipv6_outgoing_multicast_interface"></a></h5>
<p>On most systems, where scope format uses the interface name:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> socket = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp6'</span>);
socket.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
socket.<span class="hljs-title function_">setMulticastInterface</span>(<span class="hljs-string">'::%eth1'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>On Windows, where scope format uses an interface number:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> socket = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp6'</span>);
socket.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
socket.<span class="hljs-title function_">setMulticastInterface</span>(<span class="hljs-string">'::%2'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h5>Example: IPv4 outgoing multicast interface<span><a class="mark" href="#all_dgram_example-ipv4-outgoing-multicast-interface" id="all_dgram_example-ipv4-outgoing-multicast-interface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_example_ipv4_outgoing_multicast_interface"></a></h5>
<p>All systems use an IP of the host on the desired physical interface:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> socket = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
socket.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
socket.<span class="hljs-title function_">setMulticastInterface</span>(<span class="hljs-string">'10.0.0.2'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h5>Call results<span><a class="mark" href="#all_dgram_call-results" id="all_dgram_call-results">#</a></span><a aria-hidden="true" class="legacy" id="dgram_call_results"></a></h5>
<p>A call on a socket that is not ready to send or no longer open may throw a <em>Not
running</em> <a href="#all_errors_class-error"><code>Error</code></a>.</p>
<p>If <code>multicastInterface</code> can not be parsed into an IP then an <em>EINVAL</em>
<a href="#all_errors_class-systemerror"><code>System Error</code></a> is thrown.</p>
<p>On IPv4, if <code>multicastInterface</code> is a valid address but does not match any
interface, or if the address does not match the family then
a <a href="#all_errors_class-systemerror"><code>System Error</code></a> such as <code>EADDRNOTAVAIL</code> or <code>EPROTONOSUP</code> is thrown.</p>
<p>On IPv6, most errors with specifying or omitting scope will result in the socket
continuing to use (or returning to) the system's default interface selection.</p>
<p>A socket's address family's ANY address (IPv4 <code>'0.0.0.0'</code> or IPv6 <code>'::'</code>) can be
used to return control of the sockets default outgoing interface to the system
for future multicast packets.</p>
<h4><code>socket.setMulticastLoopback(flag)</code><span><a class="mark" href="#all_dgram_socketsetmulticastloopbackflag" id="all_dgram_socketsetmulticastloopbackflag">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setmulticastloopback_flag"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.8</span>
</div>
<ul>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Sets or clears the <code>IP_MULTICAST_LOOP</code> socket option. When set to <code>true</code>,
multicast packets will also be received on the local interface.</p>
<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
<h4><code>socket.setMulticastTTL(ttl)</code><span><a class="mark" href="#all_dgram_socketsetmulticastttlttl" id="all_dgram_socketsetmulticastttlttl">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setmulticastttl_ttl"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.8</span>
</div>
<ul>
<li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Sets the <code>IP_MULTICAST_TTL</code> socket option. While TTL generally stands for
"Time to Live", in this context it specifies the number of IP hops that a
packet is allowed to travel through, specifically for multicast traffic. Each
router or gateway that forwards a packet decrements the TTL. If the TTL is
decremented to 0 by a router, it will not be forwarded.</p>
<p>The <code>ttl</code> argument may be between 0 and 255. The default on most systems is <code>1</code>.</p>
<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
<h4><code>socket.setRecvBufferSize(size)</code><span><a class="mark" href="#all_dgram_socketsetrecvbuffersizesize" id="all_dgram_socketsetrecvbuffersizesize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setrecvbuffersize_size"></a></h4>
<div class="api_metadata">
<span>Added in: v8.7.0</span>
</div>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Sets the <code>SO_RCVBUF</code> socket option. Sets the maximum socket receive buffer
in bytes.</p>
<p>This method throws <a href="#all_errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p>
<h4><code>socket.setSendBufferSize(size)</code><span><a class="mark" href="#all_dgram_socketsetsendbuffersizesize" id="all_dgram_socketsetsendbuffersizesize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setsendbuffersize_size"></a></h4>
<div class="api_metadata">
<span>Added in: v8.7.0</span>
</div>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Sets the <code>SO_SNDBUF</code> socket option. Sets the maximum socket send buffer
in bytes.</p>
<p>This method throws <a href="#all_errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p>
<h4><code>socket.setTTL(ttl)</code><span><a class="mark" href="#all_dgram_socketsetttlttl" id="all_dgram_socketsetttlttl">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setttl_ttl"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.101</span>
</div>
<ul>
<li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Sets the <code>IP_TTL</code> socket option. While TTL generally stands for "Time to Live",
in this context it specifies the number of IP hops that a packet is allowed to
travel through. Each router or gateway that forwards a packet decrements the
TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
Changing TTL values is typically done for network probes or when multicasting.</p>
<p>The <code>ttl</code> argument may be between 1 and 255. The default on most systems
is 64.</p>
<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
<h4><code>socket.unref()</code><span><a class="mark" href="#all_dgram_socketunref" id="all_dgram_socketunref">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_dgram_class-dgramsocket" class="type"><dgram.Socket></a></li>
</ul>
<p>By default, binding a socket will cause it to block the Node.js process from
exiting as long as the socket is open. The <code>socket.unref()</code> method can be used
to exclude the socket from the reference counting that keeps the Node.js
process active, allowing the process to exit even if the socket is still
listening.</p>
<p>Calling <code>socket.unref()</code> multiple times will have no additional effect.</p>
<p>The <code>socket.unref()</code> method returns a reference to the socket so calls can be
chained.</p>
</section><section><h3><code>node:dgram</code> module functions<span><a class="mark" href="#all_dgram_nodedgram-module-functions" id="all_dgram_nodedgram-module-functions">#</a></span><a aria-hidden="true" class="legacy" id="dgram_node_dgram_module_functions"></a></h3>
<h4><code>dgram.createSocket(options[, callback])</code><span><a class="mark" href="#all_dgram_dgramcreatesocketoptions-callback" id="all_dgram_dgramcreatesocketoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_dgram_createsocket_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>v15.8.0</td>
<td><p>AbortSignal support was added.</p></td></tr>
<tr><td>v11.4.0</td>
<td><p>The <code>ipv6Only</code> option is supported.</p></td></tr>
<tr><td>v8.7.0</td>
<td><p>The <code>recvBufferSize</code> and <code>sendBufferSize</code> options are supported now.</p></td></tr>
<tr><td>v8.6.0</td>
<td><p>The <code>lookup</code> option is supported.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></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> Available options are:
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The family of socket. Must be either <code>'udp4'</code> or <code>'udp6'</code>.
Required.</li>
<li><code>reuseAddr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> <a href="#all_dgram_socketbindport-address-callback"><code>socket.bind()</code></a> will reuse the
address, even if another process has already bound a socket on it.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>ipv6Only</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Setting <code>ipv6Only</code> to <code>true</code> will
disable dual-stack support, i.e., binding to address <code>::</code> won't make
<code>0.0.0.0</code> be bound. <strong>Default:</strong> <code>false</code>.</li>
<li><code>recvBufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the <code>SO_RCVBUF</code> socket value.</li>
<li><code>sendBufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the <code>SO_SNDBUF</code> socket value.</li>
<li><code>lookup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Custom lookup function. <strong>Default:</strong> <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> An AbortSignal that may be used to close a socket.</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> Attached as a listener for <code>'message'</code> events. Optional.</li>
<li>Returns: <a href="#all_dgram_class-dgramsocket" class="type"><dgram.Socket></a></li>
</ul>
<p>Creates a <code>dgram.Socket</code> object. Once the socket is created, calling
<a href="#all_dgram_socketbindport-address-callback"><code>socket.bind()</code></a> will instruct the socket to begin listening for datagram
messages. When <code>address</code> and <code>port</code> are not passed to <a href="#all_dgram_socketbindport-address-callback"><code>socket.bind()</code></a> the
method will bind the socket to the "all interfaces" address on a random port
(it does the right thing for both <code>udp4</code> and <code>udp6</code> sockets). The bound address
and port can be retrieved using <a href="#all_dgram_socketaddress"><code>socket.address().address</code></a> and
<a href="#all_dgram_socketaddress"><code>socket.address().port</code></a>.</p>
<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
<code>AbortController</code> is similar to calling <code>.close()</code> on the socket:</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> { signal } = controller;
<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>({ <span class="hljs-attr">type</span>: <span class="hljs-string">'udp4'</span>, signal });
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
});
<span class="hljs-comment">// Later, when you want to close the server.</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<h4><code>dgram.createSocket(type[, callback])</code><span><a class="mark" href="#all_dgram_dgramcreatesockettype-callback" id="all_dgram_dgramcreatesockettype-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_dgram_createsocket_type_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>'udp4'</code> or <code>'udp6'</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> Attached as a listener to <code>'message'</code> events.</li>
<li>Returns: <a href="#all_dgram_class-dgramsocket" class="type"><dgram.Socket></a></li>
</ul>
<p>Creates a <code>dgram.Socket</code> object of the specified <code>type</code>.</p>
<p>Once the socket is created, calling <a href="#all_dgram_socketbindport-address-callback"><code>socket.bind()</code></a> will instruct the
socket to begin listening for datagram messages. When <code>address</code> and <code>port</code> are
not passed to <a href="#all_dgram_socketbindport-address-callback"><code>socket.bind()</code></a> the method will bind the socket to the "all
interfaces" address on a random port (it does the right thing for both <code>udp4</code>
and <code>udp6</code> sockets). The bound address and port can be retrieved using
<a href="#all_dgram_socketaddress"><code>socket.address().address</code></a> and <a href="#all_dgram_socketaddress"><code>socket.address().port</code></a>.</p></section>
</section>
<section><h2>URL<span><a class="mark" href="#all_url_url" id="all_url_url">#</a></span><a aria-hidden="true" class="legacy" id="url_url"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/url.js">lib/url.js</a></p>
<p>The <code>node:url</code> module provides utilities for URL resolution and parsing. It can
be accessed using:</p>
<pre class="with-32-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> url <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>URL strings and URL objects<span><a class="mark" href="#all_url_url-strings-and-url-objects" id="all_url_url-strings-and-url-objects">#</a></span><a aria-hidden="true" class="legacy" id="url_url_strings_and_url_objects"></a></h3>
<p>A URL string is a structured string containing multiple meaningful components.
When parsed, a URL object is returned containing properties for each of these
components.</p>
<p>The <code>node:url</code> module provides two APIs for working with URLs: a legacy API that
is Node.js specific, and a newer API that implements the same
<a href="https://url.spec.whatwg.org/">WHATWG URL Standard</a> used by web browsers.</p>
<p>A comparison between the WHATWG and legacy APIs is provided below. Above the URL
<code>'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'</code>, properties
of an object returned by the legacy <code>url.parse()</code> are shown. Below it are
properties of a WHATWG <code>URL</code> object.</p>
<p>WHATWG URL's <code>origin</code> property includes <code>protocol</code> and <code>host</code>, but not
<code>username</code> or <code>password</code>.</p>
<pre><code class="language-text">┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│ href │
├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
│ protocol │ │ auth │ host │ path │ hash │
│ │ │ ├─────────────────┬──────┼──────────┬────────────────┤ │
│ │ │ │ hostname │ port │ pathname │ search │ │
│ │ │ │ │ │ ├─┬──────────────┤ │
│ │ │ │ │ │ │ │ query │ │
" https: // user : pass @ sub.example.com : 8080 /p/a/t/h ? query=string #hash "
│ │ │ │ │ hostname │ port │ │ │ │
│ │ │ │ ├─────────────────┴──────┤ │ │ │
│ protocol │ │ username │ password │ host │ │ │ │
├──────────┴──┼──────────┴──────────┼────────────────────────┤ │ │ │
│ origin │ │ origin │ pathname │ search │ hash │
├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
│ href │
└────────────────────────────────────────────────────────────────────────────────────────────────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)</code> <button class="copy-button">copy</button></pre>
<p>Parsing the URL string using the WHATWG API:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL =
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'</span>);</code> <button class="copy-button">copy</button></pre>
<p>Parsing the URL string using the legacy API:</p>
<pre class="with-32-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> url <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">const</span> myURL =
url.<span class="hljs-title function_">parse</span>(<span class="hljs-string">'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> myURL =
url.<span class="hljs-title function_">parse</span>(<span class="hljs-string">'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'</span>);</code><button class="copy-button">copy</button></pre>
<h4>Constructing a URL from component parts and getting the constructed string<span><a class="mark" href="#all_url_constructing-a-url-from-component-parts-and-getting-the-constructed-string" id="all_url_constructing-a-url-from-component-parts-and-getting-the-constructed-string">#</a></span><a aria-hidden="true" class="legacy" id="url_constructing_a_url_from_component_parts_and_getting_the_constructed_string"></a></h4>
<p>It is possible to construct a WHATWG URL from component parts using either the
property setters or a template literal string:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org'</span>);
myURL.<span class="hljs-property">pathname</span> = <span class="hljs-string">'/a/b/c'</span>;
myURL.<span class="hljs-property">search</span> = <span class="hljs-string">'?d=e'</span>;
myURL.<span class="hljs-property">hash</span> = <span class="hljs-string">'#fgh'</span>;</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">const</span> pathname = <span class="hljs-string">'/a/b/c'</span>;
<span class="hljs-keyword">const</span> search = <span class="hljs-string">'?d=e'</span>;
<span class="hljs-keyword">const</span> hash = <span class="hljs-string">'#fgh'</span>;
<span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`https://example.org<span class="hljs-subst">${pathname}</span><span class="hljs-subst">${search}</span><span class="hljs-subst">${hash}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<p>To get the constructed URL string, use the <code>href</code> property accessor:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3>The WHATWG URL API<span><a class="mark" href="#all_url_the-whatwg-url-api" id="all_url_the-whatwg-url-api">#</a></span><a aria-hidden="true" class="legacy" id="url_the_whatwg_url_api"></a></h3>
<h4>Class: <code>URL</code><span><a class="mark" href="#all_url_class-url" id="all_url_class-url">#</a></span><a aria-hidden="true" class="legacy" id="url_class_url"></a></h4>
<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 class is now available on the global object.</p></td></tr>
<tr><td>v7.0.0, v6.13.0</td>
<td><p><span>Added in: v7.0.0, v6.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Browser-compatible <code>URL</code> class, implemented by following the WHATWG URL
Standard. <a href="https://url.spec.whatwg.org/#example-url-parsing">Examples of parsed URLs</a> may be found in the Standard itself.
The <code>URL</code> class is also available on the global object.</p>
<p>In accordance with browser conventions, all properties of <code>URL</code> objects
are implemented as getters and setters on the class prototype, rather than as
data properties on the object itself. Thus, unlike <a href="#all_url_legacy-urlobject">legacy <code>urlObject</code></a>s,
using the <code>delete</code> keyword on any properties of <code>URL</code> objects (e.g. <code>delete myURL.protocol</code>, <code>delete myURL.pathname</code>, etc) has no effect but will still
return <code>true</code>.</p>
<h5><code>new URL(input[, base])</code><span><a class="mark" href="#all_url_new-urlinput-base" id="all_url_new-urlinput-base">#</a></span><a aria-hidden="true" class="legacy" id="url_new_url_input_base"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>ICU requirement is removed.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The absolute or relative input URL to parse. If <code>input</code>
is relative, then <code>base</code> is required. If <code>input</code> is absolute, the <code>base</code>
is ignored. If <code>input</code> is not a string, it is <a href="https://tc39.es/ecma262/#sec-tostring">converted to a string</a> first.</li>
<li><code>base</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The base URL to resolve against if the <code>input</code> is not
absolute. If <code>base</code> is not a string, it is <a href="https://tc39.es/ecma262/#sec-tostring">converted to a string</a> first.</li>
</ul>
<p>Creates a new <code>URL</code> object by parsing the <code>input</code> relative to the <code>base</code>. If
<code>base</code> is passed as a string, it will be parsed equivalent to <code>new URL(base)</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'/foo'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// https://example.org/foo</span></code> <button class="copy-button">copy</button></pre>
<p>The URL constructor is accessible as a property on the global object.
It can also be imported from the built-in url module:</p>
<pre class="with-63-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-variable constant_">URL</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable constant_">URL</span> === globalThis.<span class="hljs-property">URL</span>); <span class="hljs-comment">// Prints 'true'.</span></code><code class="language-js cjs"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable constant_">URL</span> === <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>).<span class="hljs-property">URL</span>); <span class="hljs-comment">// Prints 'true'.</span></code><button class="copy-button">copy</button></pre>
<p>A <code>TypeError</code> will be thrown if the <code>input</code> or <code>base</code> are not valid URLs. Note
that an effort will be made to coerce the given values into strings. For
instance:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>({ <span class="hljs-attr">toString</span>: <span class="hljs-function">() =></span> <span class="hljs-string">'https://example.org/'</span> });
<span class="hljs-comment">// https://example.org/</span></code> <button class="copy-button">copy</button></pre>
<p>Unicode characters appearing within the host name of <code>input</code> will be
automatically converted to ASCII using the <a href="https://tools.ietf.org/html/rfc5891#section-4.4">Punycode</a> algorithm.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://測試'</span>);
<span class="hljs-comment">// https://xn--g6w251d/</span></code> <button class="copy-button">copy</button></pre>
<p>In cases where it is not known in advance if <code>input</code> is an absolute URL
and a <code>base</code> is provided, it is advised to validate that the <code>origin</code> of
the <code>URL</code> object is what is expected.</p>
<pre><code class="language-js"><span class="hljs-keyword">let</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'http://Example.com/'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// http://example.com/</span>
myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://Example.com/'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// https://example.com/</span>
myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'foo://Example.com/'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// foo://Example.com/</span>
myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'http:Example.com/'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// http://example.com/</span>
myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https:Example.com/'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// https://example.org/Example.com/</span>
myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'foo:Example.com/'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// foo:Example.com/</span></code> <button class="copy-button">copy</button></pre>
<h5><code>url.hash</code><span><a class="mark" href="#all_url_urlhash" id="all_url_urlhash">#</a></span><a aria-hidden="true" class="legacy" id="url_url_hash"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets and sets the fragment portion of the URL.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/foo#bar'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">hash</span>);
<span class="hljs-comment">// Prints #bar</span>
myURL.<span class="hljs-property">hash</span> = <span class="hljs-string">'baz'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/foo#baz</span></code> <button class="copy-button">copy</button></pre>
<p>Invalid URL characters included in the value assigned to the <code>hash</code> property
are <a href="#all_url_percent-encoding-in-urls">percent-encoded</a>. The selection of which characters to
percent-encode may vary somewhat from what the <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a> and
<a href="#all_url_urlformaturlobject"><code>url.format()</code></a> methods would produce.</p>
<h5><code>url.host</code><span><a class="mark" href="#all_url_urlhost" id="all_url_urlhost">#</a></span><a aria-hidden="true" class="legacy" id="url_url_host"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets and sets the host portion of the URL.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org:81/foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">host</span>);
<span class="hljs-comment">// Prints example.org:81</span>
myURL.<span class="hljs-property">host</span> = <span class="hljs-string">'example.com:82'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.com:82/foo</span></code> <button class="copy-button">copy</button></pre>
<p>Invalid host values assigned to the <code>host</code> property are ignored.</p>
<h5><code>url.hostname</code><span><a class="mark" href="#all_url_urlhostname" id="all_url_urlhostname">#</a></span><a aria-hidden="true" class="legacy" id="url_url_hostname"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets and sets the host name portion of the URL. The key difference between
<code>url.host</code> and <code>url.hostname</code> is that <code>url.hostname</code> does <em>not</em> include the
port.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org:81/foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">hostname</span>);
<span class="hljs-comment">// Prints example.org</span>
<span class="hljs-comment">// Setting the hostname does not change the port</span>
myURL.<span class="hljs-property">hostname</span> = <span class="hljs-string">'example.com'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.com:81/foo</span>
<span class="hljs-comment">// Use myURL.host to change the hostname and port</span>
myURL.<span class="hljs-property">host</span> = <span class="hljs-string">'example.org:82'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org:82/foo</span></code> <button class="copy-button">copy</button></pre>
<p>Invalid host name values assigned to the <code>hostname</code> property are ignored.</p>
<h5><code>url.href</code><span><a class="mark" href="#all_url_urlhref" id="all_url_urlhref">#</a></span><a aria-hidden="true" class="legacy" id="url_url_href"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets and sets the serialized URL.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/foo</span>
myURL.<span class="hljs-property">href</span> = <span class="hljs-string">'https://example.com/bar'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.com/bar</span></code> <button class="copy-button">copy</button></pre>
<p>Getting the value of the <code>href</code> property is equivalent to calling
<a href="#all_url_urltostring"><code>url.toString()</code></a>.</p>
<p>Setting the value of this property to a new value is equivalent to creating a
new <code>URL</code> object using <a href="#all_url_new-urlinput-base"><code>new URL(value)</code></a>. Each of the <code>URL</code>
object's properties will be modified.</p>
<p>If the value assigned to the <code>href</code> property is not a valid URL, a <code>TypeError</code>
will be thrown.</p>
<h5><code>url.origin</code><span><a class="mark" href="#all_url_urlorigin" id="all_url_urlorigin">#</a></span><a aria-hidden="true" class="legacy" id="url_url_origin"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The scheme "gopher" is no longer special and <code>url.origin</code> now returns <code>'null'</code> for it.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets the read-only serialization of the URL's origin.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/foo/bar?baz'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">origin</span>);
<span class="hljs-comment">// Prints https://example.org</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">const</span> idnURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://測試'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(idnURL.<span class="hljs-property">origin</span>);
<span class="hljs-comment">// Prints https://xn--g6w251d</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(idnURL.<span class="hljs-property">hostname</span>);
<span class="hljs-comment">// Prints xn--g6w251d</span></code> <button class="copy-button">copy</button></pre>
<h5><code>url.password</code><span><a class="mark" href="#all_url_urlpassword" id="all_url_urlpassword">#</a></span><a aria-hidden="true" class="legacy" id="url_url_password"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets and sets the password portion of the URL.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://abc:xyz@example.com'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">password</span>);
<span class="hljs-comment">// Prints xyz</span>
myURL.<span class="hljs-property">password</span> = <span class="hljs-string">'123'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://abc:123@example.com/</span></code> <button class="copy-button">copy</button></pre>
<p>Invalid URL characters included in the value assigned to the <code>password</code> property
are <a href="#all_url_percent-encoding-in-urls">percent-encoded</a>. The selection of which characters to
percent-encode may vary somewhat from what the <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a> and
<a href="#all_url_urlformaturlobject"><code>url.format()</code></a> methods would produce.</p>
<h5><code>url.pathname</code><span><a class="mark" href="#all_url_urlpathname" id="all_url_urlpathname">#</a></span><a aria-hidden="true" class="legacy" id="url_url_pathname"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets and sets the path portion of the URL.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/abc/xyz?123'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">pathname</span>);
<span class="hljs-comment">// Prints /abc/xyz</span>
myURL.<span class="hljs-property">pathname</span> = <span class="hljs-string">'/abcdef'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/abcdef?123</span></code> <button class="copy-button">copy</button></pre>
<p>Invalid URL characters included in the value assigned to the <code>pathname</code>
property are <a href="#all_url_percent-encoding-in-urls">percent-encoded</a>. The selection of which characters
to percent-encode may vary somewhat from what the <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a> and
<a href="#all_url_urlformaturlobject"><code>url.format()</code></a> methods would produce.</p>
<h5><code>url.port</code><span><a class="mark" href="#all_url_urlport" id="all_url_urlport">#</a></span><a aria-hidden="true" class="legacy" id="url_url_port"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The scheme "gopher" is no longer special.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets and sets the port portion of the URL.</p>
<p>The port value may be a number or a string containing a number in the range
<code>0</code> to <code>65535</code> (inclusive). Setting the value to the default port of the
<code>URL</code> objects given <code>protocol</code> will result in the <code>port</code> value becoming
the empty string (<code>''</code>).</p>
<p>The port value can be an empty string in which case the port depends on
the protocol/scheme:</p>
<table><thead><tr><th>protocol</th><th>port</th></tr></thead><tbody><tr><td>"ftp"</td><td>21</td></tr><tr><td>"file"</td><td></td></tr><tr><td>"http"</td><td>80</td></tr><tr><td>"https"</td><td>443</td></tr><tr><td>"ws"</td><td>80</td></tr><tr><td>"wss"</td><td>443</td></tr></tbody></table>
<p>Upon assigning a value to the port, the value will first be converted to a
string using <code>.toString()</code>.</p>
<p>If that string is invalid but it begins with a number, the leading number is
assigned to <code>port</code>.
If the number lies outside the range denoted above, it is ignored.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org:8888'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 8888</span>
<span class="hljs-comment">// Default ports are automatically transformed to the empty string</span>
<span class="hljs-comment">// (HTTPS protocol's default port is 443)</span>
myURL.<span class="hljs-property">port</span> = <span class="hljs-string">'443'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints the empty string</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/</span>
myURL.<span class="hljs-property">port</span> = <span class="hljs-number">1234</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 1234</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org:1234/</span>
<span class="hljs-comment">// Completely invalid port strings are ignored</span>
myURL.<span class="hljs-property">port</span> = <span class="hljs-string">'abcd'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 1234</span>
<span class="hljs-comment">// Leading numbers are treated as a port number</span>
myURL.<span class="hljs-property">port</span> = <span class="hljs-string">'5678abcd'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 5678</span>
<span class="hljs-comment">// Non-integers are truncated</span>
myURL.<span class="hljs-property">port</span> = <span class="hljs-number">1234.5678</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 1234</span>
<span class="hljs-comment">// Out-of-range numbers which are not represented in scientific notation</span>
<span class="hljs-comment">// will be ignored.</span>
myURL.<span class="hljs-property">port</span> = <span class="hljs-number">1e10</span>; <span class="hljs-comment">// 10000000000, will be range-checked as described below</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 1234</span></code> <button class="copy-button">copy</button></pre>
<p>Numbers which contain a decimal point,
such as floating-point numbers or numbers in scientific notation,
are not an exception to this rule.
Leading numbers up to the decimal point will be set as the URL's port,
assuming they are valid:</p>
<pre><code class="language-js">myURL.<span class="hljs-property">port</span> = <span class="hljs-number">4.567e21</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 4 (because it is the leading number in the string '4.567e21')</span></code> <button class="copy-button">copy</button></pre>
<h5><code>url.protocol</code><span><a class="mark" href="#all_url_urlprotocol" id="all_url_urlprotocol">#</a></span><a aria-hidden="true" class="legacy" id="url_url_protocol"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets and sets the protocol portion of the URL.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">protocol</span>);
<span class="hljs-comment">// Prints https:</span>
myURL.<span class="hljs-property">protocol</span> = <span class="hljs-string">'ftp'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints ftp://example.org/</span></code> <button class="copy-button">copy</button></pre>
<p>Invalid URL protocol values assigned to the <code>protocol</code> property are ignored.</p>
<h6>Special schemes<span><a class="mark" href="#all_url_special-schemes" id="all_url_special-schemes">#</a></span><a aria-hidden="true" class="legacy" id="url_special_schemes"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The scheme "gopher" is no longer special.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The <a href="https://url.spec.whatwg.org/">WHATWG URL Standard</a> considers a handful of URL protocol schemes to be
<em>special</em> in terms of how they are parsed and serialized. When a URL is
parsed using one of these special protocols, the <code>url.protocol</code> property
may be changed to another special protocol but cannot be changed to a
non-special protocol, and vice versa.</p>
<p>For instance, changing from <code>http</code> to <code>https</code> works:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> u = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'http://example.org'</span>);
u.<span class="hljs-property">protocol</span> = <span class="hljs-string">'https'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u.<span class="hljs-property">href</span>);
<span class="hljs-comment">// https://example.org/</span></code> <button class="copy-button">copy</button></pre>
<p>However, changing from <code>http</code> to a hypothetical <code>fish</code> protocol does not
because the new protocol is not special.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> u = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'http://example.org'</span>);
u.<span class="hljs-property">protocol</span> = <span class="hljs-string">'fish'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u.<span class="hljs-property">href</span>);
<span class="hljs-comment">// http://example.org/</span></code> <button class="copy-button">copy</button></pre>
<p>Likewise, changing from a non-special protocol to a special protocol is also
not permitted:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> u = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'fish://example.org'</span>);
u.<span class="hljs-property">protocol</span> = <span class="hljs-string">'http'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u.<span class="hljs-property">href</span>);
<span class="hljs-comment">// fish://example.org</span></code> <button class="copy-button">copy</button></pre>
<p>According to the WHATWG URL Standard, special protocol schemes are <code>ftp</code>,
<code>file</code>, <code>http</code>, <code>https</code>, <code>ws</code>, and <code>wss</code>.</p>
<h5><code>url.search</code><span><a class="mark" href="#all_url_urlsearch" id="all_url_urlsearch">#</a></span><a aria-hidden="true" class="legacy" id="url_url_search"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets and sets the serialized query portion of the URL.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/abc?123'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">search</span>);
<span class="hljs-comment">// Prints ?123</span>
myURL.<span class="hljs-property">search</span> = <span class="hljs-string">'abc=xyz'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/abc?abc=xyz</span></code> <button class="copy-button">copy</button></pre>
<p>Any invalid URL characters appearing in the value assigned the <code>search</code>
property will be <a href="#all_url_percent-encoding-in-urls">percent-encoded</a>. The selection of which
characters to percent-encode may vary somewhat from what the <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a>
and <a href="#all_url_urlformaturlobject"><code>url.format()</code></a> methods would produce.</p>
<h5><code>url.searchParams</code><span><a class="mark" href="#all_url_urlsearchparams" id="all_url_urlsearchparams">#</a></span><a aria-hidden="true" class="legacy" id="url_url_searchparams"></a></h5>
<ul>
<li><a href="#all_url_class-urlsearchparams" class="type"><URLSearchParams></a></li>
</ul>
<p>Gets the <a href="#all_url_class-urlsearchparams"><code>URLSearchParams</code></a> object representing the query parameters of the
URL. This property is read-only but the <code>URLSearchParams</code> object it provides
can be used to mutate the URL instance; to replace the entirety of query
parameters of the URL, use the <a href="#all_url_urlsearch"><code>url.search</code></a> setter. See
<a href="#all_url_class-urlsearchparams"><code>URLSearchParams</code></a> documentation for details.</p>
<p>Use care when using <code>.searchParams</code> to modify the <code>URL</code> because,
per the WHATWG specification, the <code>URLSearchParams</code> object uses
different rules to determine which characters to percent-encode. For
instance, the <code>URL</code> object will not percent encode the ASCII tilde (<code>~</code>)
character, while <code>URLSearchParams</code> will always encode it:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/abc?foo=~bar'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">search</span>); <span class="hljs-comment">// prints ?foo=~bar</span>
<span class="hljs-comment">// Modify the URL via searchParams...</span>
myURL.<span class="hljs-property">searchParams</span>.<span class="hljs-title function_">sort</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">search</span>); <span class="hljs-comment">// prints ?foo=%7Ebar</span></code> <button class="copy-button">copy</button></pre>
<h5><code>url.username</code><span><a class="mark" href="#all_url_urlusername" id="all_url_urlusername">#</a></span><a aria-hidden="true" class="legacy" id="url_url_username"></a></h5>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets and sets the username portion of the URL.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://abc:xyz@example.com'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">username</span>);
<span class="hljs-comment">// Prints abc</span>
myURL.<span class="hljs-property">username</span> = <span class="hljs-string">'123'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://123:xyz@example.com/</span></code> <button class="copy-button">copy</button></pre>
<p>Any invalid URL characters appearing in the value assigned the <code>username</code>
property will be <a href="#all_url_percent-encoding-in-urls">percent-encoded</a>. The selection of which
characters to percent-encode may vary somewhat from what the <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a>
and <a href="#all_url_urlformaturlobject"><code>url.format()</code></a> methods would produce.</p>
<h5><code>url.toString()</code><span><a class="mark" href="#all_url_urltostring" id="all_url_urltostring">#</a></span><a aria-hidden="true" class="legacy" id="url_url_tostring"></a></h5>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>toString()</code> method on the <code>URL</code> object returns the serialized URL. The
value returned is equivalent to that of <a href="#all_url_urlhref"><code>url.href</code></a> and <a href="#all_url_urltojson"><code>url.toJSON()</code></a>.</p>
<h5><code>url.toJSON()</code><span><a class="mark" href="#all_url_urltojson" id="all_url_urltojson">#</a></span><a aria-hidden="true" class="legacy" id="url_url_tojson"></a></h5>
<div class="api_metadata">
<span>Added in: v7.7.0, v6.13.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>toJSON()</code> method on the <code>URL</code> object returns the serialized URL. The
value returned is equivalent to that of <a href="#all_url_urlhref"><code>url.href</code></a> and
<a href="#all_url_urltostring"><code>url.toString()</code></a>.</p>
<p>This method is automatically called when an <code>URL</code> object is serialized
with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify"><code>JSON.stringify()</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURLs = [
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://www.example.com'</span>),
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://test.example.org'</span>),
];
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(myURLs));
<span class="hljs-comment">// Prints ["https://www.example.com/","https://test.example.org/"]</span></code> <button class="copy-button">copy</button></pre>
<h5><code>URL.createObjectURL(blob)</code><span><a class="mark" href="#all_url_urlcreateobjecturlblob" id="all_url_urlcreateobjecturlblob">#</a></span><a aria-hidden="true" class="legacy" id="url_url_createobjecturl_blob"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>blob</code> <a href="#all_buffer_class-blob" class="type"><Blob></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Creates a <code>'blob:nodedata:...'</code> URL string that represents the given <a href="#all_buffer_class-blob" class="type"><Blob></a>
object and can be used to retrieve the <code>Blob</code> later.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
<span class="hljs-title class_">Blob</span>,
resolveObjectURL,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Blob</span>([<span class="hljs-string">'hello'</span>]);
<span class="hljs-keyword">const</span> id = <span class="hljs-variable constant_">URL</span>.<span class="hljs-title function_">createObjectURL</span>(blob);
<span class="hljs-comment">// later...</span>
<span class="hljs-keyword">const</span> otherBlob = <span class="hljs-title function_">resolveObjectURL</span>(id);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(otherBlob.<span class="hljs-property">size</span>);</code> <button class="copy-button">copy</button></pre>
<p>The data stored by the registered <a href="#all_buffer_class-blob" class="type"><Blob></a> will be retained in memory until
<code>URL.revokeObjectURL()</code> is called to remove it.</p>
<p><code>Blob</code> objects are registered within the current thread. If using Worker
Threads, <code>Blob</code> objects registered within one Worker will not be available
to other workers or the main thread.</p>
<h5><code>URL.revokeObjectURL(id)</code><span><a class="mark" href="#all_url_urlrevokeobjecturlid" id="all_url_urlrevokeobjecturlid">#</a></span><a aria-hidden="true" class="legacy" id="url_url_revokeobjecturl_id"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A <code>'blob:nodedata:...</code> URL string returned by a prior call to
<code>URL.createObjectURL()</code>.</li>
</ul>
<p>Removes the stored <a href="#all_buffer_class-blob" class="type"><Blob></a> identified by the given ID. Attempting to revoke a
ID that isn't registered will silently fail.</p>
<h5><code>URL.canParse(input[, base])</code><span><a class="mark" href="#all_url_urlcanparseinput-base" id="all_url_urlcanparseinput-base">#</a></span><a aria-hidden="true" class="legacy" id="url_url_canparse_input_base"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The absolute or relative input URL to parse. If <code>input</code>
is relative, then <code>base</code> is required. If <code>input</code> is absolute, the <code>base</code>
is ignored. If <code>input</code> is not a string, it is <a href="https://tc39.es/ecma262/#sec-tostring">converted to a string</a> first.</li>
<li><code>base</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The base URL to resolve against if the <code>input</code> is not
absolute. If <code>base</code> is not a string, it is <a href="https://tc39.es/ecma262/#sec-tostring">converted to a string</a> first.</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>Checks if an <code>input</code> relative to the <code>base</code> can be parsed to a <code>URL</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> isValid = <span class="hljs-variable constant_">URL</span>.<span class="hljs-title function_">canParse</span>(<span class="hljs-string">'/foo'</span>, <span class="hljs-string">'https://example.org/'</span>); <span class="hljs-comment">// true</span>
<span class="hljs-keyword">const</span> isNotValid = <span class="hljs-variable constant_">URL</span>.<span class="hljs-title function_">canParse</span>(<span class="hljs-string">'/foo'</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<h5><code>URL.parse(input[, base])</code><span><a class="mark" href="#all_url_urlparseinput-base" id="all_url_urlparseinput-base">#</a></span><a aria-hidden="true" class="legacy" id="url_url_parse_input_base"></a></h5>
<div class="api_metadata">
<span>Added in: v22.1.0</span>
</div>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The absolute or relative input URL to parse. If <code>input</code>
is relative, then <code>base</code> is required. If <code>input</code> is absolute, the <code>base</code>
is ignored. If <code>input</code> is not a string, it is <a href="https://tc39.es/ecma262/#sec-tostring">converted to a string</a> first.</li>
<li><code>base</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The base URL to resolve against if the <code>input</code> is not
absolute. If <code>base</code> is not a string, it is <a href="https://tc39.es/ecma262/#sec-tostring">converted to a string</a> first.</li>
<li>Returns: <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a></li>
</ul>
<p>Parses a string as a URL. If <code>base</code> is provided, it will be used as the base
URL for the purpose of resolving non-absolute <code>input</code> URLs. Returns <code>null</code>
if <code>input</code> is not a valid.</p>
<h4>Class: <code>URLSearchParams</code><span><a class="mark" href="#all_url_class-urlsearchparams" id="all_url_class-urlsearchparams">#</a></span><a aria-hidden="true" class="legacy" id="url_class_urlsearchparams"></a></h4>
<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 class is now available on the global object.</p></td></tr>
<tr><td>v7.5.0, v6.13.0</td>
<td><p><span>Added in: v7.5.0, v6.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>URLSearchParams</code> API provides read and write access to the query of a
<code>URL</code>. The <code>URLSearchParams</code> class can also be used standalone with one of the
four following constructors.
The <code>URLSearchParams</code> class is also available on the global object.</p>
<p>The WHATWG <code>URLSearchParams</code> interface and the <a href="querystring.html"><code>querystring</code></a> module have
similar purpose, but the purpose of the <a href="querystring.html"><code>querystring</code></a> module is more
general, as it allows the customization of delimiter characters (<code>&</code> and <code>=</code>).
On the other hand, this API is designed purely for URL query strings.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/?abc=123'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">searchParams</span>.<span class="hljs-title function_">get</span>(<span class="hljs-string">'abc'</span>));
<span class="hljs-comment">// Prints 123</span>
myURL.<span class="hljs-property">searchParams</span>.<span class="hljs-title function_">append</span>(<span class="hljs-string">'abc'</span>, <span class="hljs-string">'xyz'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/?abc=123&abc=xyz</span>
myURL.<span class="hljs-property">searchParams</span>.<span class="hljs-title function_">delete</span>(<span class="hljs-string">'abc'</span>);
myURL.<span class="hljs-property">searchParams</span>.<span class="hljs-title function_">set</span>(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/?a=b</span>
<span class="hljs-keyword">const</span> newSearchParams = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(myURL.<span class="hljs-property">searchParams</span>);
<span class="hljs-comment">// The above is equivalent to</span>
<span class="hljs-comment">// const newSearchParams = new URLSearchParams(myURL.search);</span>
newSearchParams.<span class="hljs-title function_">append</span>(<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/?a=b</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(newSearchParams.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints a=b&a=c</span>
<span class="hljs-comment">// newSearchParams.toString() is implicitly called</span>
myURL.<span class="hljs-property">search</span> = newSearchParams;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/?a=b&a=c</span>
newSearchParams.<span class="hljs-title function_">delete</span>(<span class="hljs-string">'a'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/?a=b&a=c</span></code> <button class="copy-button">copy</button></pre>
<h5><code>new URLSearchParams()</code><span><a class="mark" href="#all_url_new-urlsearchparams" id="all_url_new-urlsearchparams">#</a></span><a aria-hidden="true" class="legacy" id="url_new_urlsearchparams"></a></h5>
<p>Instantiate a new empty <code>URLSearchParams</code> object.</p>
<h5><code>new URLSearchParams(string)</code><span><a class="mark" href="#all_url_new-urlsearchparamsstring" id="all_url_new-urlsearchparamsstring">#</a></span><a aria-hidden="true" class="legacy" id="url_new_urlsearchparams_string"></a></h5>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A query string</li>
</ul>
<p>Parse the <code>string</code> as a query string, and use it to instantiate a new
<code>URLSearchParams</code> object. A leading <code>'?'</code>, if present, is ignored.</p>
<pre><code class="language-js"><span class="hljs-keyword">let</span> params;
params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-string">'user=abc&query=xyz'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">get</span>(<span class="hljs-string">'user'</span>));
<span class="hljs-comment">// Prints 'abc'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints 'user=abc&query=xyz'</span>
params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-string">'?user=abc&query=xyz'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints 'user=abc&query=xyz'</span></code> <button class="copy-button">copy</button></pre>
<h5><code>new URLSearchParams(obj)</code><span><a class="mark" href="#all_url_new-urlsearchparamsobj" id="all_url_new-urlsearchparamsobj">#</a></span><a aria-hidden="true" class="legacy" id="url_new_urlsearchparams_obj"></a></h5>
<div class="api_metadata">
<span>Added in: v7.10.0, v6.13.0</span>
</div>
<ul>
<li><code>obj</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object representing a collection of key-value pairs</li>
</ul>
<p>Instantiate a new <code>URLSearchParams</code> object with a query hash map. The key and
value of each property of <code>obj</code> are always coerced to strings.</p>
<p>Unlike <a href="querystring.html"><code>querystring</code></a> module, duplicate keys in the form of array values are
not allowed. Arrays are stringified using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString"><code>array.toString()</code></a>, which simply
joins all array elements with commas.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>({
<span class="hljs-attr">user</span>: <span class="hljs-string">'abc'</span>,
<span class="hljs-attr">query</span>: [<span class="hljs-string">'first'</span>, <span class="hljs-string">'second'</span>],
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">getAll</span>(<span class="hljs-string">'query'</span>));
<span class="hljs-comment">// Prints [ 'first,second' ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints 'user=abc&query=first%2Csecond'</span></code> <button class="copy-button">copy</button></pre>
<h5><code>new URLSearchParams(iterable)</code><span><a class="mark" href="#all_url_new-urlsearchparamsiterable" id="all_url_new-urlsearchparamsiterable">#</a></span><a aria-hidden="true" class="legacy" id="url_new_urlsearchparams_iterable"></a></h5>
<div class="api_metadata">
<span>Added in: v7.10.0, v6.13.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> An iterable object whose elements are key-value pairs</li>
</ul>
<p>Instantiate a new <code>URLSearchParams</code> object with an iterable map in a way that
is similar to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a>'s constructor. <code>iterable</code> can be an <code>Array</code> or any
iterable object. That means <code>iterable</code> can be another <code>URLSearchParams</code>, in
which case the constructor will simply create a clone of the provided
<code>URLSearchParams</code>. Elements of <code>iterable</code> are key-value pairs, and can
themselves be any iterable object.</p>
<p>Duplicate keys are allowed.</p>
<pre><code class="language-js"><span class="hljs-keyword">let</span> params;
<span class="hljs-comment">// Using an array</span>
params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>([
[<span class="hljs-string">'user'</span>, <span class="hljs-string">'abc'</span>],
[<span class="hljs-string">'query'</span>, <span class="hljs-string">'first'</span>],
[<span class="hljs-string">'query'</span>, <span class="hljs-string">'second'</span>],
]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints 'user=abc&query=first&query=second'</span>
<span class="hljs-comment">// Using a Map object</span>
<span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();
map.<span class="hljs-title function_">set</span>(<span class="hljs-string">'user'</span>, <span class="hljs-string">'abc'</span>);
map.<span class="hljs-title function_">set</span>(<span class="hljs-string">'query'</span>, <span class="hljs-string">'xyz'</span>);
params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(map);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints 'user=abc&query=xyz'</span>
<span class="hljs-comment">// Using a generator function</span>
<span class="hljs-keyword">function</span>* <span class="hljs-title function_">getQueryPairs</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">yield</span> [<span class="hljs-string">'user'</span>, <span class="hljs-string">'abc'</span>];
<span class="hljs-keyword">yield</span> [<span class="hljs-string">'query'</span>, <span class="hljs-string">'first'</span>];
<span class="hljs-keyword">yield</span> [<span class="hljs-string">'query'</span>, <span class="hljs-string">'second'</span>];
}
params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-title function_">getQueryPairs</span>());
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints 'user=abc&query=first&query=second'</span>
<span class="hljs-comment">// Each key-value pair must have exactly two elements</span>
<span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>([
[<span class="hljs-string">'user'</span>, <span class="hljs-string">'abc'</span>, <span class="hljs-string">'error'</span>],
]);
<span class="hljs-comment">// Throws TypeError [ERR_INVALID_TUPLE]:</span>
<span class="hljs-comment">// Each query pair must be an iterable [name, value] tuple</span></code> <button class="copy-button">copy</button></pre>
<h5><code>urlSearchParams.append(name, value)</code><span><a class="mark" href="#all_url_urlsearchparamsappendname-value" id="all_url_urlsearchparamsappendname-value">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_append_name_value"></a></h5>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Append a new name-value pair to the query string.</p>
<h5><code>urlSearchParams.delete(name[, value])</code><span><a class="mark" href="#all_url_urlsearchparamsdeletename-value" id="all_url_urlsearchparamsdeletename-value">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_delete_name_value"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.2.0</td>
<td><p>Add support for optional <code>value</code> argument.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>If <code>value</code> is provided, removes all name-value pairs
where name is <code>name</code> and value is <code>value</code>..</p>
<p>If <code>value</code> is not provided, removes all name-value pairs whose name is <code>name</code>.</p>
<h5><code>urlSearchParams.entries()</code><span><a class="mark" href="#all_url_urlsearchparamsentries" id="all_url_urlsearchparamsentries">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_entries"></a></h5>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li>
</ul>
<p>Returns an ES6 <code>Iterator</code> over each of the name-value pairs in the query.
Each item of the iterator is a JavaScript <code>Array</code>. The first item of the <code>Array</code>
is the <code>name</code>, the second item of the <code>Array</code> is the <code>value</code>.</p>
<p>Alias for <a href="#all_url_urlsearchparamssymboliterator"><code>urlSearchParams[@@iterator]()</code></a>.</p>
<h5><code>urlSearchParams.forEach(fn[, thisArg])</code><span><a class="mark" href="#all_url_urlsearchparamsforeachfn-thisarg" id="all_url_urlsearchparamsforeachfn-thisarg">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_foreach_fn_thisarg"></a></h5>
<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</td>
<td><p>Passing an invalid callback to the <code>fn</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Invoked for each name-value pair in the query</li>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> To be used as <code>this</code> value for when <code>fn</code> is called</li>
</ul>
<p>Iterates over each name-value pair in the query and invokes the given function.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/?a=b&c=d'</span>);
myURL.<span class="hljs-property">searchParams</span>.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">value, name, searchParams</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name, value, myURL.<span class="hljs-property">searchParams</span> === searchParams);
});
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// a b true</span>
<span class="hljs-comment">// c d true</span></code> <button class="copy-button">copy</button></pre>
<h5><code>urlSearchParams.get(name)</code><span><a class="mark" href="#all_url_urlsearchparamsgetname" id="all_url_urlsearchparamsgetname">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_get_name"></a></h5>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <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 string or <code>null</code> if there is no name-value pair
with the given <code>name</code>.</li>
</ul>
<p>Returns the value of the first name-value pair whose name is <code>name</code>. If there
are no such pairs, <code>null</code> is returned.</p>
<h5><code>urlSearchParams.getAll(name)</code><span><a class="mark" href="#all_url_urlsearchparamsgetallname" id="all_url_urlsearchparamsgetallname">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_getall_name"></a></h5>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>Returns the values of all name-value pairs whose name is <code>name</code>. If there are
no such pairs, an empty array is returned.</p>
<h5><code>urlSearchParams.has(name[, value])</code><span><a class="mark" href="#all_url_urlsearchparamshasname-value" id="all_url_urlsearchparamshasname-value">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_has_name_value"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.2.0</td>
<td><p>Add support for optional <code>value</code> argument.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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>Checks if the <code>URLSearchParams</code> object contains key-value pair(s) based on
<code>name</code> and an optional <code>value</code> argument.</p>
<p>If <code>value</code> is provided, returns <code>true</code> when name-value pair with
same <code>name</code> and <code>value</code> exists.</p>
<p>If <code>value</code> is not provided, returns <code>true</code> if there is at least one name-value
pair whose name is <code>name</code>.</p>
<h5><code>urlSearchParams.keys()</code><span><a class="mark" href="#all_url_urlsearchparamskeys" id="all_url_urlsearchparamskeys">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_keys"></a></h5>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li>
</ul>
<p>Returns an ES6 <code>Iterator</code> over the names of each name-value pair.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-string">'foo=bar&foo=baz'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> name <span class="hljs-keyword">of</span> params.<span class="hljs-title function_">keys</span>()) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// foo</span>
<span class="hljs-comment">// foo</span></code> <button class="copy-button">copy</button></pre>
<h5><code>urlSearchParams.set(name, value)</code><span><a class="mark" href="#all_url_urlsearchparamssetname-value" id="all_url_urlsearchparamssetname-value">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_set_name_value"></a></h5>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Sets the value in the <code>URLSearchParams</code> object associated with <code>name</code> to
<code>value</code>. If there are any pre-existing name-value pairs whose names are <code>name</code>,
set the first such pair's value to <code>value</code> and remove all others. If not,
append the name-value pair to the query string.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>();
params.<span class="hljs-title function_">append</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
params.<span class="hljs-title function_">append</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'baz'</span>);
params.<span class="hljs-title function_">append</span>(<span class="hljs-string">'abc'</span>, <span class="hljs-string">'def'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints foo=bar&foo=baz&abc=def</span>
params.<span class="hljs-title function_">set</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'def'</span>);
params.<span class="hljs-title function_">set</span>(<span class="hljs-string">'xyz'</span>, <span class="hljs-string">'opq'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints foo=def&abc=def&xyz=opq</span></code> <button class="copy-button">copy</button></pre>
<h5><code>urlSearchParams.size</code><span><a class="mark" href="#all_url_urlsearchparamssize" id="all_url_urlsearchparamssize">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_size"></a></h5>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p>The total number of parameter entries.</p>
<h5><code>urlSearchParams.sort()</code><span><a class="mark" href="#all_url_urlsearchparamssort" id="all_url_urlsearchparamssort">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_sort"></a></h5>
<div class="api_metadata">
<span>Added in: v7.7.0, v6.13.0</span>
</div>
<p>Sort all existing name-value pairs in-place by their names. Sorting is done
with a <a href="https://en.wikipedia.org/wiki/Sorting_algorithm#Stability">stable sorting algorithm</a>, so relative order between name-value pairs
with the same name is preserved.</p>
<p>This method can be used, in particular, to increase cache hits.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-string">'query[]=abc&type=search&query[]=123'</span>);
params.<span class="hljs-title function_">sort</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints query%5B%5D=abc&query%5B%5D=123&type=search</span></code> <button class="copy-button">copy</button></pre>
<h5><code>urlSearchParams.toString()</code><span><a class="mark" href="#all_url_urlsearchparamstostring" id="all_url_urlsearchparamstostring">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_tostring"></a></h5>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the search parameters serialized as a string, with characters
percent-encoded where necessary.</p>
<h5><code>urlSearchParams.values()</code><span><a class="mark" href="#all_url_urlsearchparamsvalues" id="all_url_urlsearchparamsvalues">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_values"></a></h5>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li>
</ul>
<p>Returns an ES6 <code>Iterator</code> over the values of each name-value pair.</p>
<h5><code>urlSearchParams[Symbol.iterator]()</code><span><a class="mark" href="#all_url_urlsearchparamssymboliterator" id="all_url_urlsearchparamssymboliterator">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_symbol_iterator"></a></h5>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li>
</ul>
<p>Returns an ES6 <code>Iterator</code> over each of the name-value pairs in the query string.
Each item of the iterator is a JavaScript <code>Array</code>. The first item of the <code>Array</code>
is the <code>name</code>, the second item of the <code>Array</code> is the <code>value</code>.</p>
<p>Alias for <a href="#all_url_urlsearchparamsentries"><code>urlSearchParams.entries()</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-string">'foo=bar&xyz=baz'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [name, value] <span class="hljs-keyword">of</span> params) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name, value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// foo bar</span>
<span class="hljs-comment">// xyz baz</span></code> <button class="copy-button">copy</button></pre>
<h4><code>url.domainToASCII(domain)</code><span><a class="mark" href="#all_url_urldomaintoasciidomain" id="all_url_urldomaintoasciidomain">#</a></span><a aria-hidden="true" class="legacy" id="url_url_domaintoascii_domain"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>ICU requirement is removed.</p></td></tr>
<tr><td>v7.4.0, v6.13.0</td>
<td><p><span>Added in: v7.4.0, v6.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>domain</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the <a href="https://tools.ietf.org/html/rfc5891#section-4.4">Punycode</a> ASCII serialization of the <code>domain</code>. If <code>domain</code> is an
invalid domain, the empty string is returned.</p>
<p>It performs the inverse operation to <a href="#all_url_urldomaintounicodedomain"><code>url.domainToUnicode()</code></a>.</p>
<pre class="with-32-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> url <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToASCII</span>(<span class="hljs-string">'español.com'</span>));
<span class="hljs-comment">// Prints xn--espaol-zwa.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToASCII</span>(<span class="hljs-string">'中文.com'</span>));
<span class="hljs-comment">// Prints xn--fiq228c.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToASCII</span>(<span class="hljs-string">'xn--iñvalid.com'</span>));
<span class="hljs-comment">// Prints an empty string</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToASCII</span>(<span class="hljs-string">'español.com'</span>));
<span class="hljs-comment">// Prints xn--espaol-zwa.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToASCII</span>(<span class="hljs-string">'中文.com'</span>));
<span class="hljs-comment">// Prints xn--fiq228c.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToASCII</span>(<span class="hljs-string">'xn--iñvalid.com'</span>));
<span class="hljs-comment">// Prints an empty string</span></code><button class="copy-button">copy</button></pre>
<h4><code>url.domainToUnicode(domain)</code><span><a class="mark" href="#all_url_urldomaintounicodedomain" id="all_url_urldomaintounicodedomain">#</a></span><a aria-hidden="true" class="legacy" id="url_url_domaintounicode_domain"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>ICU requirement is removed.</p></td></tr>
<tr><td>v7.4.0, v6.13.0</td>
<td><p><span>Added in: v7.4.0, v6.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>domain</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the Unicode serialization of the <code>domain</code>. If <code>domain</code> is an invalid
domain, the empty string is returned.</p>
<p>It performs the inverse operation to <a href="#all_url_urldomaintoasciidomain"><code>url.domainToASCII()</code></a>.</p>
<pre class="with-32-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> url <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToUnicode</span>(<span class="hljs-string">'xn--espaol-zwa.com'</span>));
<span class="hljs-comment">// Prints español.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToUnicode</span>(<span class="hljs-string">'xn--fiq228c.com'</span>));
<span class="hljs-comment">// Prints 中文.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToUnicode</span>(<span class="hljs-string">'xn--iñvalid.com'</span>));
<span class="hljs-comment">// Prints an empty string</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToUnicode</span>(<span class="hljs-string">'xn--espaol-zwa.com'</span>));
<span class="hljs-comment">// Prints español.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToUnicode</span>(<span class="hljs-string">'xn--fiq228c.com'</span>));
<span class="hljs-comment">// Prints 中文.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToUnicode</span>(<span class="hljs-string">'xn--iñvalid.com'</span>));
<span class="hljs-comment">// Prints an empty string</span></code><button class="copy-button">copy</button></pre>
<h4><code>url.fileURLToPath(url[, options])</code><span><a class="mark" href="#all_url_urlfileurltopathurl-options" id="all_url_urlfileurltopathurl-options">#</a></span><a aria-hidden="true" class="legacy" id="url_url_fileurltopath_url_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>v20.13.0</td>
<td><p>The <code>options</code> argument can now be used to determine how to parse the <code>path</code> argument.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p><span>Added in: v10.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>url</code> <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The file URL string or URL object to convert to a path.</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>windows</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> <code>true</code> if the <code>path</code> should be
return as a windows filepath, <code>false</code> for posix, and
<code>undefined</code> for the system default.
<strong>Default:</strong> <code>undefined</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The fully-resolved platform-specific Node.js file path.</li>
</ul>
<p>This function ensures the correct decodings of percent-encoded characters as
well as ensuring a cross-platform valid absolute path string.</p>
<pre class="with-66-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> { fileURLToPath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">const</span> __filename = <span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/path/'</span>).<span class="hljs-property">pathname</span>; <span class="hljs-comment">// Incorrect: /C:/path/</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file:///C:/path/'</span>); <span class="hljs-comment">// Correct: C:\path\ (Windows)</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file://nas/foo.txt'</span>).<span class="hljs-property">pathname</span>; <span class="hljs-comment">// Incorrect: /foo.txt</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file://nas/foo.txt'</span>); <span class="hljs-comment">// Correct: \\nas\foo.txt (Windows)</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///你好.txt'</span>).<span class="hljs-property">pathname</span>; <span class="hljs-comment">// Incorrect: /%E4%BD%A0%E5%A5%BD.txt</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file:///你好.txt'</span>); <span class="hljs-comment">// Correct: /你好.txt (POSIX)</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///hello world'</span>).<span class="hljs-property">pathname</span>; <span class="hljs-comment">// Incorrect: /hello%20world</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file:///hello world'</span>); <span class="hljs-comment">// Correct: /hello world (POSIX)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { fileURLToPath } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/path/'</span>).<span class="hljs-property">pathname</span>; <span class="hljs-comment">// Incorrect: /C:/path/</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file:///C:/path/'</span>); <span class="hljs-comment">// Correct: C:\path\ (Windows)</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file://nas/foo.txt'</span>).<span class="hljs-property">pathname</span>; <span class="hljs-comment">// Incorrect: /foo.txt</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file://nas/foo.txt'</span>); <span class="hljs-comment">// Correct: \\nas\foo.txt (Windows)</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///你好.txt'</span>).<span class="hljs-property">pathname</span>; <span class="hljs-comment">// Incorrect: /%E4%BD%A0%E5%A5%BD.txt</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file:///你好.txt'</span>); <span class="hljs-comment">// Correct: /你好.txt (POSIX)</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///hello world'</span>).<span class="hljs-property">pathname</span>; <span class="hljs-comment">// Incorrect: /hello%20world</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file:///hello world'</span>); <span class="hljs-comment">// Correct: /hello world (POSIX)</span></code><button class="copy-button">copy</button></pre>
<h4><code>url.format(URL[, options])</code><span><a class="mark" href="#all_url_urlformaturl-options" id="all_url_urlformaturl-options">#</a></span><a aria-hidden="true" class="legacy" id="url_url_format_url_options"></a></h4>
<div class="api_metadata">
<span>Added in: v7.6.0</span>
</div>
<ul>
<li><code>URL</code> <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> A <a href="#all_url_the-whatwg-url-api">WHATWG URL</a> object</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>auth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the serialized URL string should include the
username and password, <code>false</code> otherwise. <strong>Default:</strong> <code>true</code>.</li>
<li><code>fragment</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the serialized URL string should include the
fragment, <code>false</code> otherwise. <strong>Default:</strong> <code>true</code>.</li>
<li><code>search</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the serialized URL string should include the
search query, <code>false</code> otherwise. <strong>Default:</strong> <code>true</code>.</li>
<li><code>unicode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if Unicode characters appearing in the host
component of the URL string should be encoded directly as opposed to being
Punycode encoded. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns a customizable serialization of a URL <code>String</code> representation of a
<a href="#all_url_the-whatwg-url-api">WHATWG URL</a> object.</p>
<p>The URL object has both a <code>toString()</code> method and <code>href</code> property that return
string serializations of the URL. These are not, however, customizable in
any way. The <code>url.format(URL[, options])</code> method allows for basic customization
of the output.</p>
<pre class="with-48-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> url <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://a:b@測試?abc#foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://a:b@xn--g6w251d/?abc#foo</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints https://a:b@xn--g6w251d/?abc#foo</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">format</span>(myURL, { <span class="hljs-attr">fragment</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">unicode</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">auth</span>: <span class="hljs-literal">false</span> }));
<span class="hljs-comment">// Prints 'https://測試/?abc'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://a:b@測試?abc#foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://a:b@xn--g6w251d/?abc#foo</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints https://a:b@xn--g6w251d/?abc#foo</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">format</span>(myURL, { <span class="hljs-attr">fragment</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">unicode</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">auth</span>: <span class="hljs-literal">false</span> }));
<span class="hljs-comment">// Prints 'https://測試/?abc'</span></code><button class="copy-button">copy</button></pre>
<h4><code>url.pathToFileURL(path[, options])</code><span><a class="mark" href="#all_url_urlpathtofileurlpath-options" id="all_url_urlpathtofileurlpath-options">#</a></span><a aria-hidden="true" class="legacy" id="url_url_pathtofileurl_path_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>v20.13.0</td>
<td><p>The <code>options</code> argument can now be used to determine how to return the <code>path</code> value.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p><span>Added in: v10.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The path to convert to a File URL.</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>windows</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> <code>true</code> if the <code>path</code> should be
treated as a windows filepath, <code>false</code> for posix, and
<code>undefined</code> for the system default.
<strong>Default:</strong> <code>undefined</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> The file URL object.</li>
</ul>
<p>This function ensures that <code>path</code> is resolved absolutely, and that the URL
control characters are correctly encoded when converting into a File URL.</p>
<pre class="with-66-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> { pathToFileURL } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'/foo#1'</span>, <span class="hljs-string">'file:'</span>); <span class="hljs-comment">// Incorrect: file:///foo#1</span>
<span class="hljs-title function_">pathToFileURL</span>(<span class="hljs-string">'/foo#1'</span>); <span class="hljs-comment">// Correct: file:///foo%231 (POSIX)</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'/some/path%.c'</span>, <span class="hljs-string">'file:'</span>); <span class="hljs-comment">// Incorrect: file:///some/path%.c</span>
<span class="hljs-title function_">pathToFileURL</span>(<span class="hljs-string">'/some/path%.c'</span>); <span class="hljs-comment">// Correct: file:///some/path%25.c (POSIX)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(__filename); <span class="hljs-comment">// Incorrect: throws (POSIX)</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(__filename); <span class="hljs-comment">// Incorrect: C:\... (Windows)</span>
<span class="hljs-title function_">pathToFileURL</span>(__filename); <span class="hljs-comment">// Correct: file:///... (POSIX)</span>
<span class="hljs-title function_">pathToFileURL</span>(__filename); <span class="hljs-comment">// Correct: file:///C:/... (Windows)</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'/foo#1'</span>, <span class="hljs-string">'file:'</span>); <span class="hljs-comment">// Incorrect: file:///foo#1</span>
<span class="hljs-title function_">pathToFileURL</span>(<span class="hljs-string">'/foo#1'</span>); <span class="hljs-comment">// Correct: file:///foo%231 (POSIX)</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'/some/path%.c'</span>, <span class="hljs-string">'file:'</span>); <span class="hljs-comment">// Incorrect: file:///some/path%.c</span>
<span class="hljs-title function_">pathToFileURL</span>(<span class="hljs-string">'/some/path%.c'</span>); <span class="hljs-comment">// Correct: file:///some/path%25.c (POSIX)</span></code><button class="copy-button">copy</button></pre>
<h4><code>url.urlToHttpOptions(url)</code><span><a class="mark" href="#all_url_urlurltohttpoptionsurl" id="all_url_urlurltohttpoptionsurl">#</a></span><a aria-hidden="true" class="legacy" id="url_url_urltohttpoptions_url"></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.9.0</td>
<td><p>The returned object will also contain all the own enumerable properties of the <code>url</code> argument.</p></td></tr>
<tr><td>v15.7.0, v14.18.0</td>
<td><p><span>Added in: v15.7.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>url</code> <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> The <a href="#all_url_the-whatwg-url-api">WHATWG URL</a> object to convert to an options object.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Options object
<ul>
<li><code>protocol</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Protocol to use.</li>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A domain name or IP address of the server to issue the
request to.</li>
<li><code>hash</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The fragment portion of the URL.</li>
<li><code>search</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The serialized query portion of the URL.</li>
<li><code>pathname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The path portion of the URL.</li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Request path. Should include query string if any.
E.G. <code>'/index.html?page=12'</code>. An exception is thrown when the request path
contains illegal characters. Currently, only spaces are rejected but that
may change in the future.</li>
<li><code>href</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The serialized URL.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port of remote server.</li>
<li><code>auth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Basic authentication i.e. <code>'user:password'</code> to compute an
Authorization header.</li>
</ul>
</li>
</ul>
<p>This utility function converts a URL object into an ordinary options object as
expected by the <a href="#all_http_httprequestoptions-callback"><code>http.request()</code></a> and <a href="#all_https_httpsrequestoptions-callback"><code>https.request()</code></a> APIs.</p>
<pre class="with-49-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> { urlToHttpOptions } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://a:b@測試?abc#foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">urlToHttpOptions</span>(myURL));
<span class="hljs-comment">/*
{
protocol: 'https:',
hostname: 'xn--g6w251d',
hash: '#foo',
search: '?abc',
pathname: '/',
path: '/?abc',
href: 'https://a:b@xn--g6w251d/?abc#foo',
auth: 'a:b'
}
*/</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { urlToHttpOptions } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://a:b@測試?abc#foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">urlToHttpOptions</span>(myURL));
<span class="hljs-comment">/*
{
protocol: 'https:',
hostname: 'xn--g6w251d',
hash: '#foo',
search: '?abc',
pathname: '/',
path: '/?abc',
href: 'https://a:b@xn--g6w251d/?abc#foo',
auth: 'a:b'
}
*/</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Legacy URL API<span><a class="mark" href="#all_url_legacy-url-api" id="all_url_legacy-url-api">#</a></span><a aria-hidden="true" class="legacy" id="url_legacy_url_api"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.13.0, v14.17.0</td>
<td><p>Deprecation revoked. Status changed to "Legacy".</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>This API is deprecated.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use the WHATWG URL API instead.</div><p></p>
<h4>Legacy <code>urlObject</code><span><a class="mark" href="#all_url_legacy-urlobject" id="all_url_legacy-urlobject">#</a></span><a aria-hidden="true" class="legacy" id="url_legacy_urlobject"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.13.0, v14.17.0</td>
<td><p>Deprecation revoked. Status changed to "Legacy".</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>The Legacy URL API is deprecated. Use the WHATWG URL API.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use the WHATWG URL API instead.</div><p></p>
<p>The legacy <code>urlObject</code> (<code>require('node:url').Url</code> or
<code>import { Url } from 'node:url'</code>) is
created and returned by the <code>url.parse()</code> function.</p>
<h5><code>urlObject.auth</code><span><a class="mark" href="#all_url_urlobjectauth" id="all_url_urlobjectauth">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_auth"></a></h5>
<p>The <code>auth</code> property is the username and password portion of the URL, also
referred to as <em>userinfo</em>. This string subset follows the <code>protocol</code> and
double slashes (if present) and precedes the <code>host</code> component, delimited by <code>@</code>.
The string is either the username, or it is the username and password separated
by <code>:</code>.</p>
<p>For example: <code>'user:pass'</code>.</p>
<h5><code>urlObject.hash</code><span><a class="mark" href="#all_url_urlobjecthash" id="all_url_urlobjecthash">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_hash"></a></h5>
<p>The <code>hash</code> property is the fragment identifier portion of the URL including the
leading <code>#</code> character.</p>
<p>For example: <code>'#hash'</code>.</p>
<h5><code>urlObject.host</code><span><a class="mark" href="#all_url_urlobjecthost" id="all_url_urlobjecthost">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_host"></a></h5>
<p>The <code>host</code> property is the full lower-cased host portion of the URL, including
the <code>port</code> if specified.</p>
<p>For example: <code>'sub.example.com:8080'</code>.</p>
<h5><code>urlObject.hostname</code><span><a class="mark" href="#all_url_urlobjecthostname" id="all_url_urlobjecthostname">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_hostname"></a></h5>
<p>The <code>hostname</code> property is the lower-cased host name portion of the <code>host</code>
component <em>without</em> the <code>port</code> included.</p>
<p>For example: <code>'sub.example.com'</code>.</p>
<h5><code>urlObject.href</code><span><a class="mark" href="#all_url_urlobjecthref" id="all_url_urlobjecthref">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_href"></a></h5>
<p>The <code>href</code> property is the full URL string that was parsed with both the
<code>protocol</code> and <code>host</code> components converted to lower-case.</p>
<p>For example: <code>'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'</code>.</p>
<h5><code>urlObject.path</code><span><a class="mark" href="#all_url_urlobjectpath" id="all_url_urlobjectpath">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_path"></a></h5>
<p>The <code>path</code> property is a concatenation of the <code>pathname</code> and <code>search</code>
components.</p>
<p>For example: <code>'/p/a/t/h?query=string'</code>.</p>
<p>No decoding of the <code>path</code> is performed.</p>
<h5><code>urlObject.pathname</code><span><a class="mark" href="#all_url_urlobjectpathname" id="all_url_urlobjectpathname">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_pathname"></a></h5>
<p>The <code>pathname</code> property consists of the entire path section of the URL. This
is everything following the <code>host</code> (including the <code>port</code>) and before the start
of the <code>query</code> or <code>hash</code> components, delimited by either the ASCII question
mark (<code>?</code>) or hash (<code>#</code>) characters.</p>
<p>For example: <code>'/p/a/t/h'</code>.</p>
<p>No decoding of the path string is performed.</p>
<h5><code>urlObject.port</code><span><a class="mark" href="#all_url_urlobjectport" id="all_url_urlobjectport">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_port"></a></h5>
<p>The <code>port</code> property is the numeric port portion of the <code>host</code> component.</p>
<p>For example: <code>'8080'</code>.</p>
<h5><code>urlObject.protocol</code><span><a class="mark" href="#all_url_urlobjectprotocol" id="all_url_urlobjectprotocol">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_protocol"></a></h5>
<p>The <code>protocol</code> property identifies the URL's lower-cased protocol scheme.</p>
<p>For example: <code>'http:'</code>.</p>
<h5><code>urlObject.query</code><span><a class="mark" href="#all_url_urlobjectquery" id="all_url_urlobjectquery">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_query"></a></h5>
<p>The <code>query</code> property is either the query string without the leading ASCII
question mark (<code>?</code>), or an object returned by the <a href="querystring.html"><code>querystring</code></a> module's
<code>parse()</code> method. Whether the <code>query</code> property is a string or object is
determined by the <code>parseQueryString</code> argument passed to <code>url.parse()</code>.</p>
<p>For example: <code>'query=string'</code> or <code>{'query': 'string'}</code>.</p>
<p>If returned as a string, no decoding of the query string is performed. If
returned as an object, both keys and values are decoded.</p>
<h5><code>urlObject.search</code><span><a class="mark" href="#all_url_urlobjectsearch" id="all_url_urlobjectsearch">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_search"></a></h5>
<p>The <code>search</code> property consists of the entire "query string" portion of the
URL, including the leading ASCII question mark (<code>?</code>) character.</p>
<p>For example: <code>'?query=string'</code>.</p>
<p>No decoding of the query string is performed.</p>
<h5><code>urlObject.slashes</code><span><a class="mark" href="#all_url_urlobjectslashes" id="all_url_urlobjectslashes">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_slashes"></a></h5>
<p>The <code>slashes</code> property is a <code>boolean</code> with a value of <code>true</code> if two ASCII
forward-slash characters (<code>/</code>) are required following the colon in the
<code>protocol</code>.</p>
<h4><code>url.format(urlObject)</code><span><a class="mark" href="#all_url_urlformaturlobject" id="all_url_urlformaturlobject">#</a></span><a aria-hidden="true" class="legacy" id="url_url_format_urlobject"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0</td>
<td><p>Now throws an <code>ERR_INVALID_URL</code> exception when Punycode conversion of a hostname introduces changes that could cause the URL to be re-parsed differently.</p></td></tr>
<tr><td>v15.13.0, v14.17.0</td>
<td><p>Deprecation revoked. Status changed to "Legacy".</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>The Legacy URL API is deprecated. Use the WHATWG URL API.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>URLs with a <code>file:</code> scheme will now always use the correct number of slashes regardless of <code>slashes</code> option. A falsy <code>slashes</code> option with no protocol is now also respected at all times.</p></td></tr>
<tr><td>v0.1.25</td>
<td><p><span>Added in: v0.1.25</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use the WHATWG URL API instead.</div><p></p>
<ul>
<li><code>urlObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A URL object (as returned by <code>url.parse()</code> or
constructed otherwise). If a string, it is converted to an object by passing
it to <code>url.parse()</code>.</li>
</ul>
<p>The <code>url.format()</code> method returns a formatted URL string derived from
<code>urlObject</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
url.<span class="hljs-title function_">format</span>({
<span class="hljs-attr">protocol</span>: <span class="hljs-string">'https'</span>,
<span class="hljs-attr">hostname</span>: <span class="hljs-string">'example.com'</span>,
<span class="hljs-attr">pathname</span>: <span class="hljs-string">'/some/path'</span>,
<span class="hljs-attr">query</span>: {
<span class="hljs-attr">page</span>: <span class="hljs-number">1</span>,
<span class="hljs-attr">format</span>: <span class="hljs-string">'json'</span>,
},
});
<span class="hljs-comment">// => 'https://example.com/some/path?page=1&format=json'</span></code> <button class="copy-button">copy</button></pre>
<p>If <code>urlObject</code> is not an object or a string, <code>url.format()</code> will throw a
<a href="#all_errors_class-typeerror"><code>TypeError</code></a>.</p>
<p>The formatting process operates as follows:</p>
<ul>
<li>A new empty string <code>result</code> is created.</li>
<li>If <code>urlObject.protocol</code> is a string, it is appended as-is to <code>result</code>.</li>
<li>Otherwise, if <code>urlObject.protocol</code> is not <code>undefined</code> and is not a string, an
<a href="#all_errors_class-error"><code>Error</code></a> is thrown.</li>
<li>For all string values of <code>urlObject.protocol</code> that <em>do not end</em> with an ASCII
colon (<code>:</code>) character, the literal string <code>:</code> will be appended to <code>result</code>.</li>
<li>If either of the following conditions is true, then the literal string <code>//</code>
will be appended to <code>result</code>:
<ul>
<li><code>urlObject.slashes</code> property is true;</li>
<li><code>urlObject.protocol</code> begins with <code>http</code>, <code>https</code>, <code>ftp</code>, <code>gopher</code>, or
<code>file</code>;</li>
</ul>
</li>
<li>If the value of the <code>urlObject.auth</code> property is truthy, and either
<code>urlObject.host</code> or <code>urlObject.hostname</code> are not <code>undefined</code>, the value of
<code>urlObject.auth</code> will be coerced into a string and appended to <code>result</code>
followed by the literal string <code>@</code>.</li>
<li>If the <code>urlObject.host</code> property is <code>undefined</code> then:
<ul>
<li>If the <code>urlObject.hostname</code> is a string, it is appended to <code>result</code>.</li>
<li>Otherwise, if <code>urlObject.hostname</code> is not <code>undefined</code> and is not a string,
an <a href="#all_errors_class-error"><code>Error</code></a> is thrown.</li>
<li>If the <code>urlObject.port</code> property value is truthy, and <code>urlObject.hostname</code>
is not <code>undefined</code>:
<ul>
<li>The literal string <code>:</code> is appended to <code>result</code>, and</li>
<li>The value of <code>urlObject.port</code> is coerced to a string and appended to
<code>result</code>.</li>
</ul>
</li>
</ul>
</li>
<li>Otherwise, if the <code>urlObject.host</code> property value is truthy, the value of
<code>urlObject.host</code> is coerced to a string and appended to <code>result</code>.</li>
<li>If the <code>urlObject.pathname</code> property is a string that is not an empty string:
<ul>
<li>If the <code>urlObject.pathname</code> <em>does not start</em> with an ASCII forward slash
(<code>/</code>), then the literal string <code>'/'</code> is appended to <code>result</code>.</li>
<li>The value of <code>urlObject.pathname</code> is appended to <code>result</code>.</li>
</ul>
</li>
<li>Otherwise, if <code>urlObject.pathname</code> is not <code>undefined</code> and is not a string, an
<a href="#all_errors_class-error"><code>Error</code></a> is thrown.</li>
<li>If the <code>urlObject.search</code> property is <code>undefined</code> and if the <code>urlObject.query</code>
property is an <code>Object</code>, the literal string <code>?</code> is appended to <code>result</code>
followed by the output of calling the <a href="querystring.html"><code>querystring</code></a> module's <code>stringify()</code>
method passing the value of <code>urlObject.query</code>.</li>
<li>Otherwise, if <code>urlObject.search</code> is a string:
<ul>
<li>If the value of <code>urlObject.search</code> <em>does not start</em> with the ASCII question
mark (<code>?</code>) character, the literal string <code>?</code> is appended to <code>result</code>.</li>
<li>The value of <code>urlObject.search</code> is appended to <code>result</code>.</li>
</ul>
</li>
<li>Otherwise, if <code>urlObject.search</code> is not <code>undefined</code> and is not a string, an
<a href="#all_errors_class-error"><code>Error</code></a> is thrown.</li>
<li>If the <code>urlObject.hash</code> property is a string:
<ul>
<li>If the value of <code>urlObject.hash</code> <em>does not start</em> with the ASCII hash (<code>#</code>)
character, the literal string <code>#</code> is appended to <code>result</code>.</li>
<li>The value of <code>urlObject.hash</code> is appended to <code>result</code>.</li>
</ul>
</li>
<li>Otherwise, if the <code>urlObject.hash</code> property is not <code>undefined</code> and is not a
string, an <a href="#all_errors_class-error"><code>Error</code></a> is thrown.</li>
<li><code>result</code> is returned.</li>
</ul>
<h4><code>url.parse(urlString[, parseQueryString[, slashesDenoteHost]])</code><span><a class="mark" href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost" id="all_url_urlparseurlstring-parsequerystring-slashesdenotehost">#</a></span><a aria-hidden="true" class="legacy" id="url_url_parse_urlstring_parsequerystring_slashesdenotehost"></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.0.0, v18.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
<tr><td>v15.13.0, v14.17.0</td>
<td><p>Deprecation revoked. Status changed to "Legacy".</p></td></tr>
<tr><td>v11.14.0</td>
<td><p>The <code>pathname</code> property on the returned URL object is now <code>/</code> when there is no path and the protocol scheme is <code>ws:</code> or <code>wss:</code>.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>The Legacy URL API is deprecated. Use the WHATWG URL API.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>search</code> property on the returned URL object is now <code>null</code> when no query string is present.</p></td></tr>
<tr><td>v0.1.25</td>
<td><p><span>Added in: v0.1.25</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use the WHATWG URL API instead.</div><p></p>
<ul>
<li><code>urlString</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The URL string to parse.</li>
<li><code>parseQueryString</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the <code>query</code> property will always
be set to an object returned by the <a href="querystring.html"><code>querystring</code></a> module's <code>parse()</code>
method. If <code>false</code>, the <code>query</code> property on the returned URL object will be an
unparsed, undecoded string. <strong>Default:</strong> <code>false</code>.</li>
<li><code>slashesDenoteHost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the first token after the literal
string <code>//</code> and preceding the next <code>/</code> will be interpreted as the <code>host</code>.
For instance, given <code>//foo/bar</code>, the result would be
<code>{host: 'foo', pathname: '/bar'}</code> rather than <code>{pathname: '//foo/bar'}</code>.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
<p>The <code>url.parse()</code> method takes a URL string, parses it, and returns a URL
object.</p>
<p>A <code>TypeError</code> is thrown if <code>urlString</code> is not a string.</p>
<p>A <code>URIError</code> is thrown if the <code>auth</code> property is present but cannot be decoded.</p>
<p><code>url.parse()</code> uses a lenient, non-standard algorithm for parsing URL
strings. It is prone to security issues such as <a href="https://hackerone.com/reports/678487">host name spoofing</a>
and incorrect handling of usernames and passwords. Do not use with untrusted
input. CVEs are not issued for <code>url.parse()</code> vulnerabilities. Use the
<a href="#all_url_the-whatwg-url-api">WHATWG URL</a> API instead.</p>
<h4><code>url.resolve(from, to)</code><span><a class="mark" href="#all_url_urlresolvefrom-to" id="all_url_urlresolvefrom-to">#</a></span><a aria-hidden="true" class="legacy" id="url_url_resolve_from_to"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.13.0, v14.17.0</td>
<td><p>Deprecation revoked. Status changed to "Legacy".</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>The Legacy URL API is deprecated. Use the WHATWG URL API.</p></td></tr>
<tr><td>v6.6.0</td>
<td><p>The <code>auth</code> fields are now kept intact when <code>from</code> and <code>to</code> refer to the same host.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>auth</code> fields is cleared now the <code>to</code> parameter contains a hostname.</p></td></tr>
<tr><td>v6.5.0, v4.6.2</td>
<td><p>The <code>port</code> field is copied correctly now.</p></td></tr>
<tr><td>v0.1.25</td>
<td><p><span>Added in: v0.1.25</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use the WHATWG URL API instead.</div><p></p>
<ul>
<li><code>from</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The base URL to use if <code>to</code> is a relative URL.</li>
<li><code>to</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The target URL to resolve.</li>
</ul>
<p>The <code>url.resolve()</code> method resolves a target URL relative to a base URL in a
manner similar to that of a web browser resolving an anchor tag.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
url.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'/one/two/three'</span>, <span class="hljs-string">'four'</span>); <span class="hljs-comment">// '/one/two/four'</span>
url.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'http://example.com/'</span>, <span class="hljs-string">'/one'</span>); <span class="hljs-comment">// 'http://example.com/one'</span>
url.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'http://example.com/one'</span>, <span class="hljs-string">'/two'</span>); <span class="hljs-comment">// 'http://example.com/two'</span></code> <button class="copy-button">copy</button></pre>
<p>To achieve the same result using the WHATWG URL API:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params"><span class="hljs-keyword">from</span>, to</span>) {
<span class="hljs-keyword">const</span> resolvedUrl = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(to, <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-keyword">from</span>, <span class="hljs-string">'resolve://'</span>));
<span class="hljs-keyword">if</span> (resolvedUrl.<span class="hljs-property">protocol</span> === <span class="hljs-string">'resolve:'</span>) {
<span class="hljs-comment">// `from` is a relative URL.</span>
<span class="hljs-keyword">const</span> { pathname, search, hash } = resolvedUrl;
<span class="hljs-keyword">return</span> pathname + search + hash;
}
<span class="hljs-keyword">return</span> resolvedUrl.<span class="hljs-title function_">toString</span>();
}
<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'/one/two/three'</span>, <span class="hljs-string">'four'</span>); <span class="hljs-comment">// '/one/two/four'</span>
<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'http://example.com/'</span>, <span class="hljs-string">'/one'</span>); <span class="hljs-comment">// 'http://example.com/one'</span>
<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'http://example.com/one'</span>, <span class="hljs-string">'/two'</span>); <span class="hljs-comment">// 'http://example.com/two'</span></code> <button class="copy-button">copy</button></pre>
<p><a id="whatwg-percent-encoding"></a></p>
</section><section><h3>Percent-encoding in URLs<span><a class="mark" href="#all_url_percent-encoding-in-urls" id="all_url_percent-encoding-in-urls">#</a></span><a aria-hidden="true" class="legacy" id="url_percent_encoding_in_urls"></a></h3>
<p>URLs are permitted to only contain a certain range of characters. Any character
falling outside of that range must be encoded. How such characters are encoded,
and which characters to encode depends entirely on where the character is
located within the structure of the URL.</p>
<h4>Legacy API<span><a class="mark" href="#all_url_legacy-api" id="all_url_legacy-api">#</a></span><a aria-hidden="true" class="legacy" id="url_legacy_api"></a></h4>
<p>Within the Legacy API, spaces (<code>' '</code>) and the following characters will be
automatically escaped in the properties of URL objects:</p>
<pre><code class="language-text">< > " ` \r \n \t { } | \ ^ '</code> <button class="copy-button">copy</button></pre>
<p>For example, the ASCII space character (<code>' '</code>) is encoded as <code>%20</code>. The ASCII
forward slash (<code>/</code>) character is encoded as <code>%3C</code>.</p>
<h4>WHATWG API<span><a class="mark" href="#all_url_whatwg-api" id="all_url_whatwg-api">#</a></span><a aria-hidden="true" class="legacy" id="url_whatwg_api"></a></h4>
<p>The <a href="https://url.spec.whatwg.org/">WHATWG URL Standard</a> uses a more selective and fine grained approach to
selecting encoded characters than that used by the Legacy API.</p>
<p>The WHATWG algorithm defines four "percent-encode sets" that describe ranges
of characters that must be percent-encoded:</p>
<ul>
<li>
<p>The <em>C0 control percent-encode set</em> includes code points in range U+0000 to
U+001F (inclusive) and all code points greater than U+007E (~).</p>
</li>
<li>
<p>The <em>fragment percent-encode set</em> includes the <em>C0 control percent-encode set</em>
and code points U+0020 SPACE, U+0022 ("), U+003C (<), U+003E (>),
and U+0060 (`).</p>
</li>
<li>
<p>The <em>path percent-encode set</em> includes the <em>C0 control percent-encode set</em>
and code points U+0020 SPACE, U+0022 ("), U+0023 (#), U+003C (<), U+003E (>),
U+003F (?), U+0060 (`), U+007B ({), and U+007D (}).</p>
</li>
<li>
<p>The <em>userinfo encode set</em> includes the <em>path percent-encode set</em> and code
points U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+0040 (@),
U+005B ([) to U+005E(^), and U+007C (|).</p>
</li>
</ul>
<p>The <em>userinfo percent-encode set</em> is used exclusively for username and
passwords encoded within the URL. The <em>path percent-encode set</em> is used for the
path of most URLs. The <em>fragment percent-encode set</em> is used for URL fragments.
The <em>C0 control percent-encode set</em> is used for host and path under certain
specific conditions, in addition to all other cases.</p>
<p>When non-ASCII characters appear within a host name, the host name is encoded
using the <a href="https://tools.ietf.org/html/rfc5891#section-4.4">Punycode</a> algorithm. Note, however, that a host name <em>may</em> contain
<em>both</em> Punycode encoded and percent-encoded characters:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://%CF%80.example.com/foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://xn--1xa.example.com/foo</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">origin</span>);
<span class="hljs-comment">// Prints https://xn--1xa.example.com</span></code> <button class="copy-button">copy</button></pre></section>
</section>
<section><h2>Util<span><a class="mark" href="#all_util_util" id="all_util_util">#</a></span><a aria-hidden="true" class="legacy" id="util_util"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/util.js">lib/util.js</a></p>
<p>The <code>node:util</code> module supports the needs of Node.js internal APIs. Many of the
utilities are useful for application and module developers as well. To access
it:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);</code> <button class="copy-button">copy</button></pre>
<section><h3><code>util.callbackify(original)</code><span><a class="mark" href="#all_util_utilcallbackifyoriginal" id="all_util_utilcallbackifyoriginal">#</a></span><a aria-hidden="true" class="legacy" id="util_util_callbackify_original"></a></h3>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
</div>
<ul>
<li><code>original</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> An <code>async</code> function</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> a callback style function</li>
</ul>
<p>Takes an <code>async</code> function (or a function that returns a <code>Promise</code>) and returns a
function following the error-first callback style, i.e. taking
an <code>(err, value) => ...</code> callback as the last argument. In the callback, the
first argument will be the rejection reason (or <code>null</code> if the <code>Promise</code>
resolved), and the second argument will be the resolved value.</p>
<pre><code class="language-js"><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">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">fn</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">return</span> <span class="hljs-string">'hello world'</span>;
}
<span class="hljs-keyword">const</span> callbackFunction = util.<span class="hljs-title function_">callbackify</span>(fn);
<span class="hljs-title function_">callbackFunction</span>(<span class="hljs-function">(<span class="hljs-params">err, ret</span>) =></span> {
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(ret);
});</code> <button class="copy-button">copy</button></pre>
<p>Will print:</p>
<pre><code class="language-text">hello world</code> <button class="copy-button">copy</button></pre>
<p>The callback is executed asynchronously, and will have a limited stack trace.
If the callback throws, the process will emit an <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a>
event, and if not handled will exit.</p>
<p>Since <code>null</code> has a special meaning as the first argument to a callback, if a
wrapped function rejects a <code>Promise</code> with a falsy value as a reason, the value
is wrapped in an <code>Error</code> with the original value stored in a field named
<code>reason</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">fn</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-literal">null</span>);
}
<span class="hljs-keyword">const</span> callbackFunction = util.<span class="hljs-title function_">callbackify</span>(fn);
<span class="hljs-title function_">callbackFunction</span>(<span class="hljs-function">(<span class="hljs-params">err, ret</span>) =></span> {
<span class="hljs-comment">// When the Promise was rejected with `null` it is wrapped with an Error and</span>
<span class="hljs-comment">// the original value is stored in `reason`.</span>
err && <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">hasOwn</span>(err, <span class="hljs-string">'reason'</span>) && err.<span class="hljs-property">reason</span> === <span class="hljs-literal">null</span>; <span class="hljs-comment">// true</span>
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.debuglog(section[, callback])</code><span><a class="mark" href="#all_util_utildebuglogsection-callback" id="all_util_utildebuglogsection-callback">#</a></span><a aria-hidden="true" class="legacy" id="util_util_debuglog_section_callback"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.3</span>
</div>
<ul>
<li><code>section</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string identifying the portion of the application for
which the <code>debuglog</code> function is being created.</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 invoked the first time the logging function
is called with a function argument that is a more optimized logging function.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The logging function</li>
</ul>
<p>The <code>util.debuglog()</code> method is used to create a function that conditionally
writes debug messages to <code>stderr</code> based on the existence of the <code>NODE_DEBUG</code>
environment variable. If the <code>section</code> name appears within the value of that
environment variable, then the returned function operates similar to
<a href="#all_console_consoleerrordata-args"><code>console.error()</code></a>. If not, then the returned function is a no-op.</p>
<pre><code class="language-js"><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">const</span> debuglog = util.<span class="hljs-title function_">debuglog</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-title function_">debuglog</span>(<span class="hljs-string">'hello from foo [%d]'</span>, <span class="hljs-number">123</span>);</code> <button class="copy-button">copy</button></pre>
<p>If this program is run with <code>NODE_DEBUG=foo</code> in the environment, then
it will output something like:</p>
<pre><code class="language-console">FOO 3245: hello from foo [123]</code> <button class="copy-button">copy</button></pre>
<p>where <code>3245</code> is the process id. If it is not run with that
environment variable set, then it will not print anything.</p>
<p>The <code>section</code> supports wildcard also:</p>
<pre><code class="language-js"><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">const</span> debuglog = util.<span class="hljs-title function_">debuglog</span>(<span class="hljs-string">'foo-bar'</span>);
<span class="hljs-title function_">debuglog</span>(<span class="hljs-string">'hi there, it\'s foo-bar [%d]'</span>, <span class="hljs-number">2333</span>);</code> <button class="copy-button">copy</button></pre>
<p>if it is run with <code>NODE_DEBUG=foo*</code> in the environment, then it will output
something like:</p>
<pre><code class="language-console">FOO-BAR 3257: hi there, it's foo-bar [2333]</code> <button class="copy-button">copy</button></pre>
<p>Multiple comma-separated <code>section</code> names may be specified in the <code>NODE_DEBUG</code>
environment variable: <code>NODE_DEBUG=fs,net,tls</code>.</p>
<p>The optional <code>callback</code> argument can be used to replace the logging function
with a different function that doesn't have any initialization or
unnecessary wrapping.</p>
<pre><code class="language-js"><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">let</span> debuglog = util.<span class="hljs-title function_">debuglog</span>(<span class="hljs-string">'internals'</span>, <span class="hljs-function">(<span class="hljs-params">debug</span>) =></span> {
<span class="hljs-comment">// Replace with a logging function that optimizes out</span>
<span class="hljs-comment">// testing if the section is enabled</span>
debuglog = debug;
});</code> <button class="copy-button">copy</button></pre>
<h4><code>debuglog().enabled</code><span><a class="mark" href="#all_util_debuglogenabled" id="all_util_debuglogenabled">#</a></span><a aria-hidden="true" class="legacy" id="util_debuglog_enabled"></a></h4>
<div class="api_metadata">
<span>Added in: v14.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>The <code>util.debuglog().enabled</code> getter is used to create a test that can be used
in conditionals based on the existence of the <code>NODE_DEBUG</code> environment variable.
If the <code>section</code> name appears within the value of that environment variable,
then the returned value will be <code>true</code>. If not, then the returned value will be
<code>false</code>.</p>
<pre><code class="language-js"><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">const</span> enabled = util.<span class="hljs-title function_">debuglog</span>(<span class="hljs-string">'foo'</span>).<span class="hljs-property">enabled</span>;
<span class="hljs-keyword">if</span> (enabled) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'hello from foo [%d]'</span>, <span class="hljs-number">123</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>If this program is run with <code>NODE_DEBUG=foo</code> in the environment, then it will
output something like:</p>
<pre><code class="language-console">hello from foo [123]</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.debug(section)</code><span><a class="mark" href="#all_util_utildebugsection" id="all_util_utildebugsection">#</a></span><a aria-hidden="true" class="legacy" id="util_util_debug_section"></a></h3>
<div class="api_metadata">
<span>Added in: v14.9.0</span>
</div>
<p>Alias for <code>util.debuglog</code>. Usage allows for readability of that doesn't imply
logging when only using <code>util.debuglog().enabled</code>.</p>
</section><section><h3><code>util.deprecate(fn, msg[, code])</code><span><a class="mark" href="#all_util_utildeprecatefn-msg-code" id="all_util_utildeprecatefn-msg-code">#</a></span><a aria-hidden="true" class="legacy" id="util_util_deprecate_fn_msg_code"></a></h3>
<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>Deprecation warnings are only emitted once for each code.</p></td></tr>
<tr><td>v0.8.0</td>
<td><p><span>Added in: v0.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function that is being deprecated.</li>
<li><code>msg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A warning message to display when the deprecated function is
invoked.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A deprecation code. See the <a href="#all_deprecations_list-of-deprecated-apis">list of deprecated APIs</a> for a
list of codes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The deprecated function wrapped to emit a warning.</li>
</ul>
<p>The <code>util.deprecate()</code> method wraps <code>fn</code> (which may be a function or class) in
such a way that it is marked as deprecated.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-built_in">exports</span>.<span class="hljs-property">obsoleteFunction</span> = util.<span class="hljs-title function_">deprecate</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// Do something here.</span>
}, <span class="hljs-string">'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'</span>);</code> <button class="copy-button">copy</button></pre>
<p>When called, <code>util.deprecate()</code> will return a function that will emit a
<code>DeprecationWarning</code> using the <a href="#all_process_event-warning"><code>'warning'</code></a> event. The warning will
be emitted and printed to <code>stderr</code> the first time the returned function is
called. After the warning is emitted, the wrapped function is called without
emitting a warning.</p>
<p>If the same optional <code>code</code> is supplied in multiple calls to <code>util.deprecate()</code>,
the warning will be emitted only once for that <code>code</code>.</p>
<pre><code class="language-js"><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">const</span> fn1 = util.<span class="hljs-title function_">deprecate</span>(someFunction, someMessage, <span class="hljs-string">'DEP0001'</span>);
<span class="hljs-keyword">const</span> fn2 = util.<span class="hljs-title function_">deprecate</span>(someOtherFunction, someOtherMessage, <span class="hljs-string">'DEP0001'</span>);
<span class="hljs-title function_">fn1</span>(); <span class="hljs-comment">// Emits a deprecation warning with code DEP0001</span>
<span class="hljs-title function_">fn2</span>(); <span class="hljs-comment">// Does not emit a deprecation warning because it has the same code</span></code> <button class="copy-button">copy</button></pre>
<p>If either the <code>--no-deprecation</code> or <code>--no-warnings</code> command-line flags are
used, or if the <code>process.noDeprecation</code> property is set to <code>true</code> <em>prior</em> to
the first deprecation warning, the <code>util.deprecate()</code> method does nothing.</p>
<p>If the <code>--trace-deprecation</code> or <code>--trace-warnings</code> command-line flags are set,
or the <code>process.traceDeprecation</code> property is set to <code>true</code>, a warning and a
stack trace are printed to <code>stderr</code> the first time the deprecated function is
called.</p>
<p>If the <code>--throw-deprecation</code> command-line flag is set, or the
<code>process.throwDeprecation</code> property is set to <code>true</code>, then an exception will be
thrown when the deprecated function is called.</p>
<p>The <code>--throw-deprecation</code> command-line flag and <code>process.throwDeprecation</code>
property take precedence over <code>--trace-deprecation</code> and
<code>process.traceDeprecation</code>.</p>
</section><section><h3><code>util.format(format[, ...args])</code><span><a class="mark" href="#all_util_utilformatformat-args" id="all_util_utilformatformat-args">#</a></span><a aria-hidden="true" class="legacy" id="util_util_format_format_args"></a></h3>
<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>The <code>%c</code> specifier is ignored now.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>The <code>format</code> argument is now only taken as such if it actually contains format specifiers.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>If the <code>format</code> argument is not a format string, the output string's formatting is no longer dependent on the type of the first argument. This change removes previously present quotes from strings that were being output when the first argument was not a string.</p></td></tr>
<tr><td>v11.4.0</td>
<td><p>The <code>%d</code>, <code>%f</code>, and <code>%i</code> specifiers now support Symbols properly.</p></td></tr>
<tr><td>v11.4.0</td>
<td><p>The <code>%o</code> specifier's <code>depth</code> has default depth of 4 again.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>The <code>%o</code> specifier's <code>depth</code> option will now fall back to the default depth.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p>The <code>%d</code> and <code>%i</code> specifiers now support BigInt.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p>The <code>%o</code> and <code>%O</code> specifiers are supported now.</p></td></tr>
<tr><td>v0.5.3</td>
<td><p><span>Added in: v0.5.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A <code>printf</code>-like format string.</li>
</ul>
<p>The <code>util.format()</code> method returns a formatted string using the first argument
as a <code>printf</code>-like format string which can contain zero or more format
specifiers. Each specifier is replaced with the converted value from the
corresponding argument. Supported specifiers are:</p>
<ul>
<li><code>%s</code>: <code>String</code> will be used to convert all values except <code>BigInt</code>, <code>Object</code>
and <code>-0</code>. <code>BigInt</code> values will be represented with an <code>n</code> and Objects that
have no user defined <code>toString</code> function are inspected using <code>util.inspect()</code>
with options <code>{ depth: 0, colors: false, compact: 3 }</code>.</li>
<li><code>%d</code>: <code>Number</code> will be used to convert all values except <code>BigInt</code> and
<code>Symbol</code>.</li>
<li><code>%i</code>: <code>parseInt(value, 10)</code> is used for all values except <code>BigInt</code> and
<code>Symbol</code>.</li>
<li><code>%f</code>: <code>parseFloat(value)</code> is used for all values expect <code>Symbol</code>.</li>
<li><code>%j</code>: JSON. Replaced with the string <code>'[Circular]'</code> if the argument contains
circular references.</li>
<li><code>%o</code>: <code>Object</code>. A string representation of an object with generic JavaScript
object formatting. Similar to <code>util.inspect()</code> with options
<code>{ showHidden: true, showProxy: true }</code>. This will show the full object
including non-enumerable properties and proxies.</li>
<li><code>%O</code>: <code>Object</code>. A string representation of an object with generic JavaScript
object formatting. Similar to <code>util.inspect()</code> without options. This will show
the full object not including non-enumerable properties and proxies.</li>
<li><code>%c</code>: <code>CSS</code>. This specifier is ignored and will skip any CSS passed in.</li>
<li><code>%%</code>: single percent sign (<code>'%'</code>). This does not consume an argument.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The formatted string</li>
</ul>
<p>If a specifier does not have a corresponding argument, it is not replaced:</p>
<pre><code class="language-js">util.<span class="hljs-title function_">format</span>(<span class="hljs-string">'%s:%s'</span>, <span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Returns: 'foo:%s'</span></code> <button class="copy-button">copy</button></pre>
<p>Values that are not part of the format string are formatted using
<code>util.inspect()</code> if their type is not <code>string</code>.</p>
<p>If there are more arguments passed to the <code>util.format()</code> method than the
number of specifiers, the extra arguments are concatenated to the returned
string, separated by spaces:</p>
<pre><code class="language-js">util.<span class="hljs-title function_">format</span>(<span class="hljs-string">'%s:%s'</span>, <span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>, <span class="hljs-string">'baz'</span>);
<span class="hljs-comment">// Returns: 'foo:bar baz'</span></code> <button class="copy-button">copy</button></pre>
<p>If the first argument does not contain a valid format specifier, <code>util.format()</code>
returns a string that is the concatenation of all arguments separated by spaces:</p>
<pre><code class="language-js">util.<span class="hljs-title function_">format</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
<span class="hljs-comment">// Returns: '1 2 3'</span></code> <button class="copy-button">copy</button></pre>
<p>If only one argument is passed to <code>util.format()</code>, it is returned as it is
without any formatting:</p>
<pre><code class="language-js">util.<span class="hljs-title function_">format</span>(<span class="hljs-string">'%% %s'</span>);
<span class="hljs-comment">// Returns: '%% %s'</span></code> <button class="copy-button">copy</button></pre>
<p><code>util.format()</code> is a synchronous method that is intended as a debugging tool.
Some input values can have a significant performance overhead that can block the
event loop. Use this function with care and never in a hot code path.</p>
</section><section><h3><code>util.formatWithOptions(inspectOptions, format[, ...args])</code><span><a class="mark" href="#all_util_utilformatwithoptionsinspectoptions-format-args" id="all_util_utilformatwithoptionsinspectoptions-format-args">#</a></span><a aria-hidden="true" class="legacy" id="util_util_formatwithoptions_inspectoptions_format_args"></a></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>inspectOptions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>This function is identical to <a href="#all_util_utilformatformat-args"><code>util.format()</code></a>, except in that it takes
an <code>inspectOptions</code> argument which specifies options that are passed along to
<a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a>.</p>
<pre><code class="language-js">util.<span class="hljs-title function_">formatWithOptions</span>({ <span class="hljs-attr">colors</span>: <span class="hljs-literal">true</span> }, <span class="hljs-string">'See object %O'</span>, { <span class="hljs-attr">foo</span>: <span class="hljs-number">42</span> });
<span class="hljs-comment">// Returns 'See object { foo: 42 }', where `42` is colored as a number</span>
<span class="hljs-comment">// when printed to a terminal.</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.getSystemErrorName(err)</code><span><a class="mark" href="#all_util_utilgetsystemerrornameerr" id="all_util_utilgetsystemerrornameerr">#</a></span><a aria-hidden="true" class="legacy" id="util_util_getsystemerrorname_err"></a></h3>
<div class="api_metadata">
<span>Added in: v9.7.0</span>
</div>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the string name for a numeric error code that comes from a Node.js API.
The mapping between error codes and error names is platform-dependent.
See <a href="#all_errors_common-system-errors">Common System Errors</a> for the names of common errors.</p>
<pre><code class="language-js">fs.<span class="hljs-title function_">access</span>(<span class="hljs-string">'file/that/does/not/exist'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">const</span> name = util.<span class="hljs-title function_">getSystemErrorName</span>(err.<span class="hljs-property">errno</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(name); <span class="hljs-comment">// ENOENT</span>
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.getSystemErrorMap()</code><span><a class="mark" href="#all_util_utilgetsystemerrormap" id="all_util_utilgetsystemerrormap">#</a></span><a aria-hidden="true" class="legacy" id="util_util_getsystemerrormap"></a></h3>
<div class="api_metadata">
<span>Added in: v16.0.0, v14.17.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type"><Map></a></li>
</ul>
<p>Returns a Map of all system error codes available from the Node.js API.
The mapping between error codes and error names is platform-dependent.
See <a href="#all_errors_common-system-errors">Common System Errors</a> for the names of common errors.</p>
<pre><code class="language-js">fs.<span class="hljs-title function_">access</span>(<span class="hljs-string">'file/that/does/not/exist'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">const</span> errorMap = util.<span class="hljs-title function_">getSystemErrorMap</span>();
<span class="hljs-keyword">const</span> name = errorMap.<span class="hljs-title function_">get</span>(err.<span class="hljs-property">errno</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(name); <span class="hljs-comment">// ENOENT</span>
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.inherits(constructor, superConstructor)</code><span><a class="mark" href="#all_util_utilinheritsconstructor-superconstructor" id="all_util_utilinheritsconstructor-superconstructor">#</a></span><a aria-hidden="true" class="legacy" id="util_util_inherits_constructor_superconstructor"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>constructor</code> parameter can refer to an ES6 class now.</p></td></tr>
<tr><td>v0.3.0</td>
<td><p><span>Added in: v0.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use ES2015 class syntax and <code>extends</code> keyword instead.</div><p></p>
<ul>
<li><code>constructor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li><code>superConstructor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>Usage of <code>util.inherits()</code> is discouraged. Please use the ES6 <code>class</code> and
<code>extends</code> keywords to get language level inheritance support. Also note
that the two styles are <a href="https://github.com/nodejs/node/issues/4179">semantically incompatible</a>.</p>
<p>Inherit the prototype methods from one <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">constructor</a> into another. The
prototype of <code>constructor</code> will be set to a new object created from
<code>superConstructor</code>.</p>
<p>This mainly adds some input validation on top of
<code>Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)</code>.
As an additional convenience, <code>superConstructor</code> will be accessible
through the <code>constructor.super_</code> property.</p>
<pre><code class="language-js"><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">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyStream</span>(<span class="hljs-params"></span>) {
<span class="hljs-title class_">EventEmitter</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>);
}
util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyStream</span>, <span class="hljs-title class_">EventEmitter</span>);
<span class="hljs-title class_">MyStream</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">write</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'data'</span>, data);
};
<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyStream</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stream <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">EventEmitter</span>); <span class="hljs-comment">// true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">MyStream</span>.<span class="hljs-property">super_</span> === <span class="hljs-title class_">EventEmitter</span>); <span class="hljs-comment">// true</span>
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received data: "<span class="hljs-subst">${data}</span>"`</span>);
});
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'It works!'</span>); <span class="hljs-comment">// Received data: "It works!"</span></code> <button class="copy-button">copy</button></pre>
<p>ES6 example using <code>class</code> and <code>extends</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyStream</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
<span class="hljs-title function_">write</span>(<span class="hljs-params">data</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'data'</span>, data);
}
}
<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyStream</span>();
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received data: "<span class="hljs-subst">${data}</span>"`</span>);
});
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'With ES6'</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.inspect(object[, options])</code><span><a class="mark" href="#all_util_utilinspectobject-options" id="all_util_utilinspectobject-options">#</a></span><a aria-hidden="true" class="legacy" id="util_util_inspect_object_options"></a></h3>
</section><section><h3><code>util.inspect(object[, showHidden[, depth[, colors]]])</code><span><a class="mark" href="#all_util_utilinspectobject-showhidden-depth-colors" id="all_util_utilinspectobject-showhidden-depth-colors">#</a></span><a aria-hidden="true" class="legacy" id="util_util_inspect_object_showhidden_depth_colors"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.18.0</td>
<td><p>add support for <code>maxArrayLength</code> when inspecting <code>Set</code> and <code>Map</code>.</p></td></tr>
<tr><td>v17.3.0, v16.14.0</td>
<td><p>The <code>numericSeparator</code> option is supported now.</p></td></tr>
<tr><td>v13.0.0</td>
<td><p>Circular references now include a marker to the reference.</p></td></tr>
<tr><td>v14.6.0, v12.19.0</td>
<td><p>If <code>object</code> is from a different <code>vm.Context</code> now, a custom inspection function on it will not receive context-specific arguments anymore.</p></td></tr>
<tr><td>v13.13.0, v12.17.0</td>
<td><p>The <code>maxStringLength</code> option is supported now.</p></td></tr>
<tr><td>v13.5.0, v12.16.0</td>
<td><p>User defined prototype properties are inspected in case <code>showHidden</code> is <code>true</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>The <code>compact</code> options default is changed to <code>3</code> and the <code>breakLength</code> options default is changed to <code>80</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Internal properties no longer appear in the context argument of a custom inspection function.</p></td></tr>
<tr><td>v11.11.0</td>
<td><p>The <code>compact</code> option accepts numbers for a new output mode.</p></td></tr>
<tr><td>v11.7.0</td>
<td><p>ArrayBuffers now also show their binary contents.</p></td></tr>
<tr><td>v11.5.0</td>
<td><p>The <code>getters</code> option is supported now.</p></td></tr>
<tr><td>v11.4.0</td>
<td><p>The <code>depth</code> default changed back to <code>2</code>.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>The <code>depth</code> default changed to <code>20</code>.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>The inspection output is now limited to about 128 MiB. Data above that size will not be fully inspected.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p>The <code>sorted</code> option is supported now.</p></td></tr>
<tr><td>v10.6.0</td>
<td><p>Inspecting linked lists and similar objects is now possible up to the maximum call stack size.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>WeakMap</code> and <code>WeakSet</code> entries can now be inspected as well.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>The <code>compact</code> option is supported now.</p></td></tr>
<tr><td>v6.6.0</td>
<td><p>Custom inspection functions can now return <code>this</code>.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakLength</code> option is supported now.</p></td></tr>
<tr><td>v6.1.0</td>
<td><p>The <code>maxArrayLength</code> option is supported now; in particular, long arrays are truncated by default.</p></td></tr>
<tr><td>v6.1.0</td>
<td><p>The <code>showProxy</code> option is supported now.</p></td></tr>
<tr><td>v0.3.0</td>
<td><p><span>Added in: v0.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any JavaScript primitive or <code>Object</code>.</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>showHidden</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, <code>object</code>'s non-enumerable symbols and
properties are included in the formatted result. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> entries are also included as well as user defined prototype
properties (excluding method properties). <strong>Default:</strong> <code>false</code>.</li>
<li><code>depth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the number of times to recurse while formatting
<code>object</code>. This is useful for inspecting large objects. To recurse up to
the maximum call stack size pass <code>Infinity</code> or <code>null</code>.
<strong>Default:</strong> <code>2</code>.</li>
<li><code>colors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the output is styled with ANSI color
codes. Colors are customizable. See <a href="#all_util_customizing-utilinspect-colors">Customizing <code>util.inspect</code> colors</a>.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>customInspect</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>false</code>,
<code>[util.inspect.custom](depth, opts, inspect)</code> functions are not invoked.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>showProxy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, <code>Proxy</code> inspection includes
the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#Terminology"><code>target</code> and <code>handler</code></a> objects. <strong>Default:</strong> <code>false</code>.</li>
<li><code>maxArrayLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the maximum number of <code>Array</code>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a>,
and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> elements to include when formatting.
Set to <code>null</code> or <code>Infinity</code> to show all elements. Set to <code>0</code> or
negative to show no elements. <strong>Default:</strong> <code>100</code>.</li>
<li><code>maxStringLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the maximum number of characters to
include when formatting. Set to <code>null</code> or <code>Infinity</code> to show all elements.
Set to <code>0</code> or negative to show no characters. <strong>Default:</strong> <code>10000</code>.</li>
<li><code>breakLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The length at which input values are split across
multiple lines. Set to <code>Infinity</code> to format the input as a single line
(in combination with <code>compact</code> set to <code>true</code> or any number >= <code>1</code>).
<strong>Default:</strong> <code>80</code>.</li>
<li><code>compact</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#Number_type" class="type"><integer></a> Setting this to <code>false</code> causes each object key
to be displayed on a new line. It will break on new lines in text that is
longer than <code>breakLength</code>. If set to a number, the most <code>n</code> inner elements
are united on a single line as long as all properties fit into
<code>breakLength</code>. Short array elements are also grouped together. For more
information, see the example below. <strong>Default:</strong> <code>3</code>.</li>
<li><code>sorted</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/Reference/Global_Objects/Function" class="type"><Function></a> If set to <code>true</code> or a function, all properties
of an object, and <code>Set</code> and <code>Map</code> entries are sorted in the resulting
string. If set to <code>true</code> the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">default sort</a> is used. If set to a function,
it is used as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters">compare function</a>.</li>
<li><code>getters</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#String_type" class="type"><string></a> If set to <code>true</code>, getters are inspected. If set
to <code>'get'</code>, only getters without a corresponding setter are inspected. If
set to <code>'set'</code>, only getters with a corresponding setter are inspected.
This might cause side effects depending on the getter function.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>numericSeparator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>true</code>, an underscore is used to
separate every three digits in all bigints and numbers.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The representation of <code>object</code>.</li>
</ul>
<p>The <code>util.inspect()</code> method returns a string representation of <code>object</code> that is
intended for debugging. The output of <code>util.inspect</code> may change at any time
and should not be depended upon programmatically. Additional <code>options</code> may be
passed that alter the result.
<code>util.inspect()</code> will use the constructor's name and/or <code>@@toStringTag</code> to make
an identifiable tag for an inspected value.</p>
<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
get [<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">toStringTag</span>]() {
<span class="hljs-keyword">return</span> <span class="hljs-string">'bar'</span>;
}
}
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Bar</span> {}
<span class="hljs-keyword">const</span> baz = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">create</span>(<span class="hljs-literal">null</span>, { [<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">toStringTag</span>]: { <span class="hljs-attr">value</span>: <span class="hljs-string">'foo'</span> } });
util.<span class="hljs-title function_">inspect</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>()); <span class="hljs-comment">// 'Foo [bar] {}'</span>
util.<span class="hljs-title function_">inspect</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Bar</span>()); <span class="hljs-comment">// 'Bar {}'</span>
util.<span class="hljs-title function_">inspect</span>(baz); <span class="hljs-comment">// '[foo] {}'</span></code> <button class="copy-button">copy</button></pre>
<p>Circular references point to their anchor by using a reference index:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { inspect } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> obj = {};
obj.<span class="hljs-property">a</span> = [obj];
obj.<span class="hljs-property">b</span> = {};
obj.<span class="hljs-property">b</span>.<span class="hljs-property">inner</span> = obj.<span class="hljs-property">b</span>;
obj.<span class="hljs-property">b</span>.<span class="hljs-property">obj</span> = obj;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(obj));
<span class="hljs-comment">// <ref *1> {</span>
<span class="hljs-comment">// a: [ [Circular *1] ],</span>
<span class="hljs-comment">// b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }</span>
<span class="hljs-comment">// }</span></code> <button class="copy-button">copy</button></pre>
<p>The following example inspects all properties of the <code>util</code> object:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-title function_">inspect</span>(util, { <span class="hljs-attr">showHidden</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">depth</span>: <span class="hljs-literal">null</span> }));</code> <button class="copy-button">copy</button></pre>
<p>The following example highlights the effect of the <code>compact</code> option:</p>
<pre><code class="language-js"><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">const</span> o = {
<span class="hljs-attr">a</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, [[
<span class="hljs-string">'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do '</span> +
<span class="hljs-string">'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.'</span>,
<span class="hljs-string">'test'</span>,
<span class="hljs-string">'foo'</span>]], <span class="hljs-number">4</span>],
<span class="hljs-attr">b</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>([[<span class="hljs-string">'za'</span>, <span class="hljs-number">1</span>], [<span class="hljs-string">'zb'</span>, <span class="hljs-string">'test'</span>]]),
};
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-title function_">inspect</span>(o, { <span class="hljs-attr">compact</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">depth</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">breakLength</span>: <span class="hljs-number">80</span> }));
<span class="hljs-comment">// { a:</span>
<span class="hljs-comment">// [ 1,</span>
<span class="hljs-comment">// 2,</span>
<span class="hljs-comment">// [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line</span>
<span class="hljs-comment">// 'test',</span>
<span class="hljs-comment">// 'foo' ] ],</span>
<span class="hljs-comment">// 4 ],</span>
<span class="hljs-comment">// b: Map(2) { 'za' => 1, 'zb' => 'test' } }</span>
<span class="hljs-comment">// Setting `compact` to false or an integer creates more reader friendly output.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-title function_">inspect</span>(o, { <span class="hljs-attr">compact</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">depth</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">breakLength</span>: <span class="hljs-number">80</span> }));
<span class="hljs-comment">// {</span>
<span class="hljs-comment">// a: [</span>
<span class="hljs-comment">// 1,</span>
<span class="hljs-comment">// 2,</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// 'Lorem ipsum dolor sit amet,\n' +</span>
<span class="hljs-comment">// 'consectetur adipiscing elit, sed do eiusmod \n' +</span>
<span class="hljs-comment">// 'tempor incididunt ut labore et dolore magna aliqua.',</span>
<span class="hljs-comment">// 'test',</span>
<span class="hljs-comment">// 'foo'</span>
<span class="hljs-comment">// ]</span>
<span class="hljs-comment">// ],</span>
<span class="hljs-comment">// 4</span>
<span class="hljs-comment">// ],</span>
<span class="hljs-comment">// b: Map(2) {</span>
<span class="hljs-comment">// 'za' => 1,</span>
<span class="hljs-comment">// 'zb' => 'test'</span>
<span class="hljs-comment">// }</span>
<span class="hljs-comment">// }</span>
<span class="hljs-comment">// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a</span>
<span class="hljs-comment">// single line.</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>showHidden</code> option allows <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> entries to be
inspected. If there are more entries than <code>maxArrayLength</code>, there is no
guarantee which entries are displayed. That means retrieving the same
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> entries twice may result in different output. Furthermore, entries
with no remaining strong references may be garbage collected at any time.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { inspect } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> };
<span class="hljs-keyword">const</span> obj2 = { <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">const</span> weakSet = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakSet</span>([obj, obj2]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(weakSet, { <span class="hljs-attr">showHidden</span>: <span class="hljs-literal">true</span> }));
<span class="hljs-comment">// WeakSet { { a: 1 }, { b: 2 } }</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>sorted</code> option ensures that an object's property insertion order does not
impact the result of <code>util.inspect()</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { inspect } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> o1 = {
<span class="hljs-attr">b</span>: [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>],
<span class="hljs-attr">a</span>: <span class="hljs-string">'`a` comes before `b`'</span>,
<span class="hljs-attr">c</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>([<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>]),
};
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(o1, { <span class="hljs-attr">sorted</span>: <span class="hljs-literal">true</span> }));
<span class="hljs-comment">// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(o1, { <span class="hljs-attr">sorted</span>: <span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> b.<span class="hljs-title function_">localeCompare</span>(a) }));
<span class="hljs-comment">// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }</span>
<span class="hljs-keyword">const</span> o2 = {
<span class="hljs-attr">c</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>([<span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>]),
<span class="hljs-attr">a</span>: <span class="hljs-string">'`a` comes before `b`'</span>,
<span class="hljs-attr">b</span>: [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>],
};
assert.<span class="hljs-property">strict</span>.<span class="hljs-title function_">equal</span>(
<span class="hljs-title function_">inspect</span>(o1, { <span class="hljs-attr">sorted</span>: <span class="hljs-literal">true</span> }),
<span class="hljs-title function_">inspect</span>(o2, { <span class="hljs-attr">sorted</span>: <span class="hljs-literal">true</span> }),
);</code> <button class="copy-button">copy</button></pre>
<p>The <code>numericSeparator</code> option adds an underscore every three digits to all
numbers.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { inspect } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> thousand = <span class="hljs-number">1_000</span>;
<span class="hljs-keyword">const</span> million = <span class="hljs-number">1_000_000</span>;
<span class="hljs-keyword">const</span> bigNumber = <span class="hljs-number">123_456_789n</span>;
<span class="hljs-keyword">const</span> bigDecimal = <span class="hljs-number">1_234.123_45</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(thousand, { <span class="hljs-attr">numericSeparator</span>: <span class="hljs-literal">true</span> }));
<span class="hljs-comment">// 1_000</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(million, { <span class="hljs-attr">numericSeparator</span>: <span class="hljs-literal">true</span> }));
<span class="hljs-comment">// 1_000_000</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(bigNumber, { <span class="hljs-attr">numericSeparator</span>: <span class="hljs-literal">true</span> }));
<span class="hljs-comment">// 123_456_789n</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(bigDecimal, { <span class="hljs-attr">numericSeparator</span>: <span class="hljs-literal">true</span> }));
<span class="hljs-comment">// 1_234.123_45</span></code> <button class="copy-button">copy</button></pre>
<p><code>util.inspect()</code> is a synchronous method intended for debugging. Its maximum
output length is approximately 128 MiB. Inputs that result in longer output will
be truncated.</p>
<h4>Customizing <code>util.inspect</code> colors<span><a class="mark" href="#all_util_customizing-utilinspect-colors" id="all_util_customizing-utilinspect-colors">#</a></span><a aria-hidden="true" class="legacy" id="util_customizing_util_inspect_colors"></a></h4>
<p>Color output (if enabled) of <code>util.inspect</code> is customizable globally
via the <code>util.inspect.styles</code> and <code>util.inspect.colors</code> properties.</p>
<p><code>util.inspect.styles</code> is a map associating a style name to a color from
<code>util.inspect.colors</code>.</p>
<p>The default styles and associated colors are:</p>
<ul>
<li><code>bigint</code>: <code>yellow</code></li>
<li><code>boolean</code>: <code>yellow</code></li>
<li><code>date</code>: <code>magenta</code></li>
<li><code>module</code>: <code>underline</code></li>
<li><code>name</code>: (no styling)</li>
<li><code>null</code>: <code>bold</code></li>
<li><code>number</code>: <code>yellow</code></li>
<li><code>regexp</code>: <code>red</code></li>
<li><code>special</code>: <code>cyan</code> (e.g., <code>Proxies</code>)</li>
<li><code>string</code>: <code>green</code></li>
<li><code>symbol</code>: <code>green</code></li>
<li><code>undefined</code>: <code>grey</code></li>
</ul>
<p>Color styling uses ANSI control codes that may not be supported on all
terminals. To verify color support use <a href="#all_tty_writestreamhascolorscount-env"><code>tty.hasColors()</code></a>.</p>
<p>Predefined control codes are listed below (grouped as "Modifiers", "Foreground
colors", and "Background colors").</p>
<h5>Modifiers<span><a class="mark" href="#all_util_modifiers" id="all_util_modifiers">#</a></span><a aria-hidden="true" class="legacy" id="util_modifiers"></a></h5>
<p>Modifier support varies throughout different terminals. They will mostly be
ignored, if not supported.</p>
<ul>
<li><code>reset</code> - Resets all (color) modifiers to their defaults</li>
<li><strong>bold</strong> - Make text bold</li>
<li><em>italic</em> - Make text italic</li>
<li><span style="border-bottom: 1px;">underline</span> - Make text underlined</li>
<li><del>strikethrough</del> - Puts a horizontal line through the center of the text
(Alias: <code>strikeThrough</code>, <code>crossedout</code>, <code>crossedOut</code>)</li>
<li><code>hidden</code> - Prints the text, but makes it invisible (Alias: conceal)</li>
<li><span style="opacity: 0.5;">dim</span> - Decreased color intensity (Alias:
<code>faint</code>)</li>
<li><span style="border-top: 1px">overlined</span> - Make text overlined</li>
<li>blink - Hides and shows the text in an interval</li>
<li><span style="filter: invert(100%)">inverse</span> - Swap foreground and
background colors (Alias: <code>swapcolors</code>, <code>swapColors</code>)</li>
<li><span style="border-bottom: 1px double;">doubleunderline</span> - Make text
double underlined (Alias: <code>doubleUnderline</code>)</li>
<li><span style="border: 1px">framed</span> - Draw a frame around the text</li>
</ul>
<h5>Foreground colors<span><a class="mark" href="#all_util_foreground-colors" id="all_util_foreground-colors">#</a></span><a aria-hidden="true" class="legacy" id="util_foreground_colors"></a></h5>
<ul>
<li><code>black</code></li>
<li><code>red</code></li>
<li><code>green</code></li>
<li><code>yellow</code></li>
<li><code>blue</code></li>
<li><code>magenta</code></li>
<li><code>cyan</code></li>
<li><code>white</code></li>
<li><code>gray</code> (alias: <code>grey</code>, <code>blackBright</code>)</li>
<li><code>redBright</code></li>
<li><code>greenBright</code></li>
<li><code>yellowBright</code></li>
<li><code>blueBright</code></li>
<li><code>magentaBright</code></li>
<li><code>cyanBright</code></li>
<li><code>whiteBright</code></li>
</ul>
<h5>Background colors<span><a class="mark" href="#all_util_background-colors" id="all_util_background-colors">#</a></span><a aria-hidden="true" class="legacy" id="util_background_colors"></a></h5>
<ul>
<li><code>bgBlack</code></li>
<li><code>bgRed</code></li>
<li><code>bgGreen</code></li>
<li><code>bgYellow</code></li>
<li><code>bgBlue</code></li>
<li><code>bgMagenta</code></li>
<li><code>bgCyan</code></li>
<li><code>bgWhite</code></li>
<li><code>bgGray</code> (alias: <code>bgGrey</code>, <code>bgBlackBright</code>)</li>
<li><code>bgRedBright</code></li>
<li><code>bgGreenBright</code></li>
<li><code>bgYellowBright</code></li>
<li><code>bgBlueBright</code></li>
<li><code>bgMagentaBright</code></li>
<li><code>bgCyanBright</code></li>
<li><code>bgWhiteBright</code></li>
</ul>
<h4>Custom inspection functions on objects<span><a class="mark" href="#all_util_custom-inspection-functions-on-objects" id="all_util_custom-inspection-functions-on-objects">#</a></span><a aria-hidden="true" class="legacy" id="util_custom_inspection_functions_on_objects"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.3.0, v16.14.0</td>
<td><p>The inspect argument is added for more interoperability.</p></td></tr>
<tr><td>v0.1.97</td>
<td><p><span>Added in: v0.1.97</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Objects may also define their own
<a href="#all_util_utilinspectcustom"><code>[util.inspect.custom](depth, opts, inspect)</code></a> function,
which <code>util.inspect()</code> will invoke and use the result of when inspecting
the object.</p>
<pre><code class="language-js"><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">class</span> <span class="hljs-title class_">Box</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">value</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = value;
}
[util.<span class="hljs-property">inspect</span>.<span class="hljs-property">custom</span>](depth, options, inspect) {
<span class="hljs-keyword">if</span> (depth < <span class="hljs-number">0</span>) {
<span class="hljs-keyword">return</span> options.<span class="hljs-title function_">stylize</span>(<span class="hljs-string">'[Box]'</span>, <span class="hljs-string">'special'</span>);
}
<span class="hljs-keyword">const</span> newOptions = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">assign</span>({}, options, {
<span class="hljs-attr">depth</span>: options.<span class="hljs-property">depth</span> === <span class="hljs-literal">null</span> ? <span class="hljs-literal">null</span> : options.<span class="hljs-property">depth</span> - <span class="hljs-number">1</span>,
});
<span class="hljs-comment">// Five space padding because that's the size of "Box< ".</span>
<span class="hljs-keyword">const</span> padding = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(<span class="hljs-number">5</span>);
<span class="hljs-keyword">const</span> inner = <span class="hljs-title function_">inspect</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span>, newOptions)
.<span class="hljs-title function_">replace</span>(<span class="hljs-regexp">/\n/g</span>, <span class="hljs-string">`\n<span class="hljs-subst">${padding}</span>`</span>);
<span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${options.stylize(<span class="hljs-string">'Box'</span>, <span class="hljs-string">'special'</span>)}</span>< <span class="hljs-subst">${inner}</span> >`</span>;
}
}
<span class="hljs-keyword">const</span> box = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Box</span>(<span class="hljs-literal">true</span>);
util.<span class="hljs-title function_">inspect</span>(box);
<span class="hljs-comment">// Returns: "Box< true >"</span></code> <button class="copy-button">copy</button></pre>
<p>Custom <code>[util.inspect.custom](depth, opts, inspect)</code> functions typically return
a string but may return a value of any type that will be formatted accordingly
by <code>util.inspect()</code>.</p>
<pre><code class="language-js"><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">const</span> obj = { <span class="hljs-attr">foo</span>: <span class="hljs-string">'this will not show up in the inspect() output'</span> };
obj[util.<span class="hljs-property">inspect</span>.<span class="hljs-property">custom</span>] = <span class="hljs-function">(<span class="hljs-params">depth</span>) =></span> {
<span class="hljs-keyword">return</span> { <span class="hljs-attr">bar</span>: <span class="hljs-string">'baz'</span> };
};
util.<span class="hljs-title function_">inspect</span>(obj);
<span class="hljs-comment">// Returns: "{ bar: 'baz' }"</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.inspect.custom</code><span><a class="mark" href="#all_util_utilinspectcustom" id="all_util_utilinspectcustom">#</a></span><a aria-hidden="true" class="legacy" id="util_util_inspect_custom"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.12.0</td>
<td><p>This is now defined as a shared symbol.</p></td></tr>
<tr><td>v6.6.0</td>
<td><p><span>Added in: v6.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> that can be used to declare custom inspect functions.</li>
</ul>
<p>In addition to being accessible through <code>util.inspect.custom</code>, this
symbol is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for">registered globally</a> and can be
accessed in any environment as <code>Symbol.for('nodejs.util.inspect.custom')</code>.</p>
<p>Using this allows code to be written in a portable fashion, so that the custom
inspect function is used in an Node.js environment and ignored in the browser.
The <code>util.inspect()</code> function itself is passed as third argument to the custom
inspect function to allow further portability.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> customInspectSymbol = <span class="hljs-title class_">Symbol</span>.<span class="hljs-title function_">for</span>(<span class="hljs-string">'nodejs.util.inspect.custom'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Password</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">value</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = value;
}
<span class="hljs-title function_">toString</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">return</span> <span class="hljs-string">'xxxxxxxx'</span>;
}
[customInspectSymbol](depth, inspectOptions, inspect) {
<span class="hljs-keyword">return</span> <span class="hljs-string">`Password <<span class="hljs-subst">${<span class="hljs-variable language_">this</span>.toString()}</span>>`</span>;
}
}
<span class="hljs-keyword">const</span> password = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Password</span>(<span class="hljs-string">'r0sebud'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(password);
<span class="hljs-comment">// Prints Password <xxxxxxxx></span></code> <button class="copy-button">copy</button></pre>
<p>See <a href="#all_util_custom-inspection-functions-on-objects">Custom inspection functions on Objects</a> for more details.</p>
<h4><code>util.inspect.defaultOptions</code><span><a class="mark" href="#all_util_utilinspectdefaultoptions" id="all_util_utilinspectdefaultoptions">#</a></span><a aria-hidden="true" class="legacy" id="util_util_inspect_defaultoptions"></a></h4>
<div class="api_metadata">
<span>Added in: v6.4.0</span>
</div>
<p>The <code>defaultOptions</code> value allows customization of the default options used by
<code>util.inspect</code>. This is useful for functions like <code>console.log</code> or
<code>util.format</code> which implicitly call into <code>util.inspect</code>. It shall be set to an
object containing one or more valid <a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> options. Setting
option properties directly is also supported.</p>
<pre><code class="language-js"><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">const</span> arr = <span class="hljs-title class_">Array</span>(<span class="hljs-number">101</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arr); <span class="hljs-comment">// Logs the truncated array</span>
util.<span class="hljs-property">inspect</span>.<span class="hljs-property">defaultOptions</span>.<span class="hljs-property">maxArrayLength</span> = <span class="hljs-literal">null</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arr); <span class="hljs-comment">// logs the full array</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.isDeepStrictEqual(val1, val2)</code><span><a class="mark" href="#all_util_utilisdeepstrictequalval1-val2" id="all_util_utilisdeepstrictequalval1-val2">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isdeepstrictequal_val1_val2"></a></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span>
</div>
<ul>
<li><code>val1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>val2</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if there is deep strict equality between <code>val1</code> and <code>val2</code>.
Otherwise, returns <code>false</code>.</p>
<p>See <a href="#all_assert_assertdeepstrictequalactual-expected-message"><code>assert.deepStrictEqual()</code></a> for more information about deep strict
equality.</p>
</section><section><h3>Class: <code>util.MIMEType</code><span><a class="mark" href="#all_util_class-utilmimetype" id="all_util_class-utilmimetype">#</a></span><a aria-hidden="true" class="legacy" id="util_class_util_mimetype"></a></h3>
<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="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>An implementation of <a href="https://bmeck.github.io/node-proposal-mime-api/">the MIMEType class</a>.</p>
<p>In accordance with browser conventions, all properties of <code>MIMEType</code> objects
are implemented as getters and setters on the class prototype, rather than as
data properties on the object itself.</p>
<p>A MIME string is a structured string containing multiple meaningful
components. When parsed, a <code>MIMEType</code> object is returned containing
properties for each of these components.</p>
<h4>Constructor: <code>new MIMEType(input)</code><span><a class="mark" href="#all_util_constructor-new-mimetypeinput" id="all_util_constructor-new-mimetypeinput">#</a></span><a aria-hidden="true" class="legacy" id="util_constructor_new_mimetype_input"></a></h4>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The input MIME to parse</li>
</ul>
<p>Creates a new <code>MIMEType</code> object by parsing the <code>input</code>.</p>
<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_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain'</span>);</code><button class="copy-button">copy</button></pre>
<p>A <code>TypeError</code> will be thrown if the <code>input</code> is not a valid MIME. Note
that an effort will be made to coerce the given values into strings. For
instance:</p>
<pre class="with-62-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_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>({ <span class="hljs-attr">toString</span>: <span class="hljs-function">() =></span> <span class="hljs-string">'text/plain'</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: text/plain</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>({ <span class="hljs-attr">toString</span>: <span class="hljs-function">() =></span> <span class="hljs-string">'text/plain'</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: text/plain</span></code><button class="copy-button">copy</button></pre>
<h4><code>mime.type</code><span><a class="mark" href="#all_util_mimetype" id="all_util_mimetype">#</a></span><a aria-hidden="true" class="legacy" id="util_mime_type"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets and sets the type portion of the MIME.</p>
<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_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/javascript'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">type</span>);
<span class="hljs-comment">// Prints: text</span>
myMIME.<span class="hljs-property">type</span> = <span class="hljs-string">'application'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">type</span>);
<span class="hljs-comment">// Prints: application</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: application/javascript</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/javascript'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">type</span>);
<span class="hljs-comment">// Prints: text</span>
myMIME.<span class="hljs-property">type</span> = <span class="hljs-string">'application'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">type</span>);
<span class="hljs-comment">// Prints: application</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: application/javascript</span></code><button class="copy-button">copy</button></pre>
<h4><code>mime.subtype</code><span><a class="mark" href="#all_util_mimesubtype" id="all_util_mimesubtype">#</a></span><a aria-hidden="true" class="legacy" id="util_mime_subtype"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets and sets the subtype portion of the MIME.</p>
<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_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/ecmascript'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">subtype</span>);
<span class="hljs-comment">// Prints: ecmascript</span>
myMIME.<span class="hljs-property">subtype</span> = <span class="hljs-string">'javascript'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">subtype</span>);
<span class="hljs-comment">// Prints: javascript</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: text/javascript</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/ecmascript'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">subtype</span>);
<span class="hljs-comment">// Prints: ecmascript</span>
myMIME.<span class="hljs-property">subtype</span> = <span class="hljs-string">'javascript'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">subtype</span>);
<span class="hljs-comment">// Prints: javascript</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: text/javascript</span></code><button class="copy-button">copy</button></pre>
<h4><code>mime.essence</code><span><a class="mark" href="#all_util_mimeessence" id="all_util_mimeessence">#</a></span><a aria-hidden="true" class="legacy" id="util_mime_essence"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Gets the essence of the MIME. This property is read only.
Use <code>mime.type</code> or <code>mime.subtype</code> to alter the MIME.</p>
<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_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/javascript;key=value'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">essence</span>);
<span class="hljs-comment">// Prints: text/javascript</span>
myMIME.<span class="hljs-property">type</span> = <span class="hljs-string">'application'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">essence</span>);
<span class="hljs-comment">// Prints: application/javascript</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: application/javascript;key=value</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/javascript;key=value'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">essence</span>);
<span class="hljs-comment">// Prints: text/javascript</span>
myMIME.<span class="hljs-property">type</span> = <span class="hljs-string">'application'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">essence</span>);
<span class="hljs-comment">// Prints: application/javascript</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: application/javascript;key=value</span></code><button class="copy-button">copy</button></pre>
<h4><code>mime.params</code><span><a class="mark" href="#all_util_mimeparams" id="all_util_mimeparams">#</a></span><a aria-hidden="true" class="legacy" id="util_mime_params"></a></h4>
<ul>
<li><a href="#all_util_class-utilmimeparams" class="type"><MIMEParams></a></li>
</ul>
<p>Gets the <a href="#all_util_class-utilmimeparams"><code>MIMEParams</code></a> object representing the
parameters of the MIME. This property is read-only. See
<a href="#all_util_class-utilmimeparams"><code>MIMEParams</code></a> documentation for details.</p>
<h4><code>mime.toString()</code><span><a class="mark" href="#all_util_mimetostring" id="all_util_mimetostring">#</a></span><a aria-hidden="true" class="legacy" id="util_mime_tostring"></a></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>toString()</code> method on the <code>MIMEType</code> object returns the serialized MIME.</p>
<p>Because of the need for standard compliance, this method does not allow users
to customize the serialization process of the MIME.</p>
<h4><code>mime.toJSON()</code><span><a class="mark" href="#all_util_mimetojson" id="all_util_mimetojson">#</a></span><a aria-hidden="true" class="legacy" id="util_mime_tojson"></a></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Alias for <a href="#all_util_mimetostring"><code>mime.toString()</code></a>.</p>
<p>This method is automatically called when an <code>MIMEType</code> object is serialized
with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify"><code>JSON.stringify()</code></a>.</p>
<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_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> myMIMES = [
<span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'image/png'</span>),
<span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'image/gif'</span>),
];
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(myMIMES));
<span class="hljs-comment">// Prints: ["image/png", "image/gif"]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> myMIMES = [
<span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'image/png'</span>),
<span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'image/gif'</span>),
];
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(myMIMES));
<span class="hljs-comment">// Prints: ["image/png", "image/gif"]</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>util.MIMEParams</code><span><a class="mark" href="#all_util_class-utilmimeparams" id="all_util_class-utilmimeparams">#</a></span><a aria-hidden="true" class="legacy" id="util_class_util_mimeparams"></a></h3>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p>The <code>MIMEParams</code> API provides read and write access to the parameters of a
<code>MIMEType</code>.</p>
<h4>Constructor: <code>new MIMEParams()</code><span><a class="mark" href="#all_util_constructor-new-mimeparams" id="all_util_constructor-new-mimeparams">#</a></span><a aria-hidden="true" class="legacy" id="util_constructor_new_mimeparams"></a></h4>
<p>Creates a new <code>MIMEParams</code> object by with empty parameters</p>
<pre class="with-44-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_">MIMEParams</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> myParams = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEParams</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEParams</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> myParams = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEParams</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>mimeParams.delete(name)</code><span><a class="mark" href="#all_util_mimeparamsdeletename" id="all_util_mimeparamsdeletename">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_delete_name"></a></h4>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Remove all name-value pairs whose name is <code>name</code>.</p>
<h4><code>mimeParams.entries()</code><span><a class="mark" href="#all_util_mimeparamsentries" id="all_util_mimeparamsentries">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_entries"></a></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li>
</ul>
<p>Returns an iterator over each of the name-value pairs in the parameters.
Each item of the iterator is a JavaScript <code>Array</code>. The first item of the array
is the <code>name</code>, the second item of the array is the <code>value</code>.</p>
<h4><code>mimeParams.get(name)</code><span><a class="mark" href="#all_util_mimeparamsgetname" id="all_util_mimeparamsgetname">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_get_name"></a></h4>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <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 string or <code>null</code> if there is no name-value pair
with the given <code>name</code>.</li>
</ul>
<p>Returns the value of the first name-value pair whose name is <code>name</code>. If there
are no such pairs, <code>null</code> is returned.</p>
<h4><code>mimeParams.has(name)</code><span><a class="mark" href="#all_util_mimeparamshasname" id="all_util_mimeparamshasname">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_has_name"></a></h4>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></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 <code>true</code> if there is at least one name-value pair whose name is <code>name</code>.</p>
<h4><code>mimeParams.keys()</code><span><a class="mark" href="#all_util_mimeparamskeys" id="all_util_mimeparamskeys">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_keys"></a></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li>
</ul>
<p>Returns an iterator over the names of each name-value pair.</p>
<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_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> { params } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain;foo=0;bar=1'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> name <span class="hljs-keyword">of</span> params.<span class="hljs-title function_">keys</span>()) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// foo</span>
<span class="hljs-comment">// bar</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> { params } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain;foo=0;bar=1'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> name <span class="hljs-keyword">of</span> params.<span class="hljs-title function_">keys</span>()) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// foo</span>
<span class="hljs-comment">// bar</span></code><button class="copy-button">copy</button></pre>
<h4><code>mimeParams.set(name, value)</code><span><a class="mark" href="#all_util_mimeparamssetname-value" id="all_util_mimeparamssetname-value">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_set_name_value"></a></h4>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Sets the value in the <code>MIMEParams</code> object associated with <code>name</code> to
<code>value</code>. If there are any pre-existing name-value pairs whose names are <code>name</code>,
set the first such pair's value to <code>value</code>.</p>
<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_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> { params } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain;foo=0;bar=1'</span>);
params.<span class="hljs-title function_">set</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'def'</span>);
params.<span class="hljs-title function_">set</span>(<span class="hljs-string">'baz'</span>, <span class="hljs-string">'xyz'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: foo=def;bar=1;baz=xyz</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> { params } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain;foo=0;bar=1'</span>);
params.<span class="hljs-title function_">set</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'def'</span>);
params.<span class="hljs-title function_">set</span>(<span class="hljs-string">'baz'</span>, <span class="hljs-string">'xyz'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: foo=def;bar=1;baz=xyz</span></code><button class="copy-button">copy</button></pre>
<h4><code>mimeParams.values()</code><span><a class="mark" href="#all_util_mimeparamsvalues" id="all_util_mimeparamsvalues">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_values"></a></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li>
</ul>
<p>Returns an iterator over the values of each name-value pair.</p>
<h4><code>mimeParams[@@iterator]()</code><span><a class="mark" href="#all_util_mimeparamsiterator" id="all_util_mimeparamsiterator">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_iterator"></a></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li>
</ul>
<p>Alias for <a href="#all_util_mimeparamsentries"><code>mimeParams.entries()</code></a>.</p>
<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_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> { params } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain;foo=bar;xyz=baz'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [name, value] <span class="hljs-keyword">of</span> params) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name, value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// foo bar</span>
<span class="hljs-comment">// xyz baz</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> { params } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain;foo=bar;xyz=baz'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [name, value] <span class="hljs-keyword">of</span> params) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name, value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// foo bar</span>
<span class="hljs-comment">// xyz baz</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>util.parseArgs([config])</code><span><a class="mark" href="#all_util_utilparseargsconfig" id="all_util_utilparseargsconfig">#</a></span><a aria-hidden="true" class="legacy" id="util_util_parseargs_config"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>add support for allowing negative options in input <code>config</code>.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p>The API is no longer experimental.</p></td></tr>
<tr><td>v18.11.0, v16.19.0</td>
<td><p>Add support for default values in input <code>config</code>.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p>add support for returning detailed parse information using <code>tokens</code> in input <code>config</code> and returned properties.</p></td></tr>
<tr><td>v18.3.0, v16.17.0</td>
<td><p><span>Added in: v18.3.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>config</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Used to provide arguments for parsing and to configure
the parser. <code>config</code> supports the following properties:</p>
<ul>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> array of argument strings. <strong>Default:</strong> <code>process.argv</code>
with <code>execPath</code> and <code>filename</code> removed.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Used to describe arguments known to the parser.
Keys of <code>options</code> are the long names of options and values are an
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> accepting the following properties:
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Type of argument, which must be either <code>boolean</code> or <code>string</code>.</li>
<li><code>multiple</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether this option can be provided multiple
times. If <code>true</code>, all values will be collected in an array. If
<code>false</code>, values for the option are last-wins. <strong>Default:</strong> <code>false</code>.</li>
<li><code>short</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A single character alias for the option.</li>
<li><code>default</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#Boolean_type" class="type"><boolean></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#Boolean_type" class="type"><boolean[]></a> The default value to
be used if (and only if) the option does not appear in the arguments to be
parsed. It must be of the same type as the <code>type</code> property. When <code>multiple</code>
is <code>true</code>, it must be an array.</li>
</ul>
</li>
<li><code>strict</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Should an error be thrown when unknown arguments
are encountered, or when arguments are passed that do not match the
<code>type</code> configured in <code>options</code>.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>allowPositionals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether this command accepts positional
arguments.
<strong>Default:</strong> <code>false</code> if <code>strict</code> is <code>true</code>, otherwise <code>true</code>.</li>
<li><code>allowNegative</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, allows explicitly setting boolean
options to <code>false</code> by prefixing the option name with <code>--no-</code>.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>tokens</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Return the parsed tokens. This is useful for extending
the built-in behavior, from adding additional checks through to reprocessing
the tokens in different ways.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The parsed command line arguments:</p>
<ul>
<li><code>values</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A mapping of parsed option names with their <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>
or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> values.</li>
<li><code>positionals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Positional arguments.</li>
<li><code>tokens</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> See <a href="#all_util_parseargs-tokens">parseArgs tokens</a>
section. Only returned if <code>config</code> includes <code>tokens: true</code>.</li>
</ul>
</li>
</ul>
<p>Provides a higher level API for command-line argument parsing than interacting
with <code>process.argv</code> directly. Takes a specification for the expected arguments
and returns a structured object with the parsed options and positionals.</p>
<pre class="with-43-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> { parseArgs } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> args = [<span class="hljs-string">'-f'</span>, <span class="hljs-string">'--bar'</span>, <span class="hljs-string">'b'</span>];
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">foo</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span>,
<span class="hljs-attr">short</span>: <span class="hljs-string">'f'</span>,
},
<span class="hljs-attr">bar</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">'string'</span>,
},
};
<span class="hljs-keyword">const</span> {
values,
positionals,
} = <span class="hljs-title function_">parseArgs</span>({ args, options });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(values, positionals);
<span class="hljs-comment">// Prints: [Object: null prototype] { foo: true, bar: 'b' } []</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { parseArgs } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> args = [<span class="hljs-string">'-f'</span>, <span class="hljs-string">'--bar'</span>, <span class="hljs-string">'b'</span>];
<span class="hljs-keyword">const</span> options = {
<span class="hljs-attr">foo</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span>,
<span class="hljs-attr">short</span>: <span class="hljs-string">'f'</span>,
},
<span class="hljs-attr">bar</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">'string'</span>,
},
};
<span class="hljs-keyword">const</span> {
values,
positionals,
} = <span class="hljs-title function_">parseArgs</span>({ args, options });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(values, positionals);
<span class="hljs-comment">// Prints: [Object: null prototype] { foo: true, bar: 'b' } []</span></code><button class="copy-button">copy</button></pre>
<h4><code>parseArgs</code> <code>tokens</code><span><a class="mark" href="#all_util_parseargs-tokens" id="all_util_parseargs-tokens">#</a></span><a aria-hidden="true" class="legacy" id="util_parseargs_tokens"></a></h4>
<p>Detailed parse information is available for adding custom behaviors by
specifying <code>tokens: true</code> in the configuration.
The returned tokens have properties describing:</p>
<ul>
<li>all tokens
<ul>
<li><code>kind</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> One of 'option', 'positional', or 'option-terminator'.</li>
<li><code>index</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Index of element in <code>args</code> containing token. So the
source argument for a token is <code>args[token.index]</code>.</li>
</ul>
</li>
<li>option tokens
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Long name of option.</li>
<li><code>rawName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> How option used in args, like <code>-f</code> of <code>--foo</code>.</li>
<li><code>value</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#Undefined_type" class="type"><undefined></a> Option value specified in args.
Undefined for boolean options.</li>
<li><code>inlineValue</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> Whether option value specified inline,
like <code>--foo=bar</code>.</li>
</ul>
</li>
<li>positional tokens
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The value of the positional argument in args (i.e. <code>args[index]</code>).</li>
</ul>
</li>
<li>option-terminator token</li>
</ul>
<p>The returned tokens are in the order encountered in the input args. Options
that appear more than once in args produce a token for each use. Short option
groups like <code>-xy</code> expand to a token for each option. So <code>-xxx</code> produces
three tokens.</p>
<p>For example, to add support for a negated option like <code>--no-color</code> (which
<code>allowNegative</code> supports when the option is of <code>boolean</code> type), the returned
tokens can be reprocessed to change the value stored for the negated option.</p>
<pre class="with-43-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> { parseArgs } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> options = {
<span class="hljs-string">'color'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span> },
<span class="hljs-string">'no-color'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span> },
<span class="hljs-string">'logfile'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'string'</span> },
<span class="hljs-string">'no-logfile'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span> },
};
<span class="hljs-keyword">const</span> { values, tokens } = <span class="hljs-title function_">parseArgs</span>({ options, <span class="hljs-attr">tokens</span>: <span class="hljs-literal">true</span> });
<span class="hljs-comment">// Reprocess the option tokens and overwrite the returned values.</span>
tokens
.<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">token</span>) =></span> token.<span class="hljs-property">kind</span> === <span class="hljs-string">'option'</span>)
.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">token</span>) =></span> {
<span class="hljs-keyword">if</span> (token.<span class="hljs-property">name</span>.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'no-'</span>)) {
<span class="hljs-comment">// Store foo:false for --no-foo</span>
<span class="hljs-keyword">const</span> positiveName = token.<span class="hljs-property">name</span>.<span class="hljs-title function_">slice</span>(<span class="hljs-number">3</span>);
values[positiveName] = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">delete</span> values[token.<span class="hljs-property">name</span>];
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Resave value so last one wins if both --foo and --no-foo.</span>
values[token.<span class="hljs-property">name</span>] = token.<span class="hljs-property">value</span> ?? <span class="hljs-literal">true</span>;
}
});
<span class="hljs-keyword">const</span> color = values.<span class="hljs-property">color</span>;
<span class="hljs-keyword">const</span> logfile = values.<span class="hljs-property">logfile</span> ?? <span class="hljs-string">'default.log'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>({ logfile, color });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { parseArgs } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> options = {
<span class="hljs-string">'color'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span> },
<span class="hljs-string">'no-color'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span> },
<span class="hljs-string">'logfile'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'string'</span> },
<span class="hljs-string">'no-logfile'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span> },
};
<span class="hljs-keyword">const</span> { values, tokens } = <span class="hljs-title function_">parseArgs</span>({ options, <span class="hljs-attr">tokens</span>: <span class="hljs-literal">true</span> });
<span class="hljs-comment">// Reprocess the option tokens and overwrite the returned values.</span>
tokens
.<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">token</span>) =></span> token.<span class="hljs-property">kind</span> === <span class="hljs-string">'option'</span>)
.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">token</span>) =></span> {
<span class="hljs-keyword">if</span> (token.<span class="hljs-property">name</span>.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'no-'</span>)) {
<span class="hljs-comment">// Store foo:false for --no-foo</span>
<span class="hljs-keyword">const</span> positiveName = token.<span class="hljs-property">name</span>.<span class="hljs-title function_">slice</span>(<span class="hljs-number">3</span>);
values[positiveName] = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">delete</span> values[token.<span class="hljs-property">name</span>];
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Resave value so last one wins if both --foo and --no-foo.</span>
values[token.<span class="hljs-property">name</span>] = token.<span class="hljs-property">value</span> ?? <span class="hljs-literal">true</span>;
}
});
<span class="hljs-keyword">const</span> color = values.<span class="hljs-property">color</span>;
<span class="hljs-keyword">const</span> logfile = values.<span class="hljs-property">logfile</span> ?? <span class="hljs-string">'default.log'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>({ logfile, color });</code><button class="copy-button">copy</button></pre>
<p>Example usage showing negated options, and when an option is used
multiple ways then last one wins.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node negate.js</span>
{ logfile: 'default.log', color: undefined }
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node negate.js --no-logfile --no-color</span>
{ logfile: false, color: false }
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node negate.js --logfile=test.log --color</span>
{ logfile: 'test.log', color: true }
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node negate.js --no-logfile --logfile=test.log --color --no-color</span>
{ logfile: 'test.log', color: false }</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.parseEnv(content)</code><span><a class="mark" href="#all_util_utilparseenvcontent" id="all_util_utilparseenvcontent">#</a></span><a aria-hidden="true" class="legacy" id="util_util_parseenv_content"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<ul>
<li><code>content</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The raw contents of a <code>.env</code> file.</p>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Given an example <code>.env</code> file:</p>
<pre class="with-42-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> { parseEnv } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-title function_">parseEnv</span>(<span class="hljs-string">'HELLO=world\nHELLO=oh my\n'</span>);
<span class="hljs-comment">// Returns: { HELLO: 'oh my' }</span></code><code class="language-js mjs"><span class="hljs-keyword">import</span> { parseEnv } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-title function_">parseEnv</span>(<span class="hljs-string">'HELLO=world\nHELLO=oh my\n'</span>);
<span class="hljs-comment">// Returns: { HELLO: 'oh my' }</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>util.promisify(original)</code><span><a class="mark" href="#all_util_utilpromisifyoriginal" id="all_util_utilpromisifyoriginal">#</a></span><a aria-hidden="true" class="legacy" id="util_util_promisify_original"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.8.0</td>
<td><p>Calling <code>promisify</code> on a function that returns a <code>Promise</code> is deprecated.</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>original</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>Takes a function following the common error-first callback style, i.e. taking
an <code>(err, value) => ...</code> callback as the last argument, and returns a version
that returns promises.</p>
<pre><code class="language-js"><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">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> stat = util.<span class="hljs-title function_">promisify</span>(fs.<span class="hljs-property">stat</span>);
<span class="hljs-title function_">stat</span>(<span class="hljs-string">'.'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">stats</span>) =></span> {
<span class="hljs-comment">// Do something with `stats`</span>
}).<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">error</span>) =></span> {
<span class="hljs-comment">// Handle the error.</span>
});</code> <button class="copy-button">copy</button></pre>
<p>Or, equivalently using <code>async function</code>s:</p>
<pre><code class="language-js"><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">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> stat = util.<span class="hljs-title function_">promisify</span>(fs.<span class="hljs-property">stat</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">callStat</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(<span class="hljs-string">'.'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This directory is owned by <span class="hljs-subst">${stats.uid}</span>`</span>);
}
<span class="hljs-title function_">callStat</span>();</code> <button class="copy-button">copy</button></pre>
<p>If there is an <code>original[util.promisify.custom]</code> property present, <code>promisify</code>
will return its value, see <a href="#all_util_custom-promisified-functions">Custom promisified functions</a>.</p>
<p><code>promisify()</code> assumes that <code>original</code> is a function taking a callback as its
final argument in all cases. If <code>original</code> is not a function, <code>promisify()</code>
will throw an error. If <code>original</code> is a function but its last argument is not
an error-first callback, it will still be passed an error-first
callback as its last argument.</p>
<p>Using <code>promisify()</code> on class methods or other methods that use <code>this</code> may not
work as expected unless handled specially:</p>
<pre><code class="language-js"><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">class</span> <span class="hljs-title class_">Foo</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">a</span> = <span class="hljs-number">42</span>;
}
<span class="hljs-title function_">bar</span>(<span class="hljs-params">callback</span>) {
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-variable language_">this</span>.<span class="hljs-property">a</span>);
}
}
<span class="hljs-keyword">const</span> foo = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>();
<span class="hljs-keyword">const</span> naiveBar = util.<span class="hljs-title function_">promisify</span>(foo.<span class="hljs-property">bar</span>);
<span class="hljs-comment">// TypeError: Cannot read property 'a' of undefined</span>
<span class="hljs-comment">// naiveBar().then(a => console.log(a));</span>
naiveBar.<span class="hljs-title function_">call</span>(foo).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">a</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a)); <span class="hljs-comment">// '42'</span>
<span class="hljs-keyword">const</span> bindBar = naiveBar.<span class="hljs-title function_">bind</span>(foo);
<span class="hljs-title function_">bindBar</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">a</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a)); <span class="hljs-comment">// '42'</span></code> <button class="copy-button">copy</button></pre>
<h4>Custom promisified functions<span><a class="mark" href="#all_util_custom-promisified-functions" id="all_util_custom-promisified-functions">#</a></span><a aria-hidden="true" class="legacy" id="util_custom_promisified_functions"></a></h4>
<p>Using the <code>util.promisify.custom</code> symbol one can override the return value of
<a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>:</p>
<pre><code class="language-js"><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_">doSomething</span>(<span class="hljs-params">foo, callback</span>) {
<span class="hljs-comment">// ...</span>
}
doSomething[util.<span class="hljs-property">promisify</span>.<span class="hljs-property">custom</span>] = <span class="hljs-function">(<span class="hljs-params">foo</span>) =></span> {
<span class="hljs-keyword">return</span> <span class="hljs-title function_">getPromiseSomehow</span>();
};
<span class="hljs-keyword">const</span> promisified = util.<span class="hljs-title function_">promisify</span>(doSomething);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(promisified === doSomething[util.<span class="hljs-property">promisify</span>.<span class="hljs-property">custom</span>]);
<span class="hljs-comment">// prints 'true'</span></code> <button class="copy-button">copy</button></pre>
<p>This can be useful for cases where the original function does not follow the
standard format of taking an error-first callback as the last argument.</p>
<p>For example, with a function that takes in
<code>(foo, onSuccessCallback, onErrorCallback)</code>:</p>
<pre><code class="language-js">doSomething[util.<span class="hljs-property">promisify</span>.<span class="hljs-property">custom</span>] = <span class="hljs-function">(<span class="hljs-params">foo</span>) =></span> {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
<span class="hljs-title function_">doSomething</span>(foo, resolve, reject);
});
};</code> <button class="copy-button">copy</button></pre>
<p>If <code>promisify.custom</code> is defined but is not a function, <code>promisify()</code> will
throw an error.</p>
<h4><code>util.promisify.custom</code><span><a class="mark" href="#all_util_utilpromisifycustom" id="all_util_utilpromisifycustom">#</a></span><a aria-hidden="true" class="legacy" id="util_util_promisify_custom"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.16.2</td>
<td><p>This is now defined as a shared symbol.</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><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> that can be used to declare custom promisified variants of functions,
see <a href="#all_util_custom-promisified-functions">Custom promisified functions</a>.</li>
</ul>
<p>In addition to being accessible through <code>util.promisify.custom</code>, this
symbol is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for">registered globally</a> and can be
accessed in any environment as <code>Symbol.for('nodejs.util.promisify.custom')</code>.</p>
<p>For example, with a function that takes in
<code>(foo, onSuccessCallback, onErrorCallback)</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> kCustomPromisifiedSymbol = <span class="hljs-title class_">Symbol</span>.<span class="hljs-title function_">for</span>(<span class="hljs-string">'nodejs.util.promisify.custom'</span>);
doSomething[kCustomPromisifiedSymbol] = <span class="hljs-function">(<span class="hljs-params">foo</span>) =></span> {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
<span class="hljs-title function_">doSomething</span>(foo, resolve, reject);
});
};</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.stripVTControlCharacters(str)</code><span><a class="mark" href="#all_util_utilstripvtcontrolcharactersstr" id="all_util_utilstripvtcontrolcharactersstr">#</a></span><a aria-hidden="true" class="legacy" id="util_util_stripvtcontrolcharacters_str"></a></h3>
<div class="api_metadata">
<span>Added in: v16.11.0</span>
</div>
<ul>
<li><code>str</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns <code>str</code> with any ANSI escape codes removed.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-title function_">stripVTControlCharacters</span>(<span class="hljs-string">'\u001B[4mvalue\u001B[0m'</span>));
<span class="hljs-comment">// Prints "value"</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.styleText(format, text[, options])</code><span><a class="mark" href="#all_util_utilstyletextformat-text-options" id="all_util_utilstyletextformat-text-options">#</a></span><a aria-hidden="true" class="legacy" id="util_util_styletext_format_text_options"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>Respect isTTY and environment variables such as NO_COLORS, NODE_DISABLE_COLORS, and FORCE_COLOR.</p></td></tr>
<tr><td>v20.12.0</td>
<td><p><span>Added in: v20.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>format</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/Reference/Global_Objects/Array" class="type"><Array></a> A text format or an Array
of text formats defined in <code>util.inspect.colors</code>.</li>
<li><code>text</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The text to to be formatted.</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>validateStream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When true, <code>stream</code> is checked to see if it can handle colors. <strong>Default:</strong> <code>true</code>.</li>
<li><code>stream</code> <a href="#all_stream_stream" class="type"><Stream></a> A stream that will be validated if it can be colored. <strong>Default:</strong> <code>process.stdout</code>.</li>
</ul>
</li>
</ul>
<p>This function returns a formatted text considering the <code>format</code> passed
for printing in a terminal. It is aware of the terminal's capabilities
and acts according to the configuration set via <code>NO_COLORS</code>,
<code>NODE_DISABLE_COLORS</code> and <code>FORCE_COLOR</code> environment variables.</p>
<pre class="with-43-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> { styleText } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">import</span> { stderr } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> successMessage = <span class="hljs-title function_">styleText</span>(<span class="hljs-string">'green'</span>, <span class="hljs-string">'Success!'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(successMessage);
<span class="hljs-keyword">const</span> errorMessage = <span class="hljs-title function_">styleText</span>(
<span class="hljs-string">'red'</span>,
<span class="hljs-string">'Error! Error!'</span>,
<span class="hljs-comment">// Validate if process.stderr has TTY</span>
{ <span class="hljs-attr">stream</span>: stderr },
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(errorMessage);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { styleText } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> { stderr } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> successMessage = <span class="hljs-title function_">styleText</span>(<span class="hljs-string">'green'</span>, <span class="hljs-string">'Success!'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(successMessage);
<span class="hljs-keyword">const</span> errorMessage = <span class="hljs-title function_">styleText</span>(
<span class="hljs-string">'red'</span>,
<span class="hljs-string">'Error! Error!'</span>,
<span class="hljs-comment">// Validate if process.stderr has TTY</span>
{ <span class="hljs-attr">stream</span>: stderr },
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(successMessage);</code><button class="copy-button">copy</button></pre>
<p><code>util.inspect.colors</code> also provides text formats such as <code>italic</code>, and
<code>underline</code> and you can combine both:</p>
<pre><code class="language-js cjs"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
util.<span class="hljs-title function_">styleText</span>([<span class="hljs-string">'underline'</span>, <span class="hljs-string">'italic'</span>], <span class="hljs-string">'My italic underlined message'</span>),
);</code> <button class="copy-button">copy</button></pre>
<p>When passing an array of formats, the order of the format applied
is left to right so the following style might overwrite the previous one.</p>
<pre><code class="language-js cjs"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
util.<span class="hljs-title function_">styleText</span>([<span class="hljs-string">'red'</span>, <span class="hljs-string">'green'</span>], <span class="hljs-string">'text'</span>), <span class="hljs-comment">// green</span>
);</code> <button class="copy-button">copy</button></pre>
<p>The full list of formats can be found in <a href="#all_util_modifiers">modifiers</a>.</p>
</section><section><h3>Class: <code>util.TextDecoder</code><span><a class="mark" href="#all_util_class-utiltextdecoder" id="all_util_class-utiltextdecoder">#</a></span><a aria-hidden="true" class="legacy" id="util_class_util_textdecoder"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>The class is now available on the global object.</p></td></tr>
<tr><td>v8.3.0</td>
<td><p><span>Added in: v8.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An implementation of the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a> <code>TextDecoder</code> API.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> decoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextDecoder</span>();
<span class="hljs-keyword">const</span> u8arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>([<span class="hljs-number">72</span>, <span class="hljs-number">101</span>, <span class="hljs-number">108</span>, <span class="hljs-number">108</span>, <span class="hljs-number">111</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decoder.<span class="hljs-title function_">decode</span>(u8arr)); <span class="hljs-comment">// Hello</span></code> <button class="copy-button">copy</button></pre>
<h4>WHATWG supported encodings<span><a class="mark" href="#all_util_whatwg-supported-encodings" id="all_util_whatwg-supported-encodings">#</a></span><a aria-hidden="true" class="legacy" id="util_whatwg_supported_encodings"></a></h4>
<p>Per the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a>, the encodings supported by the
<code>TextDecoder</code> API are outlined in the tables below. For each encoding,
one or more aliases may be used.</p>
<p>Different Node.js build configurations support different sets of encodings.
(see <a href="intl.html">Internationalization</a>)</p>
<h5>Encodings supported by default (with full ICU data)<span><a class="mark" href="#all_util_encodings-supported-by-default-with-full-icu-data" id="all_util_encodings-supported-by-default-with-full-icu-data">#</a></span><a aria-hidden="true" class="legacy" id="util_encodings_supported_by_default_with_full_icu_data"></a></h5>
<table><thead><tr><th>Encoding</th><th>Aliases</th></tr></thead><tbody><tr><td><code>'ibm866'</code></td><td><code>'866'</code>, <code>'cp866'</code>, <code>'csibm866'</code></td></tr><tr><td><code>'iso-8859-2'</code></td><td><code>'csisolatin2'</code>, <code>'iso-ir-101'</code>, <code>'iso8859-2'</code>, <code>'iso88592'</code>, <code>'iso_8859-2'</code>, <code>'iso_8859-2:1987'</code>, <code>'l2'</code>, <code>'latin2'</code></td></tr><tr><td><code>'iso-8859-3'</code></td><td><code>'csisolatin3'</code>, <code>'iso-ir-109'</code>, <code>'iso8859-3'</code>, <code>'iso88593'</code>, <code>'iso_8859-3'</code>, <code>'iso_8859-3:1988'</code>, <code>'l3'</code>, <code>'latin3'</code></td></tr><tr><td><code>'iso-8859-4'</code></td><td><code>'csisolatin4'</code>, <code>'iso-ir-110'</code>, <code>'iso8859-4'</code>, <code>'iso88594'</code>, <code>'iso_8859-4'</code>, <code>'iso_8859-4:1988'</code>, <code>'l4'</code>, <code>'latin4'</code></td></tr><tr><td><code>'iso-8859-5'</code></td><td><code>'csisolatincyrillic'</code>, <code>'cyrillic'</code>, <code>'iso-ir-144'</code>, <code>'iso8859-5'</code>, <code>'iso88595'</code>, <code>'iso_8859-5'</code>, <code>'iso_8859-5:1988'</code></td></tr><tr><td><code>'iso-8859-6'</code></td><td><code>'arabic'</code>, <code>'asmo-708'</code>, <code>'csiso88596e'</code>, <code>'csiso88596i'</code>, <code>'csisolatinarabic'</code>, <code>'ecma-114'</code>, <code>'iso-8859-6-e'</code>, <code>'iso-8859-6-i'</code>, <code>'iso-ir-127'</code>, <code>'iso8859-6'</code>, <code>'iso88596'</code>, <code>'iso_8859-6'</code>, <code>'iso_8859-6:1987'</code></td></tr><tr><td><code>'iso-8859-7'</code></td><td><code>'csisolatingreek'</code>, <code>'ecma-118'</code>, <code>'elot_928'</code>, <code>'greek'</code>, <code>'greek8'</code>, <code>'iso-ir-126'</code>, <code>'iso8859-7'</code>, <code>'iso88597'</code>, <code>'iso_8859-7'</code>, <code>'iso_8859-7:1987'</code>, <code>'sun_eu_greek'</code></td></tr><tr><td><code>'iso-8859-8'</code></td><td><code>'csiso88598e'</code>, <code>'csisolatinhebrew'</code>, <code>'hebrew'</code>, <code>'iso-8859-8-e'</code>, <code>'iso-ir-138'</code>, <code>'iso8859-8'</code>, <code>'iso88598'</code>, <code>'iso_8859-8'</code>, <code>'iso_8859-8:1988'</code>, <code>'visual'</code></td></tr><tr><td><code>'iso-8859-8-i'</code></td><td><code>'csiso88598i'</code>, <code>'logical'</code></td></tr><tr><td><code>'iso-8859-10'</code></td><td><code>'csisolatin6'</code>, <code>'iso-ir-157'</code>, <code>'iso8859-10'</code>, <code>'iso885910'</code>, <code>'l6'</code>, <code>'latin6'</code></td></tr><tr><td><code>'iso-8859-13'</code></td><td><code>'iso8859-13'</code>, <code>'iso885913'</code></td></tr><tr><td><code>'iso-8859-14'</code></td><td><code>'iso8859-14'</code>, <code>'iso885914'</code></td></tr><tr><td><code>'iso-8859-15'</code></td><td><code>'csisolatin9'</code>, <code>'iso8859-15'</code>, <code>'iso885915'</code>, <code>'iso_8859-15'</code>, <code>'l9'</code></td></tr><tr><td><code>'koi8-r'</code></td><td><code>'cskoi8r'</code>, <code>'koi'</code>, <code>'koi8'</code>, <code>'koi8_r'</code></td></tr><tr><td><code>'koi8-u'</code></td><td><code>'koi8-ru'</code></td></tr><tr><td><code>'macintosh'</code></td><td><code>'csmacintosh'</code>, <code>'mac'</code>, <code>'x-mac-roman'</code></td></tr><tr><td><code>'windows-874'</code></td><td><code>'dos-874'</code>, <code>'iso-8859-11'</code>, <code>'iso8859-11'</code>, <code>'iso885911'</code>, <code>'tis-620'</code></td></tr><tr><td><code>'windows-1250'</code></td><td><code>'cp1250'</code>, <code>'x-cp1250'</code></td></tr><tr><td><code>'windows-1251'</code></td><td><code>'cp1251'</code>, <code>'x-cp1251'</code></td></tr><tr><td><code>'windows-1252'</code></td><td><code>'ansi_x3.4-1968'</code>, <code>'ascii'</code>, <code>'cp1252'</code>, <code>'cp819'</code>, <code>'csisolatin1'</code>, <code>'ibm819'</code>, <code>'iso-8859-1'</code>, <code>'iso-ir-100'</code>, <code>'iso8859-1'</code>, <code>'iso88591'</code>, <code>'iso_8859-1'</code>, <code>'iso_8859-1:1987'</code>, <code>'l1'</code>, <code>'latin1'</code>, <code>'us-ascii'</code>, <code>'x-cp1252'</code></td></tr><tr><td><code>'windows-1253'</code></td><td><code>'cp1253'</code>, <code>'x-cp1253'</code></td></tr><tr><td><code>'windows-1254'</code></td><td><code>'cp1254'</code>, <code>'csisolatin5'</code>, <code>'iso-8859-9'</code>, <code>'iso-ir-148'</code>, <code>'iso8859-9'</code>, <code>'iso88599'</code>, <code>'iso_8859-9'</code>, <code>'iso_8859-9:1989'</code>, <code>'l5'</code>, <code>'latin5'</code>, <code>'x-cp1254'</code></td></tr><tr><td><code>'windows-1255'</code></td><td><code>'cp1255'</code>, <code>'x-cp1255'</code></td></tr><tr><td><code>'windows-1256'</code></td><td><code>'cp1256'</code>, <code>'x-cp1256'</code></td></tr><tr><td><code>'windows-1257'</code></td><td><code>'cp1257'</code>, <code>'x-cp1257'</code></td></tr><tr><td><code>'windows-1258'</code></td><td><code>'cp1258'</code>, <code>'x-cp1258'</code></td></tr><tr><td><code>'x-mac-cyrillic'</code></td><td><code>'x-mac-ukrainian'</code></td></tr><tr><td><code>'gbk'</code></td><td><code>'chinese'</code>, <code>'csgb2312'</code>, <code>'csiso58gb231280'</code>, <code>'gb2312'</code>, <code>'gb_2312'</code>, <code>'gb_2312-80'</code>, <code>'iso-ir-58'</code>, <code>'x-gbk'</code></td></tr><tr><td><code>'gb18030'</code></td><td></td></tr><tr><td><code>'big5'</code></td><td><code>'big5-hkscs'</code>, <code>'cn-big5'</code>, <code>'csbig5'</code>, <code>'x-x-big5'</code></td></tr><tr><td><code>'euc-jp'</code></td><td><code>'cseucpkdfmtjapanese'</code>, <code>'x-euc-jp'</code></td></tr><tr><td><code>'iso-2022-jp'</code></td><td><code>'csiso2022jp'</code></td></tr><tr><td><code>'shift_jis'</code></td><td><code>'csshiftjis'</code>, <code>'ms932'</code>, <code>'ms_kanji'</code>, <code>'shift-jis'</code>, <code>'sjis'</code>, <code>'windows-31j'</code>, <code>'x-sjis'</code></td></tr><tr><td><code>'euc-kr'</code></td><td><code>'cseuckr'</code>, <code>'csksc56011987'</code>, <code>'iso-ir-149'</code>, <code>'korean'</code>, <code>'ks_c_5601-1987'</code>, <code>'ks_c_5601-1989'</code>, <code>'ksc5601'</code>, <code>'ksc_5601'</code>, <code>'windows-949'</code></td></tr></tbody></table>
<h5>Encodings supported when Node.js is built with the <code>small-icu</code> option<span><a class="mark" href="#all_util_encodings-supported-when-nodejs-is-built-with-the-small-icu-option" id="all_util_encodings-supported-when-nodejs-is-built-with-the-small-icu-option">#</a></span><a aria-hidden="true" class="legacy" id="util_encodings_supported_when_node_js_is_built_with_the_small_icu_option"></a></h5>
<table><thead><tr><th>Encoding</th><th>Aliases</th></tr></thead><tbody><tr><td><code>'utf-8'</code></td><td><code>'unicode-1-1-utf-8'</code>, <code>'utf8'</code></td></tr><tr><td><code>'utf-16le'</code></td><td><code>'utf-16'</code></td></tr><tr><td><code>'utf-16be'</code></td><td></td></tr></tbody></table>
<h5>Encodings supported when ICU is disabled<span><a class="mark" href="#all_util_encodings-supported-when-icu-is-disabled" id="all_util_encodings-supported-when-icu-is-disabled">#</a></span><a aria-hidden="true" class="legacy" id="util_encodings_supported_when_icu_is_disabled"></a></h5>
<table><thead><tr><th>Encoding</th><th>Aliases</th></tr></thead><tbody><tr><td><code>'utf-8'</code></td><td><code>'unicode-1-1-utf-8'</code>, <code>'utf8'</code></td></tr><tr><td><code>'utf-16le'</code></td><td><code>'utf-16'</code></td></tr></tbody></table>
<p>The <code>'iso-8859-16'</code> encoding listed in the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a>
is not supported.</p>
<h4><code>new TextDecoder([encoding[, options]])</code><span><a class="mark" href="#all_util_new-textdecoderencoding-options" id="all_util_new-textdecoderencoding-options">#</a></span><a aria-hidden="true" class="legacy" id="util_new_textdecoder_encoding_options"></a></h4>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Identifies the <code>encoding</code> that this <code>TextDecoder</code> instance
supports. <strong>Default:</strong> <code>'utf-8'</code>.</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>fatal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if decoding failures are fatal.
This option is not supported when ICU is disabled
(see <a href="intl.html">Internationalization</a>). <strong>Default:</strong> <code>false</code>.</li>
<li><code>ignoreBOM</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>TextDecoder</code> will include the byte
order mark in the decoded result. When <code>false</code>, the byte order mark will
be removed from the output. This option is only used when <code>encoding</code> is
<code>'utf-8'</code>, <code>'utf-16be'</code>, or <code>'utf-16le'</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>TextDecoder</code> instance. The <code>encoding</code> may specify one of the
supported encodings or an alias.</p>
<p>The <code>TextDecoder</code> class is also available on the global object.</p>
<h4><code>textDecoder.decode([input[, options]])</code><span><a class="mark" href="#all_util_textdecoderdecodeinput-options" id="all_util_textdecoderdecodeinput-options">#</a></span><a aria-hidden="true" class="legacy" id="util_textdecoder_decode_input_options"></a></h4>
<ul>
<li><code>input</code> <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/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> An <code>ArrayBuffer</code>, <code>DataView</code>, or
<code>TypedArray</code> instance containing the encoded 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>
<ul>
<li><code>stream</code> <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 are expected.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Decodes the <code>input</code> and returns a string. If <code>options.stream</code> is <code>true</code>, any
incomplete byte sequences occurring at the end of the <code>input</code> are buffered
internally and emitted after the next call to <code>textDecoder.decode()</code>.</p>
<p>If <code>textDecoder.fatal</code> is <code>true</code>, decoding errors that occur will result in a
<code>TypeError</code> being thrown.</p>
<h4><code>textDecoder.encoding</code><span><a class="mark" href="#all_util_textdecoderencoding" id="all_util_textdecoderencoding">#</a></span><a aria-hidden="true" class="legacy" id="util_textdecoder_encoding"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The encoding supported by the <code>TextDecoder</code> instance.</p>
<h4><code>textDecoder.fatal</code><span><a class="mark" href="#all_util_textdecoderfatal" id="all_util_textdecoderfatal">#</a></span><a aria-hidden="true" class="legacy" id="util_textdecoder_fatal"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>The value will be <code>true</code> if decoding errors result in a <code>TypeError</code> being
thrown.</p>
<h4><code>textDecoder.ignoreBOM</code><span><a class="mark" href="#all_util_textdecoderignorebom" id="all_util_textdecoderignorebom">#</a></span><a aria-hidden="true" class="legacy" id="util_textdecoder_ignorebom"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>The value will be <code>true</code> if the decoding result will include the byte order
mark.</p>
</section><section><h3>Class: <code>util.TextEncoder</code><span><a class="mark" href="#all_util_class-utiltextencoder" id="all_util_class-utiltextencoder">#</a></span><a aria-hidden="true" class="legacy" id="util_class_util_textencoder"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>The class is now available on the global object.</p></td></tr>
<tr><td>v8.3.0</td>
<td><p><span>Added in: v8.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An implementation of the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a> <code>TextEncoder</code> API. All
instances of <code>TextEncoder</code> only support UTF-8 encoding.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> encoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> uint8array = encoder.<span class="hljs-title function_">encode</span>(<span class="hljs-string">'this is some data'</span>);</code> <button class="copy-button">copy</button></pre>
<p>The <code>TextEncoder</code> class is also available on the global object.</p>
<h4><code>textEncoder.encode([input])</code><span><a class="mark" href="#all_util_textencoderencodeinput" id="all_util_textencoderencodeinput">#</a></span><a aria-hidden="true" class="legacy" id="util_textencoder_encode_input"></a></h4>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The text to encode. <strong>Default:</strong> an empty string.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li>
</ul>
<p>UTF-8 encodes the <code>input</code> string and returns a <code>Uint8Array</code> containing the
encoded bytes.</p>
<h4><code>textEncoder.encodeInto(src, dest)</code><span><a class="mark" href="#all_util_textencoderencodeintosrc-dest" id="all_util_textencoderencodeintosrc-dest">#</a></span><a aria-hidden="true" class="legacy" id="util_textencoder_encodeinto_src_dest"></a></h4>
<div class="api_metadata">
<span>Added in: v12.11.0</span>
</div>
<ul>
<li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The text to encode.</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> The array to hold the encode result.</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>read</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The read Unicode code units of src.</li>
<li><code>written</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The written UTF-8 bytes of dest.</li>
</ul>
</li>
</ul>
<p>UTF-8 encodes the <code>src</code> string to the <code>dest</code> Uint8Array and returns an object
containing the read Unicode code units and written UTF-8 bytes.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> encoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> src = <span class="hljs-string">'this is some data'</span>;
<span class="hljs-keyword">const</span> dest = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> { read, written } = encoder.<span class="hljs-title function_">encodeInto</span>(src, dest);</code> <button class="copy-button">copy</button></pre>
<h4><code>textEncoder.encoding</code><span><a class="mark" href="#all_util_textencoderencoding" id="all_util_textencoderencoding">#</a></span><a aria-hidden="true" class="legacy" id="util_textencoder_encoding"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The encoding supported by the <code>TextEncoder</code> instance. Always set to <code>'utf-8'</code>.</p>
</section><section><h3><code>util.toUSVString(string)</code><span><a class="mark" href="#all_util_utiltousvstringstring" id="all_util_utiltousvstringstring">#</a></span><a aria-hidden="true" class="legacy" id="util_util_tousvstring_string"></a></h3>
<div class="api_metadata">
<span>Added in: v16.8.0, v14.18.0</span>
</div>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Returns the <code>string</code> after replacing any surrogate code points
(or equivalently, any unpaired surrogate code units) with the
Unicode "replacement character" U+FFFD.</p>
</section><section><h3><code>util.transferableAbortController()</code><span><a class="mark" href="#all_util_utiltransferableabortcontroller" id="all_util_utiltransferableabortcontroller">#</a></span><a aria-hidden="true" class="legacy" id="util_util_transferableabortcontroller"></a></h3>
<div class="api_metadata">
<span>Added in: v18.11.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Creates and returns an <a href="#all_globals_class-abortcontroller" class="type"><AbortController></a> instance whose <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> is marked
as transferable and can be used with <code>structuredClone()</code> or <code>postMessage()</code>.</p>
</section><section><h3><code>util.transferableAbortSignal(signal)</code><span><a class="mark" href="#all_util_utiltransferableabortsignalsignal" id="all_util_utiltransferableabortsignalsignal">#</a></span><a aria-hidden="true" class="legacy" id="util_util_transferableabortsignal_signal"></a></h3>
<div class="api_metadata">
<span>Added in: v18.11.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a></li>
<li>Returns: <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a></li>
</ul>
<p>Marks the given <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> as transferable so that it can be used with
<code>structuredClone()</code> and <code>postMessage()</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> signal = <span class="hljs-title function_">transferableAbortSignal</span>(<span class="hljs-title class_">AbortSignal</span>.<span class="hljs-title function_">timeout</span>(<span class="hljs-number">100</span>));
<span class="hljs-keyword">const</span> channel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
channel.<span class="hljs-property">port2</span>.<span class="hljs-title function_">postMessage</span>(signal, [signal]);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.aborted(signal, resource)</code><span><a class="mark" href="#all_util_utilabortedsignal-resource" id="all_util_utilabortedsignal-resource">#</a></span><a aria-hidden="true" class="legacy" id="util_util_aborted_signal_resource"></a></h3>
<div class="api_metadata">
<span>Added in: v19.7.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a></li>
<li><code>resource</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Any non-null object tied to the abortable operation and held weakly.
If <code>resource</code> is garbage collected before the <code>signal</code> aborts, the promise remains pending,
allowing Node.js to stop tracking it.
This helps prevent memory leaks in long-running or non-cancelable operations.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Listens to abort event on the provided <code>signal</code> and returns a promise that resolves when the <code>signal</code> is aborted.
If <code>resource</code> is provided, it weakly references the operation's associated object,
so if <code>resource</code> is garbage collected before the <code>signal</code> aborts,
then returned promise shall remain pending.
This prevents memory leaks in long-running or non-cancelable operations.</p>
<pre class="with-41-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> { aborted } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-comment">// Obtain an object with an abortable signal, like a custom resource or operation.</span>
<span class="hljs-keyword">const</span> dependent = <span class="hljs-title function_">obtainSomethingAbortable</span>();
<span class="hljs-comment">// Pass `dependent` as the resource, indicating the promise should only resolve</span>
<span class="hljs-comment">// if `dependent` is still in memory when the signal is aborted.</span>
<span class="hljs-title function_">aborted</span>(dependent.<span class="hljs-property">signal</span>, dependent).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// This code runs when `dependent` is aborted.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Dependent resource was aborted.'</span>);
});
<span class="hljs-comment">// Simulate an event that triggers the abort.</span>
dependent.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
dependent.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// This will cause the `aborted` promise to resolve.</span>
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { aborted } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-comment">// Obtain an object with an abortable signal, like a custom resource or operation.</span>
<span class="hljs-keyword">const</span> dependent = <span class="hljs-title function_">obtainSomethingAbortable</span>();
<span class="hljs-comment">// Pass `dependent` as the resource, indicating the promise should only resolve</span>
<span class="hljs-comment">// if `dependent` is still in memory when the signal is aborted.</span>
<span class="hljs-title function_">aborted</span>(dependent.<span class="hljs-property">signal</span>, dependent).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
<span class="hljs-comment">// This code runs when `dependent` is aborted.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Dependent resource was aborted.'</span>);
});
<span class="hljs-comment">// Simulate an event that triggers the abort.</span>
dependent.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
dependent.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// This will cause the `aborted` promise to resolve.</span>
});</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>util.types</code><span><a class="mark" href="#all_util_utiltypes" id="all_util_utiltypes">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.3.0</td>
<td><p>Exposed as <code>require('util/types')</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>
<p><code>util.types</code> provides type checks for different kinds of built-in objects.
Unlike <code>instanceof</code> or <code>Object.prototype.toString.call(value)</code>, these checks do
not inspect properties of the object that are accessible from JavaScript (like
their prototype), and usually have the overhead of calling into C++.</p>
<p>The result generally does not make any guarantees about what kinds of
properties or behavior a value exposes in JavaScript. They are primarily
useful for addon developers who prefer to do type checking in JavaScript.</p>
<p>The API is accessible via <code>require('node:util').types</code> or <code>require('node:util/types')</code>.</p>
<h4><code>util.types.isAnyArrayBuffer(value)</code><span><a class="mark" href="#all_util_utiltypesisanyarraybuffervalue" id="all_util_utiltypesisanyarraybuffervalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isanyarraybuffer_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> or
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instance.</p>
<p>See also <a href="#all_util_utiltypesisarraybuffervalue"><code>util.types.isArrayBuffer()</code></a> and
<a href="#all_util_utiltypesissharedarraybuffervalue"><code>util.types.isSharedArrayBuffer()</code></a>.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isAnyArrayBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isAnyArrayBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">SharedArrayBuffer</span>()); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isArrayBufferView(value)</code><span><a class="mark" href="#all_util_utiltypesisarraybufferviewvalue" id="all_util_utiltypesisarraybufferviewvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isarraybufferview_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an instance of one of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>
views, such as typed array objects or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView"><code>DataView</code></a>. Equivalent to
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView"><code>ArrayBuffer.isView()</code></a>.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArrayBufferView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Int8Array</span>()); <span class="hljs-comment">// true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArrayBufferView</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello world'</span>)); <span class="hljs-comment">// true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArrayBufferView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">DataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">16</span>))); <span class="hljs-comment">// true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArrayBufferView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isArgumentsObject(value)</code><span><a class="mark" href="#all_util_utiltypesisargumentsobjectvalue" id="all_util_utiltypesisargumentsobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isargumentsobject_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an <code>arguments</code> object.</p>
<!-- eslint-disable prefer-rest-params -->
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArgumentsObject</span>(<span class="hljs-variable language_">arguments</span>); <span class="hljs-comment">// Returns true</span>
}</code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isArrayBuffer(value)</code><span><a class="mark" href="#all_util_utiltypesisarraybuffervalue" id="all_util_utiltypesisarraybuffervalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isarraybuffer_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> instance.
This does <em>not</em> include <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instances. Usually, it is
desirable to test for both; See <a href="#all_util_utiltypesisanyarraybuffervalue"><code>util.types.isAnyArrayBuffer()</code></a> for that.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArrayBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArrayBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">SharedArrayBuffer</span>()); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isAsyncFunction(value)</code><span><a class="mark" href="#all_util_utiltypesisasyncfunctionvalue" id="all_util_utiltypesisasyncfunctionvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isasyncfunction_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async function</a>.
This only reports back what the JavaScript engine is seeing;
in particular, the return value may not match the original source code if
a transpilation tool was used.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isAsyncFunction</span>(<span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {}); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isAsyncFunction</span>(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {}); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isBigInt64Array(value)</code><span><a class="mark" href="#all_util_utiltypesisbigint64arrayvalue" id="all_util_utiltypesisbigint64arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isbigint64array_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a <code>BigInt64Array</code> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBigInt64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">BigInt64Array</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBigInt64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">BigUint64Array</span>()); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isBigIntObject(value)</code><span><a class="mark" href="#all_util_utiltypesisbigintobjectvalue" id="all_util_utiltypesisbigintobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isbigintobject_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.4.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a BigInt object, e.g. created
by <code>Object(BigInt(123))</code>.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBigIntObject</span>(<span class="hljs-title class_">Object</span>(<span class="hljs-title class_">BigInt</span>(<span class="hljs-number">123</span>))); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBigIntObject</span>(<span class="hljs-title class_">BigInt</span>(<span class="hljs-number">123</span>)); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBigIntObject</span>(<span class="hljs-number">123</span>); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isBigUint64Array(value)</code><span><a class="mark" href="#all_util_utiltypesisbiguint64arrayvalue" id="all_util_utiltypesisbiguint64arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isbiguint64array_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a <code>BigUint64Array</code> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBigUint64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">BigInt64Array</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBigUint64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">BigUint64Array</span>()); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isBooleanObject(value)</code><span><a class="mark" href="#all_util_utiltypesisbooleanobjectvalue" id="all_util_utiltypesisbooleanobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isbooleanobject_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a boolean object, e.g. created
by <code>new Boolean()</code>.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBooleanObject</span>(<span class="hljs-literal">false</span>); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBooleanObject</span>(<span class="hljs-literal">true</span>); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBooleanObject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Boolean</span>(<span class="hljs-literal">false</span>)); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBooleanObject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Boolean</span>(<span class="hljs-literal">true</span>)); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBooleanObject</span>(<span class="hljs-title class_">Boolean</span>(<span class="hljs-literal">false</span>)); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBooleanObject</span>(<span class="hljs-title class_">Boolean</span>(<span class="hljs-literal">true</span>)); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isBoxedPrimitive(value)</code><span><a class="mark" href="#all_util_utiltypesisboxedprimitivevalue" id="all_util_utiltypesisboxedprimitivevalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isboxedprimitive_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.11.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is any boxed primitive object, e.g. created
by <code>new Boolean()</code>, <code>new String()</code> or <code>Object(Symbol())</code>.</p>
<p>For example:</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBoxedPrimitive</span>(<span class="hljs-literal">false</span>); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBoxedPrimitive</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Boolean</span>(<span class="hljs-literal">false</span>)); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBoxedPrimitive</span>(<span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBoxedPrimitive</span>(<span class="hljs-title class_">Object</span>(<span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'foo'</span>))); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBoxedPrimitive</span>(<span class="hljs-title class_">Object</span>(<span class="hljs-title class_">BigInt</span>(<span class="hljs-number">5</span>))); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isCryptoKey(value)</code><span><a class="mark" href="#all_util_utiltypesiscryptokeyvalue" id="all_util_utiltypesiscryptokeyvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_iscryptokey_value"></a></h4>
<div class="api_metadata">
<span>Added in: v16.2.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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 <code>true</code> if <code>value</code> is a <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>, <code>false</code> otherwise.</p>
<h4><code>util.types.isDataView(value)</code><span><a class="mark" href="#all_util_utiltypesisdataviewvalue" id="all_util_utiltypesisdataviewvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isdataview_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView"><code>DataView</code></a> instance.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">20</span>);
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isDataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">DataView</span>(ab)); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isDataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>()); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<p>See also <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView"><code>ArrayBuffer.isView()</code></a>.</p>
<h4><code>util.types.isDate(value)</code><span><a class="mark" href="#all_util_utiltypesisdatevalue" id="all_util_utiltypesisdatevalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isdate_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date"><code>Date</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isDate</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>()); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isExternal(value)</code><span><a class="mark" href="#all_util_utiltypesisexternalvalue" id="all_util_utiltypesisexternalvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isexternal_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a native <code>External</code> value.</p>
<p>A native <code>External</code> value is a special type of object that contains a
raw C++ pointer (<code>void*</code>) for access from native code, and has no other
properties. Such objects are created either by Node.js internals or native
addons. In JavaScript, they are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze">frozen</a> objects with a
<code>null</code> prototype.</p>
<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><js_native_api.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><stdlib.h></span></span>
napi_value result;
<span class="hljs-type">static</span> napi_value <span class="hljs-title function_">MyNapi</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
<span class="hljs-type">int</span>* raw = (<span class="hljs-type">int</span>*) <span class="hljs-built_in">malloc</span>(<span class="hljs-number">1024</span>);
napi_status status = napi_create_external(env, (<span class="hljs-type">void</span>*) raw, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, &result);
<span class="hljs-keyword">if</span> (status != napi_ok) {
napi_throw_error(env, <span class="hljs-literal">NULL</span>, <span class="hljs-string">"napi_create_external failed"</span>);
<span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
}
<span class="hljs-keyword">return</span> result;
}
...
DECLARE_NAPI_PROPERTY(<span class="hljs-string">"myNapi"</span>, MyNapi)
...</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">const</span> native = <span class="hljs-built_in">require</span>(<span class="hljs-string">'napi_addon.node'</span>);
<span class="hljs-keyword">const</span> data = native.<span class="hljs-title function_">myNapi</span>();
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isExternal</span>(data); <span class="hljs-comment">// returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isExternal</span>(<span class="hljs-number">0</span>); <span class="hljs-comment">// returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isExternal</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// returns false</span></code> <button class="copy-button">copy</button></pre>
<p>For further information on <code>napi_create_external</code>, refer to
<a href="#all_n-api_napi_create_external"><code>napi_create_external()</code></a>.</p>
<h4><code>util.types.isFloat32Array(value)</code><span><a class="mark" href="#all_util_utiltypesisfloat32arrayvalue" id="all_util_utiltypesisfloat32arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isfloat32array_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array"><code>Float32Array</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isFloat32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isFloat32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float32Array</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isFloat32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>()); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isFloat64Array(value)</code><span><a class="mark" href="#all_util_utiltypesisfloat64arrayvalue" id="all_util_utiltypesisfloat64arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isfloat64array_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array"><code>Float64Array</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isFloat64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isFloat64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isFloat64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>()); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isGeneratorFunction(value)</code><span><a class="mark" href="#all_util_utiltypesisgeneratorfunctionvalue" id="all_util_utiltypesisgeneratorfunctionvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isgeneratorfunction_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a generator function.
This only reports back what the JavaScript engine is seeing;
in particular, the return value may not match the original source code if
a transpilation tool was used.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isGeneratorFunction</span>(<span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {}); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isGeneratorFunction</span>(<span class="hljs-keyword">function</span>* <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {}); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isGeneratorObject(value)</code><span><a class="mark" href="#all_util_utiltypesisgeneratorobjectvalue" id="all_util_utiltypesisgeneratorobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isgeneratorobject_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a generator object as returned from a
built-in generator function.
This only reports back what the JavaScript engine is seeing;
in particular, the return value may not match the original source code if
a transpilation tool was used.</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span>* <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {}
<span class="hljs-keyword">const</span> generator = <span class="hljs-title function_">foo</span>();
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isGeneratorObject</span>(generator); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isInt8Array(value)</code><span><a class="mark" href="#all_util_utiltypesisint8arrayvalue" id="all_util_utiltypesisint8arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isint8array_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array"><code>Int8Array</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Int8Array</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>()); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isInt16Array(value)</code><span><a class="mark" href="#all_util_utiltypesisint16arrayvalue" id="all_util_utiltypesisint16arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isint16array_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array"><code>Int16Array</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt16Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt16Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Int16Array</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt16Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>()); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isInt32Array(value)</code><span><a class="mark" href="#all_util_utiltypesisint32arrayvalue" id="all_util_utiltypesisint32arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isint32array_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array"><code>Int32Array</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Int32Array</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>()); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isKeyObject(value)</code><span><a class="mark" href="#all_util_utiltypesiskeyobjectvalue" id="all_util_utiltypesiskeyobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_iskeyobject_value"></a></h4>
<div class="api_metadata">
<span>Added in: v16.2.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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 <code>true</code> if <code>value</code> is a <a href="#all_crypto_class-keyobject" class="type"><KeyObject></a>, <code>false</code> otherwise.</p>
<h4><code>util.types.isMap(value)</code><span><a class="mark" href="#all_util_utiltypesismapvalue" id="all_util_utiltypesismapvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_ismap_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isMap</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>()); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isMapIterator(value)</code><span><a class="mark" href="#all_util_utiltypesismapiteratorvalue" id="all_util_utiltypesismapiteratorvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_ismapiterator_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an iterator returned for a built-in
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a> instance.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isMapIterator</span>(map.<span class="hljs-title function_">keys</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isMapIterator</span>(map.<span class="hljs-title function_">values</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isMapIterator</span>(map.<span class="hljs-title function_">entries</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isMapIterator</span>(map[<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">iterator</span>]()); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isModuleNamespaceObject(value)</code><span><a class="mark" href="#all_util_utiltypesismodulenamespaceobjectvalue" id="all_util_utiltypesismodulenamespaceobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_ismodulenamespaceobject_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an instance of a <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects">Module Namespace Object</a>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> ns <span class="hljs-keyword">from</span> <span class="hljs-string">'./a.js'</span>;
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isModuleNamespaceObject</span>(ns); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isNativeError(value)</code><span><a class="mark" href="#all_util_utiltypesisnativeerrorvalue" id="all_util_utiltypesisnativeerrorvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isnativeerror_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value was returned by the constructor of a
<a href="https://tc39.es/ecma262/#sec-error-objects">built-in <code>Error</code> type</a>.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNativeError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>())); <span class="hljs-comment">// true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNativeError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>())); <span class="hljs-comment">// true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNativeError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">RangeError</span>())); <span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></pre>
<p>Subclasses of the native error types are also native errors:</p>
<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">MyError</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Error</span> {}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNativeError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">MyError</span>())); <span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></pre>
<p>A value being <code>instanceof</code> a native error class is not equivalent to <code>isNativeError()</code>
returning <code>true</code> for that value. <code>isNativeError()</code> returns <code>true</code> for errors
which come from a different <a href="https://tc39.es/ecma262/#realm">realm</a> while <code>instanceof Error</code> returns <code>false</code>
for these errors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>({});
<span class="hljs-keyword">const</span> myError = vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'new Error()'</span>, context);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNativeError</span>(myError)); <span class="hljs-comment">// true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myError <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Error</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<p>Conversely, <code>isNativeError()</code> returns <code>false</code> for all objects which were not
returned by the constructor of a native error. That includes values
which are <code>instanceof</code> native errors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myError = { <span class="hljs-attr">__proto__</span>: <span class="hljs-title class_">Error</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span> };
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNativeError</span>(myError)); <span class="hljs-comment">// false</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myError <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Error</span>); <span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isNumberObject(value)</code><span><a class="mark" href="#all_util_utiltypesisnumberobjectvalue" id="all_util_utiltypesisnumberobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isnumberobject_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a number object, e.g. created
by <code>new Number()</code>.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNumberObject</span>(<span class="hljs-number">0</span>); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNumberObject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Number</span>(<span class="hljs-number">0</span>)); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isPromise(value)</code><span><a class="mark" href="#all_util_utiltypesispromisevalue" id="all_util_utiltypesispromisevalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_ispromise_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><code>Promise</code></a>.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isPromise</span>(<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">42</span>)); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isProxy(value)</code><span><a class="mark" href="#all_util_utiltypesisproxyvalue" id="all_util_utiltypesisproxyvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isproxy_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy"><code>Proxy</code></a> instance.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> target = {};
<span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(target, {});
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isProxy</span>(target); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isProxy</span>(proxy); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isRegExp(value)</code><span><a class="mark" href="#all_util_utiltypesisregexpvalue" id="all_util_utiltypesisregexpvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isregexp_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a regular expression object.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isRegExp</span>(<span class="hljs-regexp">/abc/</span>); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isRegExp</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">RegExp</span>(<span class="hljs-string">'abc'</span>)); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isSet(value)</code><span><a class="mark" href="#all_util_utiltypesissetvalue" id="all_util_utiltypesissetvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isset_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSet</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>()); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isSetIterator(value)</code><span><a class="mark" href="#all_util_utiltypesissetiteratorvalue" id="all_util_utiltypesissetiteratorvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_issetiterator_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an iterator returned for a built-in
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a> instance.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> set = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>();
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSetIterator</span>(set.<span class="hljs-title function_">keys</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSetIterator</span>(set.<span class="hljs-title function_">values</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSetIterator</span>(set.<span class="hljs-title function_">entries</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSetIterator</span>(set[<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">iterator</span>]()); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isSharedArrayBuffer(value)</code><span><a class="mark" href="#all_util_utiltypesissharedarraybuffervalue" id="all_util_utiltypesissharedarraybuffervalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_issharedarraybuffer_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instance.
This does <em>not</em> include <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> instances. Usually, it is
desirable to test for both; See <a href="#all_util_utiltypesisanyarraybuffervalue"><code>util.types.isAnyArrayBuffer()</code></a> for that.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSharedArrayBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSharedArrayBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">SharedArrayBuffer</span>()); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isStringObject(value)</code><span><a class="mark" href="#all_util_utiltypesisstringobjectvalue" id="all_util_utiltypesisstringobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isstringobject_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a string object, e.g. created
by <code>new String()</code>.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isStringObject</span>(<span class="hljs-string">'foo'</span>); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isStringObject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isSymbolObject(value)</code><span><a class="mark" href="#all_util_utiltypesissymbolobjectvalue" id="all_util_utiltypesissymbolobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_issymbolobject_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a symbol object, created
by calling <code>Object()</code> on a <code>Symbol</code> primitive.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> symbol = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'foo'</span>);
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSymbolObject</span>(symbol); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSymbolObject</span>(<span class="hljs-title class_">Object</span>(symbol)); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isTypedArray(value)</code><span><a class="mark" href="#all_util_utiltypesistypedarrayvalue" id="all_util_utiltypesistypedarrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_istypedarray_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isTypedArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isTypedArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isTypedArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>()); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<p>See also <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView"><code>ArrayBuffer.isView()</code></a>.</p>
<h4><code>util.types.isUint8Array(value)</code><span><a class="mark" href="#all_util_utiltypesisuint8arrayvalue" id="all_util_utiltypesisuint8arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isuint8array_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>()); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isUint8ClampedArray(value)</code><span><a class="mark" href="#all_util_utiltypesisuint8clampedarrayvalue" id="all_util_utiltypesisuint8clampedarrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isuint8clampedarray_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray"><code>Uint8ClampedArray</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint8ClampedArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint8ClampedArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8ClampedArray</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint8ClampedArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>()); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isUint16Array(value)</code><span><a class="mark" href="#all_util_utiltypesisuint16arrayvalue" id="all_util_utiltypesisuint16arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isuint16array_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array"><code>Uint16Array</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint16Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint16Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint16Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>()); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isUint32Array(value)</code><span><a class="mark" href="#all_util_utiltypesisuint32arrayvalue" id="all_util_utiltypesisuint32arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isuint32array_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array"><code>Uint32Array</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>()); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>()); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>()); <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isWeakMap(value)</code><span><a class="mark" href="#all_util_utiltypesisweakmapvalue" id="all_util_utiltypesisweakmapvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isweakmap_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isWeakMap</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>()); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isWeakSet(value)</code><span><a class="mark" href="#all_util_utiltypesisweaksetvalue" id="all_util_utiltypesisweaksetvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isweakset_value"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> instance.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isWeakSet</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakSet</span>()); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3>Deprecated APIs<span><a class="mark" href="#all_util_deprecated-apis" id="all_util_deprecated-apis">#</a></span><a aria-hidden="true" class="legacy" id="util_deprecated_apis"></a></h3>
<p>The following APIs are deprecated and should no longer be used. Existing
applications and modules should be updated to find alternative approaches.</p>
<h4><code>util._extend(target, source)</code><span><a class="mark" href="#all_util_util_extendtarget-source" id="all_util_util_extendtarget-source">#</a></span><a aria-hidden="true" class="legacy" id="util_util_extend_target_source"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.5</span><span>Deprecated since: v6.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign"><code>Object.assign()</code></a> instead.</div><p></p>
<ul>
<li><code>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>source</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The <code>util._extend()</code> method was never intended to be used outside of internal
Node.js modules. The community found and used it anyway.</p>
<p>It is deprecated and should not be used in new code. JavaScript comes with very
similar built-in functionality through <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign"><code>Object.assign()</code></a>.</p>
<h4><code>util.isArray(object)</code><span><a class="mark" href="#all_util_utilisarrayobject" id="all_util_utilisarrayobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isarray_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.6.0</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray"><code>Array.isArray()</code></a> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Alias for <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray"><code>Array.isArray()</code></a>.</p>
<p>Returns <code>true</code> if the given <code>object</code> is an <code>Array</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isArray</span>([]);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Array</span>());
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isArray</span>({});
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isBoolean(object)</code><span><a class="mark" href="#all_util_utilisbooleanobject" id="all_util_utilisbooleanobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isboolean_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'boolean'</code> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>Boolean</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isBoolean</span>(<span class="hljs-number">1</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isBoolean</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isBoolean</span>(<span class="hljs-literal">false</span>);
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isBuffer(object)</code><span><a class="mark" href="#all_util_utilisbufferobject" id="all_util_utilisbufferobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isbuffer_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_static-method-bufferisbufferobj"><code>Buffer.isBuffer()</code></a> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>Buffer</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isBuffer</span>({ <span class="hljs-attr">length</span>: <span class="hljs-number">0</span> });
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isBuffer</span>([]);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello world'</span>));
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isDate(object)</code><span><a class="mark" href="#all_util_utilisdateobject" id="all_util_utilisdateobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isdate_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.6.0</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_util_utiltypesisdatevalue"><code>util.types.isDate()</code></a> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>Date</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isDate</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>());
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isDate</span>(<span class="hljs-title class_">Date</span>());
<span class="hljs-comment">// false (without 'new' returns a String)</span>
util.<span class="hljs-title function_">isDate</span>({});
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isError(object)</code><span><a class="mark" href="#all_util_utiliserrorobject" id="all_util_utiliserrorobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_iserror_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.6.0</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_util_utiltypesisnativeerrorvalue"><code>util.types.isNativeError()</code></a> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is an <a href="#all_errors_class-error"><code>Error</code></a>. Otherwise, returns
<code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>());
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>());
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isError</span>({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Error'</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">'an error occurred'</span> });
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<p>This method relies on <code>Object.prototype.toString()</code> behavior. It is
possible to obtain an incorrect result when the <code>object</code> argument manipulates
<code>@@toStringTag</code>.</p>
<pre><code class="language-js"><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">const</span> obj = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Error'</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">'an error occurred'</span> };
util.<span class="hljs-title function_">isError</span>(obj);
<span class="hljs-comment">// Returns: false</span>
obj[<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">toStringTag</span>] = <span class="hljs-string">'Error'</span>;
util.<span class="hljs-title function_">isError</span>(obj);
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isFunction(object)</code><span><a class="mark" href="#all_util_utilisfunctionobject" id="all_util_utilisfunctionobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isfunction_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'function'</code> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>Function</code>. Otherwise, returns
<code>false</code>.</p>
<pre><code class="language-js"><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_">Foo</span>(<span class="hljs-params"></span>) {}
<span class="hljs-keyword">const</span> <span class="hljs-title function_">Bar</span> = (<span class="hljs-params"></span>) => {};
util.<span class="hljs-title function_">isFunction</span>({});
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isFunction</span>(<span class="hljs-title class_">Foo</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isFunction</span>(<span class="hljs-title class_">Bar</span>);
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isNull(object)</code><span><a class="mark" href="#all_util_utilisnullobject" id="all_util_utilisnullobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isnull_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <code>value === null</code> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is strictly <code>null</code>. Otherwise, returns
<code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isNull</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isNull</span>(<span class="hljs-literal">undefined</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isNull</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isNullOrUndefined(object)</code><span><a class="mark" href="#all_util_utilisnullorundefinedobject" id="all_util_utilisnullorundefinedobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isnullorundefined_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use
<code>value === undefined || value === null</code> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is <code>null</code> or <code>undefined</code>. Otherwise,
returns <code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isNullOrUndefined</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isNullOrUndefined</span>(<span class="hljs-literal">undefined</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isNullOrUndefined</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isNumber(object)</code><span><a class="mark" href="#all_util_utilisnumberobject" id="all_util_utilisnumberobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isnumber_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'number'</code> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>Number</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isNumber</span>(<span class="hljs-literal">false</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isNumber</span>(<span class="hljs-title class_">Infinity</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isNumber</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isNumber</span>(<span class="hljs-title class_">NaN</span>);
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isObject(object)</code><span><a class="mark" href="#all_util_utilisobjectobject" id="all_util_utilisobjectobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isobject_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated:
Use <code>value !== null && typeof value === 'object'</code> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is strictly an <code>Object</code> <strong>and</strong> not a
<code>Function</code> (even though functions are objects in JavaScript).
Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isObject</span>(<span class="hljs-number">5</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isObject</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isObject</span>({});
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isObject</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isPrimitive(object)</code><span><a class="mark" href="#all_util_utilisprimitiveobject" id="all_util_utilisprimitiveobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isprimitive_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use
<code>(typeof value !== 'object' && typeof value !== 'function') || value === null</code>
instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a primitive type. Otherwise, returns
<code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-number">5</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-literal">false</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-literal">undefined</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isPrimitive</span>({});
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-regexp">/^$/</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>());
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isRegExp(object)</code><span><a class="mark" href="#all_util_utilisregexpobject" id="all_util_utilisregexpobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isregexp_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.6.0</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>RegExp</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isRegExp</span>(<span class="hljs-regexp">/some regexp/</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isRegExp</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">RegExp</span>(<span class="hljs-string">'another regexp'</span>));
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isRegExp</span>({});
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isString(object)</code><span><a class="mark" href="#all_util_utilisstringobject" id="all_util_utilisstringobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isstring_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'string'</code> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>string</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isString</span>(<span class="hljs-string">''</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isString</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isString</span>(<span class="hljs-title class_">String</span>(<span class="hljs-string">'foo'</span>));
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isString</span>(<span class="hljs-number">5</span>);
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isSymbol(object)</code><span><a class="mark" href="#all_util_utilissymbolobject" id="all_util_utilissymbolobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_issymbol_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'symbol'</code> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>Symbol</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">isSymbol</span>(<span class="hljs-number">5</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isSymbol</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isSymbol</span>(<span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'foo'</span>));
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isUndefined(object)</code><span><a class="mark" href="#all_util_utilisundefinedobject" id="all_util_utilisundefinedobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isundefined_object"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <code>value === undefined</code> instead.</div><p></p>
<ul>
<li><code>object</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#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is <code>undefined</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js"><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">const</span> foo = <span class="hljs-literal">undefined</span>;
util.<span class="hljs-title function_">isUndefined</span>(<span class="hljs-number">5</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isUndefined</span>(foo);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isUndefined</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.log(string)</code><span><a class="mark" href="#all_util_utillogstring" id="all_util_utillogstring">#</a></span><a aria-hidden="true" class="legacy" id="util_util_log_string"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span><span>Deprecated since: v6.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use a third party module instead.</div><p></p>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>util.log()</code> method prints the given <code>string</code> to <code>stdout</code> with an included
timestamp.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
util.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Timestamped message.'</span>);</code> <button class="copy-button">copy</button></pre></section>
</section>
<section><h2>V8<span><a class="mark" href="#all_v8_v8" id="all_v8_v8">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8"></a></h2>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/v8.js">lib/v8.js</a></p>
<p>The <code>node:v8</code> module exposes APIs that are specific to the version of <a href="https://developers.google.com/v8/">V8</a>
built into the Node.js binary. It can be accessed using:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> v8 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);</code> <button class="copy-button">copy</button></pre>
<section><h3><code>v8.cachedDataVersionTag()</code><span><a class="mark" href="#all_v8_v8cacheddataversiontag" id="all_v8_v8cacheddataversiontag">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_cacheddataversiontag"></a></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<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 an integer representing a version tag derived from the V8 version,
command-line flags, and detected CPU features. This is useful for determining
whether a <a href="#all_vm_new-vmscriptcode-options"><code>vm.Script</code></a> <code>cachedData</code> buffer is compatible with this instance
of V8.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(v8.<span class="hljs-title function_">cachedDataVersionTag</span>()); <span class="hljs-comment">// 3947234607</span>
<span class="hljs-comment">// The value returned by v8.cachedDataVersionTag() is derived from the V8</span>
<span class="hljs-comment">// version, command-line flags, and detected CPU features. Test that the value</span>
<span class="hljs-comment">// does indeed update when flags are toggled.</span>
v8.<span class="hljs-title function_">setFlagsFromString</span>(<span class="hljs-string">'--allow_natives_syntax'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(v8.<span class="hljs-title function_">cachedDataVersionTag</span>()); <span class="hljs-comment">// 183726201</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.getHeapCodeStatistics()</code><span><a class="mark" href="#all_v8_v8getheapcodestatistics" id="all_v8_v8getheapcodestatistics">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_getheapcodestatistics"></a></h3>
<div class="api_metadata">
<span>Added in: v12.8.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Get statistics about code and its metadata in the heap, see V8
<a href="https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866"><code>GetHeapCodeAndMetadataStatistics</code></a> API. Returns an object with the
following properties:</p>
<ul>
<li><code>code_and_metadata_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>bytecode_and_metadata_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>external_script_source_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>cpu_profiler_metadata_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
<span class="hljs-attr">code_and_metadata_size</span>: <span class="hljs-number">212208</span>,
<span class="hljs-attr">bytecode_and_metadata_size</span>: <span class="hljs-number">161368</span>,
<span class="hljs-attr">external_script_source_size</span>: <span class="hljs-number">1410794</span>,
<span class="hljs-attr">cpu_profiler_metadata_size</span>: <span class="hljs-number">0</span>,
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.getHeapSnapshot([options])</code><span><a class="mark" href="#all_v8_v8getheapsnapshotoptions" id="all_v8_v8getheapsnapshotoptions">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_getheapsnapshot_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.1.0</td>
<td><p>Support options to configure the heap snapshot.</p></td></tr>
<tr><td>v11.13.0</td>
<td><p><span>Added in: v11.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p>
<ul>
<li><code>exposeInternals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If true, expose internals in the heap snapshot.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>exposeNumericValues</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If true, expose numeric values in
artificial fields. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>
<p>Returns: <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a> A Readable containing the V8 heap snapshot.</p>
</li>
</ul>
<p>Generates a snapshot of the current V8 heap and returns a Readable
Stream that may be used to read the JSON serialized representation.
This JSON stream format is intended to be used with tools such as
Chrome DevTools. The JSON schema is undocumented and specific to the
V8 engine. Therefore, the schema may change from one version of V8 to the next.</p>
<p>Creating a heap snapshot requires memory about twice the size of the heap at
the time the snapshot is created. This results in the risk of OOM killers
terminating the process.</p>
<p>Generating a snapshot is a synchronous operation which blocks the event loop
for a duration depending on the heap size.</p>
<pre><code class="language-js"><span class="hljs-comment">// Print heap snapshot to the console</span>
<span class="hljs-keyword">const</span> v8 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
<span class="hljs-keyword">const</span> stream = v8.<span class="hljs-title function_">getHeapSnapshot</span>();
stream.<span class="hljs-title function_">pipe</span>(process.<span class="hljs-property">stdout</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.getHeapSpaceStatistics()</code><span><a class="mark" href="#all_v8_v8getheapspacestatistics" id="all_v8_v8getheapspacestatistics">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_getheapspacestatistics"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.5.0</td>
<td><p>Support values exceeding the 32-bit unsigned integer range.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Added in: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li>
</ul>
<p>Returns statistics about the V8 heap spaces, i.e. the segments which make up
the V8 heap. Neither the ordering of heap spaces, nor the availability of a
heap space can be guaranteed as the statistics are provided via the V8
<a href="https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4"><code>GetHeapSpaceStatistics</code></a> function and may change from one V8 version to the
next.</p>
<p>The value returned is an array of objects containing the following properties:</p>
<ul>
<li><code>space_name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>space_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>space_used_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>space_available_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>physical_space_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<pre><code class="language-json"><span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"space_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"new_space"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2063872</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_used_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">951112</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_available_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">80824</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"physical_space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2063872</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"space_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"old_space"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3090560</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_used_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2493792</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_available_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"physical_space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3090560</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"space_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"code_space"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1260160</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_used_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">644256</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_available_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">960</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"physical_space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1260160</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"space_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"map_space"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1094160</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_used_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">201608</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_available_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"physical_space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1094160</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"space_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"large_object_space"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_used_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"space_available_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1490980608</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"physical_space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.getHeapStatistics()</code><span><a class="mark" href="#all_v8_v8getheapstatistics" id="all_v8_v8getheapstatistics">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_getheapstatistics"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.5.0</td>
<td><p>Support values exceeding the 32-bit unsigned integer range.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>Added <code>malloced_memory</code>, <code>peak_malloced_memory</code>, and <code>does_zap_garbage</code>.</p></td></tr>
<tr><td>v1.0.0</td>
<td><p><span>Added in: v1.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns an object with the following properties:</p>
<ul>
<li><code>total_heap_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>total_heap_size_executable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>total_physical_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>total_available_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>used_heap_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>heap_size_limit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>malloced_memory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>peak_malloced_memory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>does_zap_garbage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>number_of_native_contexts</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>number_of_detached_contexts</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>total_global_handles_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>used_global_handles_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>external_memory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p><code>total_heap_size</code> The value of total_heap_size is the number of bytes V8 has
allocated for the heap. This can grow if used_heap needs more memory.</p>
<p><code>total_heap_size_executable</code> The value of total_heap_size_executable is the
portion of the heap that can contain executable code, in bytes. This includes
memory used by JIT-compiled code and any memory that must be kept executable.</p>
<p><code>total_physical_size</code> The value of total_physical_size is the actual physical memory
used by the V8 heap, in bytes. This is the amount of memory that is committed
(or in use) rather than reserved.</p>
<p><code>total_available_size</code> The value of total_available_size is the number of
bytes of memory available to the V8 heap. This value represents how much
more memory V8 can use before it exceeds the heap limit.</p>
<p><code>used_heap_size</code> The value of used_heap_size is number of bytes currently
being used by V8’s JavaScript objects. This is the actual memory in use and
does not include memory that has been allocated but not yet used.</p>
<p><code>heap_size_limit</code> The value of heap_size_limit is the maximum size of the V8
heap, in bytes (either the default limit, determined by system resources, or
the value passed to the <code>--max_old_space_size</code> option).</p>
<p><code>malloced_memory</code> The value of malloced_memory is the number of bytes allocated
through <code>malloc</code> by V8.</p>
<p><code>peak_malloced_memory</code> The value of peak_malloced_memory is the peak number of
bytes allocated through <code>malloc</code> by V8 during the lifetime of the process.</p>
<p><code>does_zap_garbage</code> is a 0/1 boolean, which signifies whether the
<code>--zap_code_space</code> option is enabled or not. This makes V8 overwrite heap
garbage with a bit pattern. The RSS footprint (resident set size) gets bigger
because it continuously touches all heap pages and that makes them less likely
to get swapped out by the operating system.</p>
<p><code>number_of_native_contexts</code> The value of native_context is the number of the
top-level contexts currently active. Increase of this number over time indicates
a memory leak.</p>
<p><code>number_of_detached_contexts</code> The value of detached_context is the number
of contexts that were detached and not yet garbage collected. This number
being non-zero indicates a potential memory leak.</p>
<p><code>total_global_handles_size</code> The value of total_global_handles_size is the
total memory size of V8 global handles.</p>
<p><code>used_global_handles_size</code> The value of used_global_handles_size is the
used memory size of V8 global handles.</p>
<p><code>external_memory</code> The value of external_memory is the memory size of array
buffers and external strings.</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
<span class="hljs-attr">total_heap_size</span>: <span class="hljs-number">7326976</span>,
<span class="hljs-attr">total_heap_size_executable</span>: <span class="hljs-number">4194304</span>,
<span class="hljs-attr">total_physical_size</span>: <span class="hljs-number">7326976</span>,
<span class="hljs-attr">total_available_size</span>: <span class="hljs-number">1152656</span>,
<span class="hljs-attr">used_heap_size</span>: <span class="hljs-number">3476208</span>,
<span class="hljs-attr">heap_size_limit</span>: <span class="hljs-number">1535115264</span>,
<span class="hljs-attr">malloced_memory</span>: <span class="hljs-number">16384</span>,
<span class="hljs-attr">peak_malloced_memory</span>: <span class="hljs-number">1127496</span>,
<span class="hljs-attr">does_zap_garbage</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">number_of_native_contexts</span>: <span class="hljs-number">1</span>,
<span class="hljs-attr">number_of_detached_contexts</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">total_global_handles_size</span>: <span class="hljs-number">8192</span>,
<span class="hljs-attr">used_global_handles_size</span>: <span class="hljs-number">3296</span>,
<span class="hljs-attr">external_memory</span>: <span class="hljs-number">318824</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.queryObjects(ctor[, options])</code><span><a class="mark" href="#all_v8_v8queryobjectsctor-options" id="all_v8_v8queryobjectsctor-options">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_queryobjects_ctor_options"></a></h3>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<ul>
<li><code>ctor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The constructor that can be used to search on the
prototype chain in order to filter target objects in the heap.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If it's <code>'count'</code>, the count of matched objects
is returned. If it's <code>'summary'</code>, an array with summary strings
of the matched objects is returned.</li>
</ul>
</li>
<li>Returns: {number|Array<string>}</string></li>
</ul>
<p>This is similar to the <a href="https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function"><code>queryObjects()</code> console API</a> provided by the
Chromium DevTools console. It can be used to search for objects that
have the matching constructor on its prototype chain in the heap after
a full garbage collection, which can be useful for memory leak
regression tests. To avoid surprising results, users should avoid using
this API on constructors whose implementation they don't control, or on
constructors that can be invoked by other parties in the application.</p>
<p>To avoid accidental leaks, this API does not return raw references to
the objects found. By default, it returns the count of the objects
found. If <code>options.format</code> is <code>'summary'</code>, it returns an array
containing brief string representations for each object. The visibility
provided in this API is similar to what the heap snapshot provides,
while users can save the cost of serialization and parsing and directly
filter the target objects during the search.</p>
<p>Only objects created in the current execution context are included in the
results.</p>
<pre class="with-44-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> { queryObjects } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">A</span> { foo = <span class="hljs-string">'bar'</span>; }
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A)); <span class="hljs-comment">// 0</span>
<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title function_">A</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A)); <span class="hljs-comment">// 1</span>
<span class="hljs-comment">// [ "A { foo: 'bar' }" ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A, { <span class="hljs-attr">format</span>: <span class="hljs-string">'summary'</span> }));
<span class="hljs-keyword">class</span> <span class="hljs-title class_">B</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">A</span> { bar = <span class="hljs-string">'qux'</span>; }
<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title function_">B</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(B)); <span class="hljs-comment">// 1</span>
<span class="hljs-comment">// [ "B { foo: 'bar', bar: 'qux' }" ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(B, { <span class="hljs-attr">format</span>: <span class="hljs-string">'summary'</span> }));
<span class="hljs-comment">// Note that, when there are child classes inheriting from a constructor,</span>
<span class="hljs-comment">// the constructor also shows up in the prototype chain of the child</span>
<span class="hljs-comment">// classes's prototoype, so the child classes's prototoype would also be</span>
<span class="hljs-comment">// included in the result.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A)); <span class="hljs-comment">// 3</span>
<span class="hljs-comment">// [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A, { <span class="hljs-attr">format</span>: <span class="hljs-string">'summary'</span> }));</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { queryObjects } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">A</span> { foo = <span class="hljs-string">'bar'</span>; }
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A)); <span class="hljs-comment">// 0</span>
<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title function_">A</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A)); <span class="hljs-comment">// 1</span>
<span class="hljs-comment">// [ "A { foo: 'bar' }" ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A, { <span class="hljs-attr">format</span>: <span class="hljs-string">'summary'</span> }));
<span class="hljs-keyword">class</span> <span class="hljs-title class_">B</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">A</span> { bar = <span class="hljs-string">'qux'</span>; }
<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title function_">B</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(B)); <span class="hljs-comment">// 1</span>
<span class="hljs-comment">// [ "B { foo: 'bar', bar: 'qux' }" ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(B, { <span class="hljs-attr">format</span>: <span class="hljs-string">'summary'</span> }));
<span class="hljs-comment">// Note that, when there are child classes inheriting from a constructor,</span>
<span class="hljs-comment">// the constructor also shows up in the prototype chain of the child</span>
<span class="hljs-comment">// classes's prototoype, so the child classes's prototoype would also be</span>
<span class="hljs-comment">// included in the result.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A)); <span class="hljs-comment">// 3</span>
<span class="hljs-comment">// [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A, { <span class="hljs-attr">format</span>: <span class="hljs-string">'summary'</span> }));</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.setFlagsFromString(flags)</code><span><a class="mark" href="#all_v8_v8setflagsfromstringflags" id="all_v8_v8setflagsfromstringflags">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_setflagsfromstring_flags"></a></h3>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div>
<ul>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The <code>v8.setFlagsFromString()</code> method can be used to programmatically set
V8 command-line flags. This method should be used with care. Changing settings
after the VM has started may result in unpredictable behavior, including
crashes and data loss; or it may simply do nothing.</p>
<p>The V8 options available for a version of Node.js may be determined by running
<code>node --v8-options</code>.</p>
<p>Usage:</p>
<pre><code class="language-js"><span class="hljs-comment">// Print GC events to stdout for one minute.</span>
<span class="hljs-keyword">const</span> v8 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
v8.<span class="hljs-title function_">setFlagsFromString</span>(<span class="hljs-string">'--trace_gc'</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { v8.<span class="hljs-title function_">setFlagsFromString</span>(<span class="hljs-string">'--notrace_gc'</span>); }, <span class="hljs-number">60e3</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.stopCoverage()</code><span><a class="mark" href="#all_v8_v8stopcoverage" id="all_v8_v8stopcoverage">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_stopcoverage"></a></h3>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.18.0, v12.22.0</span>
</div>
<p>The <code>v8.stopCoverage()</code> method allows the user to stop the coverage collection
started by <a href="#all_cli_node_v8_coveragedir"><code>NODE_V8_COVERAGE</code></a>, so that V8 can release the execution count
records and optimize code. This can be used in conjunction with
<a href="#all_v8_v8takecoverage"><code>v8.takeCoverage()</code></a> if the user wants to collect the coverage on demand.</p>
</section><section><h3><code>v8.takeCoverage()</code><span><a class="mark" href="#all_v8_v8takecoverage" id="all_v8_v8takecoverage">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_takecoverage"></a></h3>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.18.0, v12.22.0</span>
</div>
<p>The <code>v8.takeCoverage()</code> method allows the user to write the coverage started by
<a href="#all_cli_node_v8_coveragedir"><code>NODE_V8_COVERAGE</code></a> to disk on demand. This method can be invoked multiple
times during the lifetime of the process. Each time the execution counter will
be reset and a new coverage report will be written to the directory specified
by <a href="#all_cli_node_v8_coveragedir"><code>NODE_V8_COVERAGE</code></a>.</p>
<p>When the process is about to exit, one last coverage will still be written to
disk unless <a href="#all_v8_v8stopcoverage"><code>v8.stopCoverage()</code></a> is invoked before the process exits.</p>
</section><section><h3><code>v8.writeHeapSnapshot([filename[,options]])</code><span><a class="mark" href="#all_v8_v8writeheapsnapshotfilenameoptions" id="all_v8_v8writeheapsnapshotfilenameoptions">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_writeheapsnapshot_filename_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.1.0</td>
<td><p>Support options to configure the heap snapshot.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>An exception will now be thrown if the file could not be written.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Make the returned error codes consistent across all platforms.</p></td></tr>
<tr><td>v11.13.0</td>
<td><p><span>Added in: v11.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The file path where the V8 heap snapshot is to be
saved. If not specified, a file name with the pattern
<code>'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'</code> will be
generated, where <code>{pid}</code> will be the PID of the Node.js process,
<code>{thread_id}</code> will be <code>0</code> when <code>writeHeapSnapshot()</code> is called from
the main Node.js thread or the id of a worker thread.</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>exposeInternals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If true, expose internals in the heap snapshot.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>exposeNumericValues</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If true, expose numeric values in
artificial fields. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The filename where the snapshot was saved.</li>
</ul>
<p>Generates a snapshot of the current V8 heap and writes it to a JSON
file. This file is intended to be used with tools such as Chrome
DevTools. The JSON schema is undocumented and specific to the V8
engine, and may change from one version of V8 to the next.</p>
<p>A heap snapshot is specific to a single V8 isolate. When using
<a href="worker_threads.html">worker threads</a>, a heap snapshot generated from the main thread will
not contain any information about the workers, and vice versa.</p>
<p>Creating a heap snapshot requires memory about twice the size of the heap at
the time the snapshot is created. This results in the risk of OOM killers
terminating the process.</p>
<p>Generating a snapshot is a synchronous operation which blocks the event loop
for a duration depending on the heap size.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { writeHeapSnapshot } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
<span class="hljs-keyword">const</span> {
<span class="hljs-title class_">Worker</span>,
isMainThread,
parentPort,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">if</span> (isMainThread) {
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
worker.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">filename</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker heapdump: <span class="hljs-subst">${filename}</span>`</span>);
<span class="hljs-comment">// Now get a heapdump for the main thread.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`main thread heapdump: <span class="hljs-subst">${writeHeapSnapshot()}</span>`</span>);
});
<span class="hljs-comment">// Tell the worker to create a heapdump.</span>
worker.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'heapdump'</span>);
} <span class="hljs-keyword">else</span> {
parentPort.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
<span class="hljs-keyword">if</span> (message === <span class="hljs-string">'heapdump'</span>) {
<span class="hljs-comment">// Generate a heapdump for the worker</span>
<span class="hljs-comment">// and return the filename to the parent.</span>
parentPort.<span class="hljs-title function_">postMessage</span>(<span class="hljs-title function_">writeHeapSnapshot</span>());
}
});
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.setHeapSnapshotNearHeapLimit(limit)</code><span><a class="mark" href="#all_v8_v8setheapsnapshotnearheaplimitlimit" id="all_v8_v8setheapsnapshotnearheaplimitlimit">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_setheapsnapshotnearheaplimit_limit"></a></h3>
<div class="api_metadata">
<span>Added in: v18.10.0, v16.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_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"><integer></a></li>
</ul>
<p>The API is a no-op if <code>--heapsnapshot-near-heap-limit</code> is already set from the
command line or the API is called more than once. <code>limit</code> must be a positive
integer. See <a href="#all_cli_--heapsnapshot-near-heap-limitmax_count"><code>--heapsnapshot-near-heap-limit</code></a> for more information.</p>
</section><section><h3>Serialization API<span><a class="mark" href="#all_v8_serialization-api" id="all_v8_serialization-api">#</a></span><a aria-hidden="true" class="legacy" id="v8_serialization_api"></a></h3>
<p>The serialization API provides means of serializing JavaScript values in a way
that is compatible with the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>.</p>
<p>The format is backward-compatible (i.e. safe to store to disk).
Equal JavaScript values may result in different serialized output.</p>
<h4><code>v8.serialize(value)</code><span><a class="mark" href="#all_v8_v8serializevalue" id="all_v8_v8serializevalue">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_serialize_value"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>value</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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Uses a <a href="#all_v8_class-v8defaultserializer"><code>DefaultSerializer</code></a> to serialize <code>value</code> into a buffer.</p>
<p><a href="#all_errors_err_buffer_too_large"><code>ERR_BUFFER_TOO_LARGE</code></a> will be thrown when trying to
serialize a huge object which requires buffer
larger than <a href="#all_buffer_bufferconstantsmax_length"><code>buffer.constants.MAX_LENGTH</code></a>.</p>
<h4><code>v8.deserialize(buffer)</code><span><a class="mark" href="#all_v8_v8deserializebuffer" id="all_v8_v8deserializebuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_deserialize_buffer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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 buffer returned by <a href="#all_v8_v8serializevalue"><code>serialize()</code></a>.</li>
</ul>
<p>Uses a <a href="#all_v8_class-v8defaultdeserializer"><code>DefaultDeserializer</code></a> with default options to read a JS value
from a buffer.</p>
<h4>Class: <code>v8.Serializer</code><span><a class="mark" href="#all_v8_class-v8serializer" id="all_v8_class-v8serializer">#</a></span><a aria-hidden="true" class="legacy" id="v8_class_v8_serializer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<h5><code>new Serializer()</code><span><a class="mark" href="#all_v8_new-serializer" id="all_v8_new-serializer">#</a></span><a aria-hidden="true" class="legacy" id="v8_new_serializer"></a></h5>
<p>Creates a new <code>Serializer</code> object.</p>
<h5><code>serializer.writeHeader()</code><span><a class="mark" href="#all_v8_serializerwriteheader" id="all_v8_serializerwriteheader">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writeheader"></a></h5>
<p>Writes out a header, which includes the serialization format version.</p>
<h5><code>serializer.writeValue(value)</code><span><a class="mark" href="#all_v8_serializerwritevaluevalue" id="all_v8_serializerwritevaluevalue">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writevalue_value"></a></h5>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Serializes a JavaScript value and adds the serialized representation to the
internal buffer.</p>
<p>This throws an error if <code>value</code> cannot be serialized.</p>
<h5><code>serializer.releaseBuffer()</code><span><a class="mark" href="#all_v8_serializerreleasebuffer" id="all_v8_serializerreleasebuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_releasebuffer"></a></h5>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Returns the stored internal buffer. This serializer should not be used once
the buffer is released. Calling this method results in undefined behavior
if a previous write has failed.</p>
<h5><code>serializer.transferArrayBuffer(id, arrayBuffer)</code><span><a class="mark" href="#all_v8_serializertransferarraybufferid-arraybuffer" id="all_v8_serializertransferarraybufferid-arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_transferarraybuffer_id_arraybuffer"></a></h5>
<ul>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> A 32-bit unsigned integer.</li>
<li><code>arrayBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> An <code>ArrayBuffer</code> instance.</li>
</ul>
<p>Marks an <code>ArrayBuffer</code> as having its contents transferred out of band.
Pass the corresponding <code>ArrayBuffer</code> in the deserializing context to
<a href="#all_v8_deserializertransferarraybufferid-arraybuffer"><code>deserializer.transferArrayBuffer()</code></a>.</p>
<h5><code>serializer.writeUint32(value)</code><span><a class="mark" href="#all_v8_serializerwriteuint32value" id="all_v8_serializerwriteuint32value">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writeuint32_value"></a></h5>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Write a raw 32-bit unsigned integer.
For use inside of a custom <a href="#all_v8_serializer_writehostobjectobject"><code>serializer._writeHostObject()</code></a>.</p>
<h5><code>serializer.writeUint64(hi, lo)</code><span><a class="mark" href="#all_v8_serializerwriteuint64hi-lo" id="all_v8_serializerwriteuint64hi-lo">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writeuint64_hi_lo"></a></h5>
<ul>
<li><code>hi</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>lo</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Write a raw 64-bit unsigned integer, split into high and low 32-bit parts.
For use inside of a custom <a href="#all_v8_serializer_writehostobjectobject"><code>serializer._writeHostObject()</code></a>.</p>
<h5><code>serializer.writeDouble(value)</code><span><a class="mark" href="#all_v8_serializerwritedoublevalue" id="all_v8_serializerwritedoublevalue">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writedouble_value"></a></h5>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Write a JS <code>number</code> value.
For use inside of a custom <a href="#all_v8_serializer_writehostobjectobject"><code>serializer._writeHostObject()</code></a>.</p>
<h5><code>serializer.writeRawBytes(buffer)</code><span><a class="mark" href="#all_v8_serializerwriterawbytesbuffer" id="all_v8_serializerwriterawbytesbuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writerawbytes_buffer"></a></h5>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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></li>
</ul>
<p>Write raw bytes into the serializer's internal buffer. The deserializer
will require a way to compute the length of the buffer.
For use inside of a custom <a href="#all_v8_serializer_writehostobjectobject"><code>serializer._writeHostObject()</code></a>.</p>
<h5><code>serializer._writeHostObject(object)</code><span><a class="mark" href="#all_v8_serializer_writehostobjectobject" id="all_v8_serializer_writehostobjectobject">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writehostobject_object"></a></h5>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>This method is called to write some kind of host object, i.e. an object created
by native C++ bindings. If it is not possible to serialize <code>object</code>, a suitable
exception should be thrown.</p>
<p>This method is not present on the <code>Serializer</code> class itself but can be provided
by subclasses.</p>
<h5><code>serializer._getDataCloneError(message)</code><span><a class="mark" href="#all_v8_serializer_getdatacloneerrormessage" id="all_v8_serializer_getdatacloneerrormessage">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_getdatacloneerror_message"></a></h5>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>This method is called to generate error objects that will be thrown when an
object can not be cloned.</p>
<p>This method defaults to the <a href="#all_errors_class-error"><code>Error</code></a> constructor and can be overridden on
subclasses.</p>
<h5><code>serializer._getSharedArrayBufferId(sharedArrayBuffer)</code><span><a class="mark" href="#all_v8_serializer_getsharedarraybufferidsharedarraybuffer" id="all_v8_serializer_getsharedarraybufferidsharedarraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_getsharedarraybufferid_sharedarraybuffer"></a></h5>
<ul>
<li><code>sharedArrayBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a></li>
</ul>
<p>This method is called when the serializer is going to serialize a
<code>SharedArrayBuffer</code> object. It must return an unsigned 32-bit integer ID for
the object, using the same ID if this <code>SharedArrayBuffer</code> has already been
serialized. When deserializing, this ID will be passed to
<a href="#all_v8_deserializertransferarraybufferid-arraybuffer"><code>deserializer.transferArrayBuffer()</code></a>.</p>
<p>If the object cannot be serialized, an exception should be thrown.</p>
<p>This method is not present on the <code>Serializer</code> class itself but can be provided
by subclasses.</p>
<h5><code>serializer._setTreatArrayBufferViewsAsHostObjects(flag)</code><span><a class="mark" href="#all_v8_serializer_settreatarraybufferviewsashostobjectsflag" id="all_v8_serializer_settreatarraybufferviewsashostobjectsflag">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_settreatarraybufferviewsashostobjects_flag"></a></h5>
<ul>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li>
</ul>
<p>Indicate whether to treat <code>TypedArray</code> and <code>DataView</code> objects as
host objects, i.e. pass them to <a href="#all_v8_serializer_writehostobjectobject"><code>serializer._writeHostObject()</code></a>.</p>
<h4>Class: <code>v8.Deserializer</code><span><a class="mark" href="#all_v8_class-v8deserializer" id="all_v8_class-v8deserializer">#</a></span><a aria-hidden="true" class="legacy" id="v8_class_v8_deserializer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<h5><code>new Deserializer(buffer)</code><span><a class="mark" href="#all_v8_new-deserializerbuffer" id="all_v8_new-deserializerbuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_new_deserializer_buffer"></a></h5>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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 buffer returned by
<a href="#all_v8_serializerreleasebuffer"><code>serializer.releaseBuffer()</code></a>.</li>
</ul>
<p>Creates a new <code>Deserializer</code> object.</p>
<h5><code>deserializer.readHeader()</code><span><a class="mark" href="#all_v8_deserializerreadheader" id="all_v8_deserializerreadheader">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readheader"></a></h5>
<p>Reads and validates a header (including the format version).
May, for example, reject an invalid or unsupported wire format. In that case,
an <code>Error</code> is thrown.</p>
<h5><code>deserializer.readValue()</code><span><a class="mark" href="#all_v8_deserializerreadvalue" id="all_v8_deserializerreadvalue">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readvalue"></a></h5>
<p>Deserializes a JavaScript value from the buffer and returns it.</p>
<h5><code>deserializer.transferArrayBuffer(id, arrayBuffer)</code><span><a class="mark" href="#all_v8_deserializertransferarraybufferid-arraybuffer" id="all_v8_deserializertransferarraybufferid-arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_transferarraybuffer_id_arraybuffer"></a></h5>
<ul>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> A 32-bit unsigned integer.</li>
<li><code>arrayBuffer</code> <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/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> An <code>ArrayBuffer</code> instance.</li>
</ul>
<p>Marks an <code>ArrayBuffer</code> as having its contents transferred out of band.
Pass the corresponding <code>ArrayBuffer</code> in the serializing context to
<a href="#all_v8_serializertransferarraybufferid-arraybuffer"><code>serializer.transferArrayBuffer()</code></a> (or return the <code>id</code> from
<a href="#all_v8_serializer_getsharedarraybufferidsharedarraybuffer"><code>serializer._getSharedArrayBufferId()</code></a> in the case of <code>SharedArrayBuffer</code>s).</p>
<h5><code>deserializer.getWireFormatVersion()</code><span><a class="mark" href="#all_v8_deserializergetwireformatversion" id="all_v8_deserializergetwireformatversion">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_getwireformatversion"></a></h5>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Reads the underlying wire format version. Likely mostly to be useful to
legacy code reading old wire format versions. May not be called before
<code>.readHeader()</code>.</p>
<h5><code>deserializer.readUint32()</code><span><a class="mark" href="#all_v8_deserializerreaduint32" id="all_v8_deserializerreaduint32">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readuint32"></a></h5>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Read a raw 32-bit unsigned integer and return it.
For use inside of a custom <a href="#all_v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p>
<h5><code>deserializer.readUint64()</code><span><a class="mark" href="#all_v8_deserializerreaduint64" id="all_v8_deserializerreaduint64">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readuint64"></a></h5>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a></li>
</ul>
<p>Read a raw 64-bit unsigned integer and return it as an array <code>[hi, lo]</code>
with two 32-bit unsigned integer entries.
For use inside of a custom <a href="#all_v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p>
<h5><code>deserializer.readDouble()</code><span><a class="mark" href="#all_v8_deserializerreaddouble" id="all_v8_deserializerreaddouble">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readdouble"></a></h5>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Read a JS <code>number</code> value.
For use inside of a custom <a href="#all_v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p>
<h5><code>deserializer.readRawBytes(length)</code><span><a class="mark" href="#all_v8_deserializerreadrawbyteslength" id="all_v8_deserializerreadrawbyteslength">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readrawbytes_length"></a></h5>
<ul>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Read raw bytes from the deserializer's internal buffer. The <code>length</code> parameter
must correspond to the length of the buffer that was passed to
<a href="#all_v8_serializerwriterawbytesbuffer"><code>serializer.writeRawBytes()</code></a>.
For use inside of a custom <a href="#all_v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p>
<h5><code>deserializer._readHostObject()</code><span><a class="mark" href="#all_v8_deserializer_readhostobject" id="all_v8_deserializer_readhostobject">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readhostobject"></a></h5>
<p>This method is called to read some kind of host object, i.e. an object that is
created by native C++ bindings. If it is not possible to deserialize the data,
a suitable exception should be thrown.</p>
<p>This method is not present on the <code>Deserializer</code> class itself but can be
provided by subclasses.</p>
<h4>Class: <code>v8.DefaultSerializer</code><span><a class="mark" href="#all_v8_class-v8defaultserializer" id="all_v8_class-v8defaultserializer">#</a></span><a aria-hidden="true" class="legacy" id="v8_class_v8_defaultserializer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>A subclass of <a href="#all_v8_class-v8serializer"><code>Serializer</code></a> that serializes <code>TypedArray</code>
(in particular <a href="buffer.html"><code>Buffer</code></a>) and <code>DataView</code> objects as host objects, and only
stores the part of their underlying <code>ArrayBuffer</code>s that they are referring to.</p>
<h4>Class: <code>v8.DefaultDeserializer</code><span><a class="mark" href="#all_v8_class-v8defaultdeserializer" id="all_v8_class-v8defaultdeserializer">#</a></span><a aria-hidden="true" class="legacy" id="v8_class_v8_defaultdeserializer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>A subclass of <a href="#all_v8_class-v8deserializer"><code>Deserializer</code></a> corresponding to the format written by
<a href="#all_v8_class-v8defaultserializer"><code>DefaultSerializer</code></a>.</p>
</section><section><h3>Promise hooks<span><a class="mark" href="#all_v8_promise-hooks" id="all_v8_promise-hooks">#</a></span><a aria-hidden="true" class="legacy" id="v8_promise_hooks"></a></h3>
<p>The <code>promiseHooks</code> interface can be used to track promise lifecycle events.
To track <em>all</em> async activity, see <a href="async_hooks.html"><code>async_hooks</code></a> which internally uses this
module to produce promise lifecycle events in addition to events for other
async resources. For request context management, see <a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { promiseHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;
<span class="hljs-comment">// There are four lifecycle events produced by promises:</span>
<span class="hljs-comment">// The `init` event represents the creation of a promise. This could be a</span>
<span class="hljs-comment">// direct creation such as with `new Promise(...)` or a continuation such</span>
<span class="hljs-comment">// as `then()` or `catch()`. It also happens whenever an async function is</span>
<span class="hljs-comment">// called or does an `await`. If a continuation promise is created, the</span>
<span class="hljs-comment">// `parent` will be the promise it is a continuation from.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">promise, parent</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a promise was created'</span>, { promise, parent });
}
<span class="hljs-comment">// The `settled` event happens when a promise receives a resolution or</span>
<span class="hljs-comment">// rejection value. This may happen synchronously such as when using</span>
<span class="hljs-comment">// `Promise.resolve()` on non-promise input.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">settled</span>(<span class="hljs-params">promise</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a promise resolved or rejected'</span>, { promise });
}
<span class="hljs-comment">// The `before` event runs immediately before a `then()` or `catch()` handler</span>
<span class="hljs-comment">// runs or an `await` resumes execution.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">before</span>(<span class="hljs-params">promise</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a promise is about to call a then handler'</span>, { promise });
}
<span class="hljs-comment">// The `after` event runs immediately after a `then()` handler runs or when</span>
<span class="hljs-comment">// an `await` begins after resuming from another.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">after</span>(<span class="hljs-params">promise</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a promise is done calling a then handler'</span>, { promise });
}
<span class="hljs-comment">// Lifecycle hooks may be started and stopped individually</span>
<span class="hljs-keyword">const</span> stopWatchingInits = promiseHooks.<span class="hljs-title function_">onInit</span>(init);
<span class="hljs-keyword">const</span> stopWatchingSettleds = promiseHooks.<span class="hljs-title function_">onSettled</span>(settled);
<span class="hljs-keyword">const</span> stopWatchingBefores = promiseHooks.<span class="hljs-title function_">onBefore</span>(before);
<span class="hljs-keyword">const</span> stopWatchingAfters = promiseHooks.<span class="hljs-title function_">onAfter</span>(after);
<span class="hljs-comment">// Or they may be started and stopped in groups</span>
<span class="hljs-keyword">const</span> stopHookSet = promiseHooks.<span class="hljs-title function_">createHook</span>({
init,
settled,
before,
after,
});
<span class="hljs-comment">// To stop a hook, call the function returned at its creation.</span>
<span class="hljs-title function_">stopWatchingInits</span>();
<span class="hljs-title function_">stopWatchingSettleds</span>();
<span class="hljs-title function_">stopWatchingBefores</span>();
<span class="hljs-title function_">stopWatchingAfters</span>();
<span class="hljs-title function_">stopHookSet</span>();</code> <button class="copy-button">copy</button></pre>
<h4><code>promiseHooks.onInit(init)</code><span><a class="mark" href="#all_v8_promisehooksoninitinit" id="all_v8_promisehooksoninitinit">#</a></span><a aria-hidden="true" class="legacy" id="v8_promisehooks_oninit_init"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<ul>
<li><code>init</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_v8_initpromise-parent"><code>init</code> callback</a> to call when a promise is created.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call to stop the hook.</li>
</ul>
<p><strong>The <code>init</code> hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.</strong></p>
<pre class="with-44-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> { promiseHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;
<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onInit</span>(<span class="hljs-function">(<span class="hljs-params">promise, parent</span>) =></span> {});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { promiseHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onInit</span>(<span class="hljs-function">(<span class="hljs-params">promise, parent</span>) =></span> {});</code><button class="copy-button">copy</button></pre>
<h4><code>promiseHooks.onSettled(settled)</code><span><a class="mark" href="#all_v8_promisehooksonsettledsettled" id="all_v8_promisehooksonsettledsettled">#</a></span><a aria-hidden="true" class="legacy" id="v8_promisehooks_onsettled_settled"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<ul>
<li><code>settled</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_v8_settledpromise"><code>settled</code> callback</a> to call when a promise
is resolved or rejected.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call to stop the hook.</li>
</ul>
<p><strong>The <code>settled</code> hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.</strong></p>
<pre class="with-44-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> { promiseHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;
<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onSettled</span>(<span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { promiseHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onSettled</span>(<span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {});</code><button class="copy-button">copy</button></pre>
<h4><code>promiseHooks.onBefore(before)</code><span><a class="mark" href="#all_v8_promisehooksonbeforebefore" id="all_v8_promisehooksonbeforebefore">#</a></span><a aria-hidden="true" class="legacy" id="v8_promisehooks_onbefore_before"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<ul>
<li><code>before</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_v8_beforepromise"><code>before</code> callback</a> to call before a promise
continuation executes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call to stop the hook.</li>
</ul>
<p><strong>The <code>before</code> hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.</strong></p>
<pre class="with-44-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> { promiseHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;
<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onBefore</span>(<span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { promiseHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onBefore</span>(<span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {});</code><button class="copy-button">copy</button></pre>
<h4><code>promiseHooks.onAfter(after)</code><span><a class="mark" href="#all_v8_promisehooksonafterafter" id="all_v8_promisehooksonafterafter">#</a></span><a aria-hidden="true" class="legacy" id="v8_promisehooks_onafter_after"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<ul>
<li><code>after</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_v8_afterpromise"><code>after</code> callback</a> to call after a promise
continuation executes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call to stop the hook.</li>
</ul>
<p><strong>The <code>after</code> hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.</strong></p>
<pre class="with-44-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> { promiseHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;
<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onAfter</span>(<span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { promiseHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onAfter</span>(<span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {});</code><button class="copy-button">copy</button></pre>
<h4><code>promiseHooks.createHook(callbacks)</code><span><a class="mark" href="#all_v8_promisehookscreatehookcallbacks" id="all_v8_promisehookscreatehookcallbacks">#</a></span><a aria-hidden="true" class="legacy" id="v8_promisehooks_createhook_callbacks"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<ul>
<li><code>callbacks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <a href="#all_v8_hook-callbacks">Hook Callbacks</a> to register
<ul>
<li><code>init</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_v8_initpromise-parent"><code>init</code> callback</a>.</li>
<li><code>before</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_v8_beforepromise"><code>before</code> callback</a>.</li>
<li><code>after</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_v8_afterpromise"><code>after</code> callback</a>.</li>
<li><code>settled</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#all_v8_settledpromise"><code>settled</code> callback</a>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Used for disabling hooks</li>
</ul>
<p><strong>The hook callbacks must be plain functions. Providing async functions will
throw as it would produce an infinite microtask loop.</strong></p>
<p>Registers functions to be called for different lifetime events of each promise.</p>
<p>The callbacks <code>init()</code>/<code>before()</code>/<code>after()</code>/<code>settled()</code> are called for the
respective events during a promise's lifetime.</p>
<p>All callbacks are optional. For example, if only promise creation needs to
be tracked, then only the <code>init</code> callback needs to be passed. The
specifics of all functions that can be passed to <code>callbacks</code> is in the
<a href="#all_v8_hook-callbacks">Hook Callbacks</a> section.</p>
<pre class="with-44-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> { promiseHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;
<span class="hljs-keyword">const</span> stopAll = promiseHooks.<span class="hljs-title function_">createHook</span>({
<span class="hljs-title function_">init</span>(<span class="hljs-params">promise, parent</span>) {},
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { promiseHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
<span class="hljs-keyword">const</span> stopAll = promiseHooks.<span class="hljs-title function_">createHook</span>({
<span class="hljs-title function_">init</span>(<span class="hljs-params">promise, parent</span>) {},
});</code><button class="copy-button">copy</button></pre>
<h4>Hook callbacks<span><a class="mark" href="#all_v8_hook-callbacks" id="all_v8_hook-callbacks">#</a></span><a aria-hidden="true" class="legacy" id="v8_hook_callbacks"></a></h4>
<p>Key events in the lifetime of a promise have been categorized into four areas:
creation of a promise, before/after a continuation handler is called or around
an await, and when the promise resolves or rejects.</p>
<p>While these hooks are similar to those of <a href="async_hooks.html"><code>async_hooks</code></a> they lack a
<code>destroy</code> hook. Other types of async resources typically represent sockets or
file descriptors which have a distinct "closed" state to express the <code>destroy</code>
lifecycle event while promises remain usable for as long as code can still
reach them. Garbage collection tracking is used to make promises fit into the
<code>async_hooks</code> event model, however this tracking is very expensive and they may
not necessarily ever even be garbage collected.</p>
<p>Because promises are asynchronous resources whose lifecycle is tracked
via the promise hooks mechanism, the <code>init()</code>, <code>before()</code>, <code>after()</code>, and
<code>settled()</code> callbacks <em>must not</em> be async functions as they create more
promises which would produce an infinite loop.</p>
<p>While this API is used to feed promise events into <a href="async_hooks.html"><code>async_hooks</code></a>, the
ordering between the two is undefined. Both APIs are multi-tenant
and therefore could produce events in any order relative to each other.</p>
<h5><code>init(promise, parent)</code><span><a class="mark" href="#all_v8_initpromise-parent" id="all_v8_initpromise-parent">#</a></span><a aria-hidden="true" class="legacy" id="v8_init_promise_parent"></a></h5>
<ul>
<li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> The promise being created.</li>
<li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> The promise continued from, if applicable.</li>
</ul>
<p>Called when a promise is constructed. This <em>does not</em> mean that corresponding
<code>before</code>/<code>after</code> events will occur, only that the possibility exists. This will
happen if a promise is created without ever getting a continuation.</p>
<h5><code>before(promise)</code><span><a class="mark" href="#all_v8_beforepromise" id="all_v8_beforepromise">#</a></span><a aria-hidden="true" class="legacy" id="v8_before_promise"></a></h5>
<ul>
<li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Called before a promise continuation executes. This can be in the form of
<code>then()</code>, <code>catch()</code>, or <code>finally()</code> handlers or an <code>await</code> resuming.</p>
<p>The <code>before</code> callback will be called 0 to N times. The <code>before</code> callback
will typically be called 0 times if no continuation was ever made for the
promise. The <code>before</code> callback may be called many times in the case where
many continuations have been made from the same promise.</p>
<h5><code>after(promise)</code><span><a class="mark" href="#all_v8_afterpromise" id="all_v8_afterpromise">#</a></span><a aria-hidden="true" class="legacy" id="v8_after_promise"></a></h5>
<ul>
<li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Called immediately after a promise continuation executes. This may be after a
<code>then()</code>, <code>catch()</code>, or <code>finally()</code> handler or before an <code>await</code> after another
<code>await</code>.</p>
<h5><code>settled(promise)</code><span><a class="mark" href="#all_v8_settledpromise" id="all_v8_settledpromise">#</a></span><a aria-hidden="true" class="legacy" id="v8_settled_promise"></a></h5>
<ul>
<li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Called when the promise receives a resolution or rejection value. This may
occur synchronously in the case of <code>Promise.resolve()</code> or <code>Promise.reject()</code>.</p>
</section><section><h3>Startup Snapshot API<span><a class="mark" href="#all_v8_startup-snapshot-api" id="all_v8_startup-snapshot-api">#</a></span><a aria-hidden="true" class="legacy" id="v8_startup_snapshot_api"></a></h3>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>The <code>v8.startupSnapshot</code> interface can be used to add serialization and
deserialization hooks for custom startup snapshots.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --snapshot-blob snapshot.blob --build-snapshot entry.js</span>
<span class="hljs-meta prompt_"># </span><span class="language-bash">This launches a process with the snapshot</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node --snapshot-blob snapshot.blob</span></code> <button class="copy-button">copy</button></pre>
<p>In the example above, <code>entry.js</code> can use methods from the <code>v8.startupSnapshot</code>
interface to specify how to save information for custom objects in the snapshot
during serialization and how the information can be used to synchronize these
objects during deserialization of the snapshot. For example, if the <code>entry.js</code>
contains the following script:</p>
<pre><code class="language-js cjs"><span class="hljs-meta">'use strict'</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">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> v8 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">BookShelf</span> {
storage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();
<span class="hljs-comment">// Reading a series of files from directory and store them into storage.</span>
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">directory, books</span>) {
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> book <span class="hljs-keyword">of</span> books) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">storage</span>.<span class="hljs-title function_">set</span>(book, fs.<span class="hljs-title function_">readFileSync</span>(path.<span class="hljs-title function_">join</span>(directory, book)));
}
}
<span class="hljs-keyword">static</span> <span class="hljs-title function_">compressAll</span>(<span class="hljs-params">shelf</span>) {
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [ book, content ] <span class="hljs-keyword">of</span> shelf.<span class="hljs-property">storage</span>) {
shelf.<span class="hljs-property">storage</span>.<span class="hljs-title function_">set</span>(book, zlib.<span class="hljs-title function_">gzipSync</span>(content));
}
}
<span class="hljs-keyword">static</span> <span class="hljs-title function_">decompressAll</span>(<span class="hljs-params">shelf</span>) {
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [ book, content ] <span class="hljs-keyword">of</span> shelf.<span class="hljs-property">storage</span>) {
shelf.<span class="hljs-property">storage</span>.<span class="hljs-title function_">set</span>(book, zlib.<span class="hljs-title function_">gunzipSync</span>(content));
}
}
}
<span class="hljs-comment">// __dirname here is where the snapshot script is placed</span>
<span class="hljs-comment">// during snapshot building time.</span>
<span class="hljs-keyword">const</span> shelf = <span class="hljs-keyword">new</span> <span class="hljs-title class_">BookShelf</span>(__dirname, [
<span class="hljs-string">'book1.en_US.txt'</span>,
<span class="hljs-string">'book1.es_ES.txt'</span>,
<span class="hljs-string">'book2.zh_CN.txt'</span>,
]);
<span class="hljs-title function_">assert</span>(v8.<span class="hljs-property">startupSnapshot</span>.<span class="hljs-title function_">isBuildingSnapshot</span>());
<span class="hljs-comment">// On snapshot serialization, compress the books to reduce size.</span>
v8.<span class="hljs-property">startupSnapshot</span>.<span class="hljs-title function_">addSerializeCallback</span>(<span class="hljs-title class_">BookShelf</span>.<span class="hljs-property">compressAll</span>, shelf);
<span class="hljs-comment">// On snapshot deserialization, decompress the books.</span>
v8.<span class="hljs-property">startupSnapshot</span>.<span class="hljs-title function_">addDeserializeCallback</span>(<span class="hljs-title class_">BookShelf</span>.<span class="hljs-property">decompressAll</span>, shelf);
v8.<span class="hljs-property">startupSnapshot</span>.<span class="hljs-title function_">setDeserializeMainFunction</span>(<span class="hljs-function">(<span class="hljs-params">shelf</span>) =></span> {
<span class="hljs-comment">// process.env and process.argv are refreshed during snapshot</span>
<span class="hljs-comment">// deserialization.</span>
<span class="hljs-keyword">const</span> lang = process.<span class="hljs-property">env</span>.<span class="hljs-property">BOOK_LANG</span> || <span class="hljs-string">'en_US'</span>;
<span class="hljs-keyword">const</span> book = process.<span class="hljs-property">argv</span>[<span class="hljs-number">1</span>];
<span class="hljs-keyword">const</span> name = <span class="hljs-string">`<span class="hljs-subst">${book}</span>.<span class="hljs-subst">${lang}</span>.txt`</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(shelf.<span class="hljs-property">storage</span>.<span class="hljs-title function_">get</span>(name));
}, shelf);</code> <button class="copy-button">copy</button></pre>
<p>The resulted binary will get print the data deserialized from the snapshot
during start up, using the refreshed <code>process.env</code> and <code>process.argv</code> of
the launched process:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1</span>
<span class="hljs-meta prompt_"># </span><span class="language-bash">Prints content of book1.es_ES.txt deserialized from the snapshot.</span></code> <button class="copy-button">copy</button></pre>
<p>Currently the application deserialized from a user-land snapshot cannot
be snapshotted again, so these APIs are only available to applications
that are not deserialized from a user-land snapshot.</p>
<h4><code>v8.startupSnapshot.addSerializeCallback(callback[, data])</code><span><a class="mark" href="#all_v8_v8startupsnapshotaddserializecallbackcallback-data" id="all_v8_v8startupsnapshotaddserializecallbackcallback-data">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_startupsnapshot_addserializecallback_callback_data"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.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> Callback to be invoked before serialization.</li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional data that will be passed to the <code>callback</code> when it
gets called.</li>
</ul>
<p>Add a callback that will be called when the Node.js instance is about to
get serialized into a snapshot and exit. This can be used to release
resources that should not or cannot be serialized or to convert user data
into a form more suitable for serialization.</p>
<p>Callbacks are run in the order in which they are added.</p>
<h4><code>v8.startupSnapshot.addDeserializeCallback(callback[, data])</code><span><a class="mark" href="#all_v8_v8startupsnapshotadddeserializecallbackcallback-data" id="all_v8_v8startupsnapshotadddeserializecallbackcallback-data">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_startupsnapshot_adddeserializecallback_callback_data"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.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> Callback to be invoked after the snapshot is
deserialized.</li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional data that will be passed to the <code>callback</code> when it
gets called.</li>
</ul>
<p>Add a callback that will be called when the Node.js instance is deserialized
from a snapshot. The <code>callback</code> and the <code>data</code> (if provided) will be
serialized into the snapshot, they can be used to re-initialize the state
of the application or to re-acquire resources that the application needs
when the application is restarted from the snapshot.</p>
<p>Callbacks are run in the order in which they are added.</p>
<h4><code>v8.startupSnapshot.setDeserializeMainFunction(callback[, data])</code><span><a class="mark" href="#all_v8_v8startupsnapshotsetdeserializemainfunctioncallback-data" id="all_v8_v8startupsnapshotsetdeserializemainfunctioncallback-data">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_startupsnapshot_setdeserializemainfunction_callback_data"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.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> Callback to be invoked as the entry point after the
snapshot is deserialized.</li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional data that will be passed to the <code>callback</code> when it
gets called.</li>
</ul>
<p>This sets the entry point of the Node.js application when it is deserialized
from a snapshot. This can be called only once in the snapshot building
script. If called, the deserialized application no longer needs an additional
entry point script to start up and will simply invoke the callback along with
the deserialized data (if provided), otherwise an entry point script still
needs to be provided to the deserialized application.</p>
<h4><code>v8.startupSnapshot.isBuildingSnapshot()</code><span><a class="mark" href="#all_v8_v8startupsnapshotisbuildingsnapshot" id="all_v8_v8startupsnapshotisbuildingsnapshot">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_startupsnapshot_isbuildingsnapshot"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.0</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>Returns true if the Node.js instance is run to build a snapshot.</p>
</section><section><h3>Class: <code>v8.GCProfiler</code><span><a class="mark" href="#all_v8_class-v8gcprofiler" id="all_v8_class-v8gcprofiler">#</a></span><a aria-hidden="true" class="legacy" id="v8_class_v8_gcprofiler"></a></h3>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<p>This API collects GC data in current thread.</p>
<h4><code>new v8.GCProfiler()</code><span><a class="mark" href="#all_v8_new-v8gcprofiler" id="all_v8_new-v8gcprofiler">#</a></span><a aria-hidden="true" class="legacy" id="v8_new_v8_gcprofiler"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<p>Create a new instance of the <code>v8.GCProfiler</code> class.</p>
<h4><code>profiler.start()</code><span><a class="mark" href="#all_v8_profilerstart" id="all_v8_profilerstart">#</a></span><a aria-hidden="true" class="legacy" id="v8_profiler_start"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<p>Start collecting GC data.</p>
<h4><code>profiler.stop()</code><span><a class="mark" href="#all_v8_profilerstop" id="all_v8_profilerstop">#</a></span><a aria-hidden="true" class="legacy" id="v8_profiler_stop"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<p>Stop collecting GC data and return an object.The content of object
is as follows.</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
<span class="hljs-attr">"version"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"startTime"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1674059033862</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"statistics"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"gcType"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Scavenge"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"beforeGC"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"heapStatistics"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"totalHeapSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5005312</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"totalHeapSizeExecutable"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">524288</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"totalPhysicalSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5226496</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"totalAvailableSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4341325216</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"totalGlobalHandlesSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">8192</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"usedGlobalHandlesSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2112</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"usedHeapSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4883840</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"heapSizeLimit"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4345298944</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"mallocedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">254128</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"externalMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">225138</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"peakMallocedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">181760</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"heapSpaceStatistics"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"spaceName"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"read_only_space"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"spaceSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"spaceUsedSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"spaceAvailableSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"physicalSpaceSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"cost"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1574.14</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"afterGC"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"heapStatistics"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
<span class="hljs-attr">"totalHeapSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">6053888</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"totalHeapSizeExecutable"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">524288</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"totalPhysicalSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5500928</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"totalAvailableSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4341101384</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"totalGlobalHandlesSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">8192</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"usedGlobalHandlesSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2112</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"usedHeapSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4059096</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"heapSizeLimit"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4345298944</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"mallocedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">254128</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"externalMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">225138</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"peakMallocedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">181760</span>
<span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"heapSpaceStatistics"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
<span class="hljs-punctuation">{</span>
<span class="hljs-attr">"spaceName"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"read_only_space"</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"spaceSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"spaceUsedSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"spaceAvailableSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"physicalSpaceSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
<span class="hljs-attr">"endTime"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1674059036865</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Here's an example.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">GCProfiler</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'v8'</span>);
<span class="hljs-keyword">const</span> profiler = <span class="hljs-keyword">new</span> <span class="hljs-title class_">GCProfiler</span>();
profiler.<span class="hljs-title function_">start</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>(profiler.<span class="hljs-title function_">stop</span>());
}, <span class="hljs-number">1000</span>);</code> <button class="copy-button">copy</button></pre></section>
</section>
<section><h2>VM (executing JavaScript)<span><a class="mark" href="#all_vm_vm-executing-javascript" id="all_vm_vm-executing-javascript">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_executing_javascript"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/vm.js">lib/vm.js</a></p>
<p>The <code>node:vm</code> module enables compiling and running code within V8 Virtual
Machine contexts.</p>
<p><strong class="critical">The <code>node:vm</code> module is not a security
mechanism. Do not use it to run untrusted code.</strong></p>
<p>JavaScript code can be compiled and run immediately or
compiled, saved, and run later.</p>
<p>A common use case is to run the code in a different V8 Context. This means
invoked code has a different global object than the invoking code.</p>
<p>One can provide the context by <a href="#all_vm_what-does-it-mean-to-contextify-an-object"><em>contextifying</em></a> an
object. The invoked code treats any property in the context like a
global variable. Any changes to global variables caused by the invoked
code are reflected in the context object.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> x = <span class="hljs-number">1</span>;
<span class="hljs-keyword">const</span> context = { <span class="hljs-attr">x</span>: <span class="hljs-number">2</span> };
vm.<span class="hljs-title function_">createContext</span>(context); <span class="hljs-comment">// Contextify the object.</span>
<span class="hljs-keyword">const</span> code = <span class="hljs-string">'x += 40; var y = 17;'</span>;
<span class="hljs-comment">// `x` and `y` are global variables in the context.</span>
<span class="hljs-comment">// Initially, x has the value 2 because that is the value of context.x.</span>
vm.<span class="hljs-title function_">runInContext</span>(code, context);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">x</span>); <span class="hljs-comment">// 42</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">y</span>); <span class="hljs-comment">// 17</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x); <span class="hljs-comment">// 1; y is not defined.</span></code> <button class="copy-button">copy</button></pre>
<section><h3>Class: <code>vm.Script</code><span><a class="mark" href="#all_vm_class-vmscript" id="all_vm_class-vmscript">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_script"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div>
<p>Instances of the <code>vm.Script</code> class contain precompiled scripts that can be
executed in specific contexts.</p>
<h4><code>new vm.Script(code[, options])</code><span><a class="mark" href="#all_vm_new-vmscriptcode-options" id="all_vm_new-vmscriptcode-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_new_vm_script_code_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>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
<tr><td>v10.6.0</td>
<td><p>The <code>produceCachedData</code> is deprecated in favour of <code>script.createCachedData()</code>.</p></td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>cachedData</code> and <code>produceCachedData</code> options are supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.<anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>cachedData</code> <a href="#all_buffer_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> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. When supplied, the <code>cachedDataRejected</code> value will be set to
either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li>
<li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> and no <code>cachedData</code> is present, V8
will attempt to produce code cache data for <code>code</code>. Upon success, a
<code>Buffer</code> with V8's code cache data will be produced and stored in the
<code>cachedData</code> property of the returned <code>vm.Script</code> instance.
The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code>
depending on whether code cache data is produced successfully.
This option is <strong>deprecated</strong> in favor of <code>script.createCachedData()</code>.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_vm_vmconstantsuse_main_context_default_loader" class="type"><vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
</ul>
<p>If <code>options</code> is a string, then it specifies the filename.</p>
<p>Creating a new <code>vm.Script</code> object compiles <code>code</code> but does not run it. The
compiled <code>vm.Script</code> can be run later multiple times. The <code>code</code> is not bound to
any global object; rather, it is bound before each run, just for that run.</p>
<h4><code>script.cachedDataRejected</code><span><a class="mark" href="#all_vm_scriptcacheddatarejected" id="all_vm_scriptcacheddatarejected">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_cacheddatarejected"></a></h4>
<div class="api_metadata">
<span>Added in: v5.7.0</span>
</div>
<ul>
<li><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>
</ul>
<p>When <code>cachedData</code> is supplied to create the <code>vm.Script</code>, this value will be set
to either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.
Otherwise the value is <code>undefined</code>.</p>
<h4><code>script.createCachedData()</code><span><a class="mark" href="#all_vm_scriptcreatecacheddata" id="all_vm_scriptcreatecacheddata">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_createcacheddata"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Creates a code cache that can be used with the <code>Script</code> constructor's
<code>cachedData</code> option. Returns a <code>Buffer</code>. This method may be called at any
time and any number of times.</p>
<p>The code cache of the <code>Script</code> doesn't contain any JavaScript observable
states. The code cache is safe to be saved along side the script source and
used to construct new <code>Script</code> instances multiple times.</p>
<p>Functions in the <code>Script</code> source can be marked as lazily compiled and they are
not compiled at construction of the <code>Script</code>. These functions are going to be
compiled when they are invoked the first time. The code cache serializes the
metadata that V8 currently knows about the <code>Script</code> that it can use to speed up
future compilations.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">`
function add(a, b) {
return a + b;
}
const x = add(1, 2);
`</span>);
<span class="hljs-keyword">const</span> cacheWithoutAdd = script.<span class="hljs-title function_">createCachedData</span>();
<span class="hljs-comment">// In `cacheWithoutAdd` the function `add()` is marked for full compilation</span>
<span class="hljs-comment">// upon invocation.</span>
script.<span class="hljs-title function_">runInThisContext</span>();
<span class="hljs-keyword">const</span> cacheWithAdd = script.<span class="hljs-title function_">createCachedData</span>();
<span class="hljs-comment">// `cacheWithAdd` contains fully compiled function `add()`.</span></code> <button class="copy-button">copy</button></pre>
<h4><code>script.runInContext(contextifiedObject[, options])</code><span><a class="mark" href="#all_vm_scriptrunincontextcontextifiedobject-options" id="all_vm_scriptrunincontextcontextifiedobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_runincontext_contextifiedobject_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>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>contextifiedObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> object as returned by the
<code>vm.createContext()</code> method.</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>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="#all_errors_class-error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="#all_errors_class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>Runs the compiled code contained by the <code>vm.Script</code> object within the given
<code>contextifiedObject</code> and returns the result. Running code does not have access
to local scope.</p>
<p>The following example compiles code that increments a global variable, sets
the value of another global variable, then execute the code multiple times.
The globals are contained in the <code>context</code> object.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> context = {
<span class="hljs-attr">animal</span>: <span class="hljs-string">'cat'</span>,
<span class="hljs-attr">count</span>: <span class="hljs-number">2</span>,
};
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'count += 1; name = "kitty";'</span>);
vm.<span class="hljs-title function_">createContext</span>(context);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">10</span>; ++i) {
script.<span class="hljs-title function_">runInContext</span>(context);
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context);
<span class="hljs-comment">// Prints: { animal: 'cat', count: 12, name: 'kitty' }</span></code> <button class="copy-button">copy</button></pre>
<p>Using the <code>timeout</code> or <code>breakOnSigint</code> options will result in new event loops
and corresponding threads being started, which have a non-zero performance
overhead.</p>
<h4><code>script.runInNewContext([contextObject[, options]])</code><span><a class="mark" href="#all_vm_scriptruninnewcontextcontextobject-options" id="all_vm_scriptruninnewcontextcontextobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_runinnewcontext_contextobject_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>v20.18.0</td>
<td><p>The <code>contextObject</code> argument now accepts <code>vm.constants.DONT_CONTEXTIFY</code>.</p></td></tr>
<tr><td>v14.6.0</td>
<td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="#all_vm_vmconstantsdont_contextify" class="type"><vm.constants.DONT_CONTEXTIFY></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a>
Either <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> or an object that will be <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a>.
If <code>undefined</code>, an empty contextified object will be created for backwards compatibility.</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>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="#all_errors_class-error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="#all_errors_class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
<li><code>contextName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Human-readable name of the newly created context.
<strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of
the created context.</li>
<li><code>contextOrigin</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/Glossary/Origin">Origin</a> corresponding to the newly
created context for display purposes. The origin should be formatted like a
URL, but with only the scheme, host, and port (if necessary), like the
value of the <a href="#all_url_urlorigin"><code>url.origin</code></a> property of a <a href="#all_url_class-url"><code>URL</code></a> object. Most notably,
this string should omit the trailing slash, as that denotes a path.
<strong>Default:</strong> <code>''</code>.</li>
<li><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to false any calls to <code>eval</code> or function
constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an
<code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li>
<li><code>wasm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to false any attempt to compile a WebAssembly
module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li><code>microtaskMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If set to <code>afterEvaluate</code>, microtasks (tasks
scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately
after the script has run. They are included in the <code>timeout</code> and
<code>breakOnSigint</code> scopes in that case.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>This method is a shortcut to <code>script.runInContext(vm.createContext(options), options)</code>.
It does several things at once:</p>
<ol>
<li>Creates a new context.</li>
<li>If <code>contextObject</code> is an object, <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextifies</a> it with the new context.
If <code>contextObject</code> is undefined, creates a new object and <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextifies</a> it.
If <code>contextObject</code> is <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a>, don't <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextify</a> anything.</li>
<li>Runs the compiled code contained by the <code>vm.Script</code> object within the created context. The code
does not have access to the scope in which this method is called.</li>
<li>Returns the result.</li>
</ol>
<p>The following example compiles code that sets a global variable, then executes
the code multiple times in different contexts. The globals are set on and
contained within each individual <code>context</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'globalVar = "set"'</span>);
<span class="hljs-keyword">const</span> contexts = [{}, {}, {}];
contexts.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
script.<span class="hljs-title function_">runInNewContext</span>(context);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contexts);
<span class="hljs-comment">// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]</span>
<span class="hljs-comment">// This would throw if the context is created from a contextified object.</span>
<span class="hljs-comment">// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary</span>
<span class="hljs-comment">// global objects that can be frozen.</span>
<span class="hljs-keyword">const</span> freezeScript = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'Object.freeze(globalThis); globalThis;'</span>);
<span class="hljs-keyword">const</span> frozenContext = freezeScript.<span class="hljs-title function_">runInNewContext</span>(vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>script.runInThisContext([options])</code><span><a class="mark" href="#all_vm_scriptruninthiscontextoptions" id="all_vm_scriptruninthiscontextoptions">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_runinthiscontext_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>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></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>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="#all_errors_class-error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="#all_errors_class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>Runs the compiled code contained by the <code>vm.Script</code> within the context of the
current <code>global</code> object. Running code does not have access to local scope, but
<em>does</em> have access to the current <code>global</code> object.</p>
<p>The following example compiles code that increments a <code>global</code> variable then
executes that code multiple times:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span> = <span class="hljs-number">0</span>;
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'globalVar += 1'</span>, { <span class="hljs-attr">filename</span>: <span class="hljs-string">'myfile.vm'</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">1000</span>; ++i) {
script.<span class="hljs-title function_">runInThisContext</span>();
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(globalVar);
<span class="hljs-comment">// 1000</span></code> <button class="copy-button">copy</button></pre>
<h4><code>script.sourceMapURL</code><span><a class="mark" href="#all_vm_scriptsourcemapurl" id="all_vm_scriptsourcemapurl">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_sourcemapurl"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<ul>
<li><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#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>When the script is compiled from a source that contains a source map magic
comment, this property will be set to the URL of the source map.</p>
<pre class="with-30-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> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">`
function myFunc() {}
//# sourceMappingURL=sourcemap.json
`</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(script.<span class="hljs-property">sourceMapURL</span>);
<span class="hljs-comment">// Prints: sourcemap.json</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">`
function myFunc() {}
//# sourceMappingURL=sourcemap.json
`</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(script.<span class="hljs-property">sourceMapURL</span>);
<span class="hljs-comment">// Prints: sourcemap.json</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>vm.Module</code><span><a class="mark" href="#all_vm_class-vmmodule" id="all_vm_class-vmmodule">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_module"></a></h3>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</p>
<p>The <code>vm.Module</code> class provides a low-level interface for using
ECMAScript modules in VM contexts. It is the counterpart of the <code>vm.Script</code>
class that closely mirrors <a href="https://262.ecma-international.org/14.0/#sec-abstract-module-records">Module Record</a>s as defined in the ECMAScript
specification.</p>
<p>Unlike <code>vm.Script</code> however, every <code>vm.Module</code> object is bound to a context from
its creation. Operations on <code>vm.Module</code> objects are intrinsically asynchronous,
in contrast with the synchronous nature of <code>vm.Script</code> objects. The use of
'async' functions can help with manipulating <code>vm.Module</code> objects.</p>
<p>Using a <code>vm.Module</code> object requires three distinct steps: creation/parsing,
linking, and evaluation. These three steps are illustrated in the following
example.</p>
<p>This implementation lies at a lower level than the <a href="#all_esm_modules-ecmascript-modules">ECMAScript Module
loader</a>. There is also no way to interact with the Loader yet, though
support is planned.</p>
<pre class="with-30-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> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;
<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({
<span class="hljs-attr">secret</span>: <span class="hljs-number">42</span>,
<span class="hljs-attr">print</span>: <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>,
});
<span class="hljs-comment">// Step 1</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Create a Module by constructing a new `vm.SourceTextModule` object. This</span>
<span class="hljs-comment">// parses the provided source text, throwing a `SyntaxError` if anything goes</span>
<span class="hljs-comment">// wrong. By default, a Module is created in the top context. But here, we</span>
<span class="hljs-comment">// specify `contextifiedObject` as the context this Module belongs to.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Here, we attempt to obtain the default export from the module "foo", and</span>
<span class="hljs-comment">// put it into local binding "secret".</span>
<span class="hljs-keyword">const</span> bar = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
import s from 'foo';
s;
print(s);
`</span>, { <span class="hljs-attr">context</span>: contextifiedObject });
<span class="hljs-comment">// Step 2</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// "Link" the imported dependencies of this Module to it.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The provided linking callback (the "linker") accepts two arguments: the</span>
<span class="hljs-comment">// parent module (`bar` in this case) and the string that is the specifier of</span>
<span class="hljs-comment">// the imported module. The callback is expected to return a Module that</span>
<span class="hljs-comment">// corresponds to the provided specifier, with certain requirements documented</span>
<span class="hljs-comment">// in `module.link()`.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// If linking has not started for the returned Module, the same linker</span>
<span class="hljs-comment">// callback will be called on the returned Module.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Even top-level Modules without dependencies must be explicitly linked. The</span>
<span class="hljs-comment">// callback provided would never be called, however.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The link() method returns a Promise that will be resolved when all the</span>
<span class="hljs-comment">// Promises returned by the linker resolve.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Note: This is a contrived example in that the linker function creates a new</span>
<span class="hljs-comment">// "foo" module every time it is called. In a full-fledged module system, a</span>
<span class="hljs-comment">// cache would probably be used to avoid duplicated modules.</span>
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">linker</span>(<span class="hljs-params">specifier, referencingModule</span>) {
<span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'foo'</span>) {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
// The "secret" variable refers to the global variable we added to
// "contextifiedObject" when creating the context.
export default secret;
`</span>, { <span class="hljs-attr">context</span>: referencingModule.<span class="hljs-property">context</span> });
<span class="hljs-comment">// Using `contextifiedObject` instead of `referencingModule.context`</span>
<span class="hljs-comment">// here would work as well.</span>
}
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Unable to resolve dependency: <span class="hljs-subst">${specifier}</span>`</span>);
}
<span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">link</span>(linker);
<span class="hljs-comment">// Step 3</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Evaluate the Module. The evaluate() method returns a promise which will</span>
<span class="hljs-comment">// resolve after the module has finished evaluating.</span>
<span class="hljs-comment">// Prints 42.</span>
<span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">evaluate</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({
<span class="hljs-attr">secret</span>: <span class="hljs-number">42</span>,
<span class="hljs-attr">print</span>: <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>,
});
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-comment">// Step 1</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Create a Module by constructing a new `vm.SourceTextModule` object. This</span>
<span class="hljs-comment">// parses the provided source text, throwing a `SyntaxError` if anything goes</span>
<span class="hljs-comment">// wrong. By default, a Module is created in the top context. But here, we</span>
<span class="hljs-comment">// specify `contextifiedObject` as the context this Module belongs to.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Here, we attempt to obtain the default export from the module "foo", and</span>
<span class="hljs-comment">// put it into local binding "secret".</span>
<span class="hljs-keyword">const</span> bar = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
import s from 'foo';
s;
print(s);
`</span>, { <span class="hljs-attr">context</span>: contextifiedObject });
<span class="hljs-comment">// Step 2</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// "Link" the imported dependencies of this Module to it.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The provided linking callback (the "linker") accepts two arguments: the</span>
<span class="hljs-comment">// parent module (`bar` in this case) and the string that is the specifier of</span>
<span class="hljs-comment">// the imported module. The callback is expected to return a Module that</span>
<span class="hljs-comment">// corresponds to the provided specifier, with certain requirements documented</span>
<span class="hljs-comment">// in `module.link()`.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// If linking has not started for the returned Module, the same linker</span>
<span class="hljs-comment">// callback will be called on the returned Module.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Even top-level Modules without dependencies must be explicitly linked. The</span>
<span class="hljs-comment">// callback provided would never be called, however.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The link() method returns a Promise that will be resolved when all the</span>
<span class="hljs-comment">// Promises returned by the linker resolve.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Note: This is a contrived example in that the linker function creates a new</span>
<span class="hljs-comment">// "foo" module every time it is called. In a full-fledged module system, a</span>
<span class="hljs-comment">// cache would probably be used to avoid duplicated modules.</span>
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">linker</span>(<span class="hljs-params">specifier, referencingModule</span>) {
<span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'foo'</span>) {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
// The "secret" variable refers to the global variable we added to
// "contextifiedObject" when creating the context.
export default secret;
`</span>, { <span class="hljs-attr">context</span>: referencingModule.<span class="hljs-property">context</span> });
<span class="hljs-comment">// Using `contextifiedObject` instead of `referencingModule.context`</span>
<span class="hljs-comment">// here would work as well.</span>
}
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Unable to resolve dependency: <span class="hljs-subst">${specifier}</span>`</span>);
}
<span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">link</span>(linker);
<span class="hljs-comment">// Step 3</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Evaluate the Module. The evaluate() method returns a promise which will</span>
<span class="hljs-comment">// resolve after the module has finished evaluating.</span>
<span class="hljs-comment">// Prints 42.</span>
<span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">evaluate</span>();
})();</code><button class="copy-button">copy</button></pre>
<h4><code>module.dependencySpecifiers</code><span><a class="mark" href="#all_vm_moduledependencyspecifiers" id="all_vm_moduledependencyspecifiers">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_dependencyspecifiers"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>The specifiers of all dependencies of this module. The returned array is frozen
to disallow any changes to it.</p>
<p>Corresponds to the <code>[[RequestedModules]]</code> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>s in
the ECMAScript specification.</p>
<h4><code>module.error</code><span><a class="mark" href="#all_vm_moduleerror" id="all_vm_moduleerror">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_error"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>If the <code>module.status</code> is <code>'errored'</code>, this property contains the exception
thrown by the module during evaluation. If the status is anything else,
accessing this property will result in a thrown exception.</p>
<p>The value <code>undefined</code> cannot be used for cases where there is not a thrown
exception due to possible ambiguity with <code>throw undefined;</code>.</p>
<p>Corresponds to the <code>[[EvaluationError]]</code> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>s
in the ECMAScript specification.</p>
<h4><code>module.evaluate([options])</code><span><a class="mark" href="#all_vm_moduleevaluateoptions" id="all_vm_moduleevaluateoptions">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_evaluate_options"></a></h4>
<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>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to evaluate
before terminating execution. If execution is interrupted, an <a href="#all_errors_class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <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 with <code>undefined</code> upon success.</li>
</ul>
<p>Evaluate the module.</p>
<p>This must be called after the module has been linked; otherwise it will reject.
It could be called also when the module has already been evaluated, in which
case it will either do nothing if the initial evaluation ended in success
(<code>module.status</code> is <code>'evaluated'</code>) or it will re-throw the exception that the
initial evaluation resulted in (<code>module.status</code> is <code>'errored'</code>).</p>
<p>This method cannot be called while the module is being evaluated
(<code>module.status</code> is <code>'evaluating'</code>).</p>
<p>Corresponds to the <a href="https://tc39.es/ecma262/#sec-moduleevaluation">Evaluate() concrete method</a> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module
Record</a>s in the ECMAScript specification.</p>
<h4><code>module.identifier</code><span><a class="mark" href="#all_vm_moduleidentifier" id="all_vm_moduleidentifier">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_identifier"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The identifier of the current module, as set in the constructor.</p>
<h4><code>module.link(linker)</code><span><a class="mark" href="#all_vm_modulelinklinker" id="all_vm_modulelinklinker">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_link_linker"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The option <code>extra.assert</code> is renamed to <code>extra.attributes</code>. The former name is still provided for backward compatibility.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>linker</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<ul>
<li>
<p><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The specifier of the requested module:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> foo <span class="hljs-keyword">from</span> <span class="hljs-string">'foo'</span>;
<span class="hljs-comment">// ^^^^^ the module specifier</span></code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p><code>referencingModule</code> <a href="#all_vm_class-vmmodule" class="type"><vm.Module></a> The <code>Module</code> object <code>link()</code> is called on.</p>
</li>
<li>
<p><code>extra</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p>
<ul>
<li><code>attributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The data from the attribute:
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> foo <span class="hljs-keyword">from</span> <span class="hljs-string">'foo'</span> <span class="hljs-keyword">with</span> { <span class="hljs-attr">name</span>: <span class="hljs-string">'value'</span> };
<span class="hljs-comment">// ^^^^^^^^^^^^^^^^^ the attribute</span></code> <button class="copy-button">copy</button></pre>
Per ECMA-262, hosts are expected to trigger an error if an
unsupported attribute is present.</li>
<li><code>assert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Alias for <code>extra.attributes</code>.</li>
</ul>
</li>
<li>
<p>Returns: <a href="#all_vm_class-vmmodule" class="type"><vm.Module></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></p>
</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Link module dependencies. This method must be called before evaluation, and
can only be called once per module.</p>
<p>The function is expected to return a <code>Module</code> object or a <code>Promise</code> that
eventually resolves to a <code>Module</code> object. The returned <code>Module</code> must satisfy the
following two invariants:</p>
<ul>
<li>It must belong to the same context as the parent <code>Module</code>.</li>
<li>Its <code>status</code> must not be <code>'errored'</code>.</li>
</ul>
<p>If the returned <code>Module</code>'s <code>status</code> is <code>'unlinked'</code>, this method will be
recursively called on the returned <code>Module</code> with the same provided <code>linker</code>
function.</p>
<p><code>link()</code> returns a <code>Promise</code> that will either get resolved when all linking
instances resolve to a valid <code>Module</code>, or rejected if the linker function either
throws an exception or returns an invalid <code>Module</code>.</p>
<p>The linker function roughly corresponds to the implementation-defined
<a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> abstract operation in the ECMAScript
specification, with a few key differences:</p>
<ul>
<li>The linker function is allowed to be asynchronous while
<a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> is synchronous.</li>
</ul>
<p>The actual <a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> implementation used during module
linking is one that returns the modules linked during linking. Since at
that point all modules would have been fully linked already, the
<a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> implementation is fully synchronous per
specification.</p>
<p>Corresponds to the <a href="https://tc39.es/ecma262/#sec-moduledeclarationlinking">Link() concrete method</a> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module
Record</a>s in the ECMAScript specification.</p>
<h4><code>module.namespace</code><span><a class="mark" href="#all_vm_modulenamespace" id="all_vm_modulenamespace">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_namespace"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>The namespace object of the module. This is only available after linking
(<code>module.link()</code>) has completed.</p>
<p>Corresponds to the <a href="https://tc39.es/ecma262/#sec-getmodulenamespace">GetModuleNamespace</a> abstract operation in the ECMAScript
specification.</p>
<h4><code>module.status</code><span><a class="mark" href="#all_vm_modulestatus" id="all_vm_modulestatus">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_status"></a></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The current status of the module. Will be one of:</p>
<ul>
<li>
<p><code>'unlinked'</code>: <code>module.link()</code> has not yet been called.</p>
</li>
<li>
<p><code>'linking'</code>: <code>module.link()</code> has been called, but not all Promises returned
by the linker function have been resolved yet.</p>
</li>
<li>
<p><code>'linked'</code>: The module has been linked successfully, and all of its
dependencies are linked, but <code>module.evaluate()</code> has not yet been called.</p>
</li>
<li>
<p><code>'evaluating'</code>: The module is being evaluated through a <code>module.evaluate()</code> on
itself or a parent module.</p>
</li>
<li>
<p><code>'evaluated'</code>: The module has been successfully evaluated.</p>
</li>
<li>
<p><code>'errored'</code>: The module has been evaluated, but an exception was thrown.</p>
</li>
</ul>
<p>Other than <code>'errored'</code>, this status string corresponds to the specification's
<a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>'s <code>[[Status]]</code> field. <code>'errored'</code> corresponds to
<code>'evaluated'</code> in the specification, but with <code>[[EvaluationError]]</code> set to a
value that is not <code>undefined</code>.</p>
</section><section><h3>Class: <code>vm.SourceTextModule</code><span><a class="mark" href="#all_vm_class-vmsourcetextmodule" id="all_vm_class-vmsourcetextmodule">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_sourcetextmodule"></a></h3>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</p>
<ul>
<li>Extends: <a href="#all_vm_class-vmmodule" class="type"><vm.Module></a></li>
</ul>
<p>The <code>vm.SourceTextModule</code> class provides the <a href="https://tc39.es/ecma262/#sec-source-text-module-records">Source Text Module Record</a> as
defined in the ECMAScript specification.</p>
<h4><code>new vm.SourceTextModule(code[, options])</code><span><a class="mark" href="#all_vm_new-vmsourcetextmodulecode-options" id="all_vm_new-vmsourcetextmodulecode-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_new_vm_sourcetextmodule_code_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>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> JavaScript Module code to parse</li>
<li><code>options</code>
<ul>
<li><code>identifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> String used in stack traces.
<strong>Default:</strong> <code>'vm:module(i)'</code> where <code>i</code> is a context-specific ascending
index.</li>
<li><code>cachedData</code> <a href="#all_buffer_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> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. The <code>code</code> must be the same as the module from which this
<code>cachedData</code> was created.</li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> object as returned by the
<code>vm.createContext()</code> method, to compile and evaluate this <code>Module</code> in.
If no context is specified, the module is evaluated in the current
execution context.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the line number offset that is displayed
in stack traces produced by this <code>Module</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this <code>Module</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>initializeImportMeta</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called during evaluation of this <code>Module</code>
to initialize the <code>import.meta</code>.
<ul>
<li><code>meta</code> <a href="#all_esm_importmeta" class="type"><import.meta></a></li>
<li><code>module</code> <a href="#all_vm_class-vmsourcetextmodule" class="type"><vm.SourceTextModule></a></li>
</ul>
</li>
<li><code>importModuleDynamically</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Used to specify the
how the modules should be loaded during the evaluation of this module
when <code>import()</code> is called. This option is part of the experimental
modules API. We do not recommend using it in a production environment.
For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>SourceTextModule</code> instance.</p>
<p>Properties assigned to the <code>import.meta</code> object that are objects may
allow the module to access information outside the specified <code>context</code>. Use
<code>vm.runInContext()</code> to create objects in a specific context.</p>
<pre class="with-60-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> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;
<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({ <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span> });
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(
<span class="hljs-string">'Object.getPrototypeOf(import.meta.prop).secret = secret;'</span>,
{
<span class="hljs-title function_">initializeImportMeta</span>(<span class="hljs-params">meta</span>) {
<span class="hljs-comment">// Note: this object is created in the top context. As such,</span>
<span class="hljs-comment">// Object.getPrototypeOf(import.meta.prop) points to the</span>
<span class="hljs-comment">// Object.prototype in the top context rather than that in</span>
<span class="hljs-comment">// the contextified object.</span>
meta.<span class="hljs-property">prop</span> = {};
},
});
<span class="hljs-comment">// Since module has no dependencies, the linker function will never be called.</span>
<span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">evaluate</span>();
<span class="hljs-comment">// Now, Object.prototype.secret will be equal to 42.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// To fix this problem, replace</span>
<span class="hljs-comment">// meta.prop = {};</span>
<span class="hljs-comment">// above with</span>
<span class="hljs-comment">// meta.prop = vm.runInContext('{}', contextifiedObject);</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({ <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span> });
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(
<span class="hljs-string">'Object.getPrototypeOf(import.meta.prop).secret = secret;'</span>,
{
<span class="hljs-title function_">initializeImportMeta</span>(<span class="hljs-params">meta</span>) {
<span class="hljs-comment">// Note: this object is created in the top context. As such,</span>
<span class="hljs-comment">// Object.getPrototypeOf(import.meta.prop) points to the</span>
<span class="hljs-comment">// Object.prototype in the top context rather than that in</span>
<span class="hljs-comment">// the contextified object.</span>
meta.<span class="hljs-property">prop</span> = {};
},
});
<span class="hljs-comment">// Since module has no dependencies, the linker function will never be called.</span>
<span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">evaluate</span>();
<span class="hljs-comment">// Now, Object.prototype.secret will be equal to 42.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// To fix this problem, replace</span>
<span class="hljs-comment">// meta.prop = {};</span>
<span class="hljs-comment">// above with</span>
<span class="hljs-comment">// meta.prop = vm.runInContext('{}', contextifiedObject);</span>
})();</code><button class="copy-button">copy</button></pre>
<h4><code>sourceTextModule.createCachedData()</code><span><a class="mark" href="#all_vm_sourcetextmodulecreatecacheddata" id="all_vm_sourcetextmodulecreatecacheddata">#</a></span><a aria-hidden="true" class="legacy" id="vm_sourcetextmodule_createcacheddata"></a></h4>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0</span>
</div>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Creates a code cache that can be used with the <code>SourceTextModule</code> constructor's
<code>cachedData</code> option. Returns a <code>Buffer</code>. This method may be called any number
of times before the module has been evaluated.</p>
<p>The code cache of the <code>SourceTextModule</code> doesn't contain any JavaScript
observable states. The code cache is safe to be saved along side the script
source and used to construct new <code>SourceTextModule</code> instances multiple times.</p>
<p>Functions in the <code>SourceTextModule</code> source can be marked as lazily compiled
and they are not compiled at construction of the <code>SourceTextModule</code>. These
functions are going to be compiled when they are invoked the first time. The
code cache serializes the metadata that V8 currently knows about the
<code>SourceTextModule</code> that it can use to speed up future compilations.</p>
<pre><code class="language-js"><span class="hljs-comment">// Create an initial module</span>
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">'const a = 1;'</span>);
<span class="hljs-comment">// Create cached data from this module</span>
<span class="hljs-keyword">const</span> cachedData = <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">createCachedData</span>();
<span class="hljs-comment">// Create a new module using the cached data. The code must be the same.</span>
<span class="hljs-keyword">const</span> module2 = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">'const a = 1;'</span>, { cachedData });</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>vm.SyntheticModule</code><span><a class="mark" href="#all_vm_class-vmsyntheticmodule" id="all_vm_class-vmsyntheticmodule">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_syntheticmodule"></a></h3>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</p>
<ul>
<li>Extends: <a href="#all_vm_class-vmmodule" class="type"><vm.Module></a></li>
</ul>
<p>The <code>vm.SyntheticModule</code> class provides the <a href="https://heycam.github.io/webidl/#synthetic-module-records">Synthetic Module Record</a> as
defined in the WebIDL specification. The purpose of synthetic modules is to
provide a generic interface for exposing non-JavaScript sources to ECMAScript
module graphs.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> source = <span class="hljs-string">'{ "a": 1 }'</span>;
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'default'</span>], <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> obj = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(source);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'default'</span>, obj);
});
<span class="hljs-comment">// Use `module` in linking...</span></code> <button class="copy-button">copy</button></pre>
<h4><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code><span><a class="mark" href="#all_vm_new-vmsyntheticmoduleexportnames-evaluatecallback-options" id="all_vm_new-vmsyntheticmoduleexportnames-evaluatecallback-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_new_vm_syntheticmodule_exportnames_evaluatecallback_options"></a></h4>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0</span>
</div>
<ul>
<li><code>exportNames</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Array of names that will be exported from the
module.</li>
<li><code>evaluateCallback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called when the module is evaluated.</li>
<li><code>options</code>
<ul>
<li><code>identifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> String used in stack traces.
<strong>Default:</strong> <code>'vm:module(i)'</code> where <code>i</code> is a context-specific ascending
index.</li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> object as returned by the
<code>vm.createContext()</code> method, to compile and evaluate this <code>Module</code> in.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>SyntheticModule</code> instance.</p>
<p>Objects assigned to the exports of this instance may allow importers of
the module to access information outside the specified <code>context</code>. Use
<code>vm.runInContext()</code> to create objects in a specific context.</p>
<h4><code>syntheticModule.setExport(name, value)</code><span><a class="mark" href="#all_vm_syntheticmodulesetexportname-value" id="all_vm_syntheticmodulesetexportname-value">#</a></span><a aria-hidden="true" class="legacy" id="vm_syntheticmodule_setexport_name_value"></a></h4>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the export to set.</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The value to set the export to.</li>
</ul>
<p>This method is used after the module is linked to set the values of exports. If
it is called before the module is linked, an <a href="#all_errors_err_vm_module_status"><code>ERR_VM_MODULE_STATUS</code></a> error
will be thrown.</p>
<pre class="with-30-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> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;
<span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'x'</span>], <span class="hljs-function">() =></span> {
m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'x'</span>, <span class="hljs-number">1</span>);
});
<span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-keyword">await</span> m.<span class="hljs-title function_">evaluate</span>();
assert.<span class="hljs-title function_">strictEqual</span>(m.<span class="hljs-property">namespace</span>.<span class="hljs-property">x</span>, <span class="hljs-number">1</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'x'</span>], <span class="hljs-function">() =></span> {
m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'x'</span>, <span class="hljs-number">1</span>);
});
<span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-keyword">await</span> m.<span class="hljs-title function_">evaluate</span>();
assert.<span class="hljs-title function_">strictEqual</span>(m.<span class="hljs-property">namespace</span>.<span class="hljs-property">x</span>, <span class="hljs-number">1</span>);
})();</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.compileFunction(code[, params[, options]])</code><span><a class="mark" href="#all_vm_vmcompilefunctioncode-params-options" id="all_vm_vmcompilefunctioncode-params-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_compilefunction_code_params_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v19.6.0, v18.15.0</td>
<td><p>The return value now includes <code>cachedDataRejected</code> with the same semantics as the <code>vm.Script</code> version if the <code>cachedData</code> option was passed.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
<tr><td>v15.9.0</td>
<td><p>Added <code>importModuleDynamically</code> option again.</p></td></tr>
<tr><td>v14.3.0</td>
<td><p>Removal of <code>importModuleDynamically</code> due to compatibility issues.</p></td></tr>
<tr><td>v14.1.0, v13.14.0</td>
<td><p>The <code>importModuleDynamically</code> option is now supported.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p><span>Added in: v10.10.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The body of the function to compile.</li>
<li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array of strings containing all parameters for the
function.</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>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>''</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>cachedData</code> <a href="#all_buffer_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> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. This must be produced by a prior call to <a href="#all_vm_vmcompilefunctioncode-params-options"><code>vm.compileFunction()</code></a>
with the same <code>code</code> and <code>params</code>.</li>
<li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Specifies whether to produce new cache data.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>parsingContext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> object in which the said
function should be compiled in.</li>
<li><code>contextExtensions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> An array containing a collection of context
extensions (objects wrapping the current scope) to be applied while
compiling. <strong>Default:</strong> <code>[]</code>.</li>
</ul>
</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_vm_vmconstantsuse_main_context_default_loader" class="type"><vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation of
this function when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>Compiles the given code into the provided context (if no context is
supplied, the current context is used), and returns it wrapped inside a
function with the given <code>params</code>.</p>
</section><section><h3><code>vm.constants</code><span><a class="mark" href="#all_vm_vmconstants" id="all_vm_vmconstants">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_constants"></a></h3>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>Returns an object containing commonly used constants for VM operations.</p>
<h4><code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code><span><a class="mark" href="#all_vm_vmconstantsuse_main_context_default_loader" id="all_vm_vmconstantsuse_main_context_default_loader">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_constants_use_main_context_default_loader"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>A constant that can be used as the <code>importModuleDynamically</code> option to
<code>vm.Script</code> and <code>vm.compileFunction()</code> so that Node.js uses the default
ESM loader from the main context to load the requested module.</p>
<p>For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</p>
</section><section><h3><code>vm.createContext([contextObject[, options]])</code><span><a class="mark" href="#all_vm_vmcreatecontextcontextobject-options" id="all_vm_vmcreatecontextcontextobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_createcontext_contextobject_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>The <code>contextObject</code> argument now accepts <code>vm.constants.DONT_CONTEXTIFY</code>.</p></td></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v20.11.0</td>
<td><p>The <code>importModuleDynamically</code> option is supported now.</p></td></tr>
<tr><td>v14.6.0</td>
<td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The first argument can no longer be a function.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>codeGeneration</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="#all_vm_vmconstantsdont_contextify" class="type"><vm.constants.DONT_CONTEXTIFY></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a>
Either <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> or an object that will be <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a>.
If <code>undefined</code>, an empty contextified object will be created for backwards compatibility.</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>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Human-readable name of the newly created context.
<strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of
the created context.</li>
<li><code>origin</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/Glossary/Origin">Origin</a> corresponding to the newly created
context for display purposes. The origin should be formatted like a URL,
but with only the scheme, host, and port (if necessary), like the value of
the <a href="#all_url_urlorigin"><code>url.origin</code></a> property of a <a href="#all_url_class-url"><code>URL</code></a> object. Most notably, this
string should omit the trailing slash, as that denotes a path.
<strong>Default:</strong> <code>''</code>.</li>
<li><code>codeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to false any calls to <code>eval</code> or function
constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an
<code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li>
<li><code>wasm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to false any attempt to compile a WebAssembly
module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li><code>microtaskMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If set to <code>afterEvaluate</code>, microtasks (tasks
scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately
after a script has run through <a href="#all_vm_scriptrunincontextcontextifiedobject-options"><code>script.runInContext()</code></a>.
They are included in the <code>timeout</code> and <code>breakOnSigint</code> scopes in that case.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_vm_vmconstantsuse_main_context_default_loader" class="type"><vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded when <code>import()</code> is
called in this context without a referrer script or module. This option is
part of the experimental modules API. We do not recommend using it in a
production environment. For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> contextified object.</li>
</ul>
<p>If the given <code>contextObject</code> is an object, the <code>vm.createContext()</code> method will <a href="#all_vm_what-does-it-mean-to-contextify-an-object">prepare that
object</a> and return a reference to it so that it can be used in
calls to <a href="#all_vm_vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext()</code></a> or <a href="#all_vm_scriptrunincontextcontextifiedobject-options"><code>script.runInContext()</code></a>. Inside such
scripts, the global object will be wrapped by the <code>contextObject</code>, retaining all of its
existing properties but also having the built-in objects and functions any
standard <a href="https://es5.github.io/#x15.1">global object</a> has. Outside of scripts run by the vm module, global
variables will remain unchanged.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span> = <span class="hljs-number">3</span>;
<span class="hljs-keyword">const</span> context = { <span class="hljs-attr">globalVar</span>: <span class="hljs-number">1</span> };
vm.<span class="hljs-title function_">createContext</span>(context);
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalVar *= 2;'</span>, context);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context);
<span class="hljs-comment">// Prints: { globalVar: 2 }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span>);
<span class="hljs-comment">// Prints: 3</span></code> <button class="copy-button">copy</button></pre>
<p>If <code>contextObject</code> is omitted (or passed explicitly as <code>undefined</code>), a new,
empty <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> object will be returned.</p>
<p>When the global object in the newly created context is <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a>, it has some quirks
compared to ordinary global objects. For example, it cannot be frozen. To create a context
without the contextifying quirks, pass <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> as the <code>contextObject</code>
argument. See the documentation of <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> for details.</p>
<p>The <code>vm.createContext()</code> method is primarily useful for creating a single
context that can be used to run multiple scripts. For instance, if emulating a
web browser, the method can be used to create a single context representing a
window's global object, then run all <code><script></code> tags together within that
context.</p>
<p>The provided <code>name</code> and <code>origin</code> of the context are made visible through the
Inspector API.</p>
</section><section><h3><code>vm.isContext(object)</code><span><a class="mark" href="#all_vm_vmiscontextobject" id="all_vm_vmiscontextobject">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_iscontext_object"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.7</span>
</div>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></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 <code>true</code> if the given <code>object</code> object has been <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> using
<a href="#all_vm_vmcreatecontextcontextobject-options"><code>vm.createContext()</code></a>, or if it's the global object of a context created
using <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a>.</p>
</section><section><h3><code>vm.measureMemory([options])</code><span><a class="mark" href="#all_vm_vmmeasurememoryoptions" id="all_vm_vmmeasurememoryoptions">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_measurememory_options"></a></h3>
<div class="api_metadata">
<span>Added in: v13.10.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Measure the memory known to V8 and used by all contexts known to the
current V8 isolate, or the main context.</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> Optional.
<ul>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>'summary'</code> or <code>'detailed'</code>. In summary mode,
only the memory measured for the main context will be returned. In
detailed mode, the memory measured for all contexts known to the
current V8 isolate will be returned.
<strong>Default:</strong> <code>'summary'</code></li>
<li><code>execution</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>'default'</code> or <code>'eager'</code>. With default
execution, the promise will not resolve until after the next scheduled
garbage collection starts, which may take a while (or never if the program
exits before the next GC). With eager execution, the GC will be started
right away to measure the memory.
<strong>Default:</strong> <code>'default'</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> If the memory is successfully measured, the promise will
resolve with an object containing information about the memory usage.
Otherwise it will be rejected with an <code>ERR_CONTEXT_NOT_INITIALIZED</code> error.</li>
</ul>
<p>The format of the object that the returned Promise may resolve with is
specific to the V8 engine and may change from one version of V8 to the next.</p>
<p>The returned result is different from the statistics returned by
<code>v8.getHeapSpaceStatistics()</code> in that <code>vm.measureMemory()</code> measure the
memory reachable by each V8 specific contexts in the current instance of
the V8 engine, while the result of <code>v8.getHeapSpaceStatistics()</code> measure
the memory occupied by each heap space in the current V8 instance.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-comment">// Measure the memory used by the main context.</span>
vm.<span class="hljs-title function_">measureMemory</span>({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'summary'</span> })
<span class="hljs-comment">// This is the same as vm.measureMemory()</span>
.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
<span class="hljs-comment">// The current format is:</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">// total: {</span>
<span class="hljs-comment">// jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ]</span>
<span class="hljs-comment">// }</span>
<span class="hljs-comment">// }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
});
<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> });
vm.<span class="hljs-title function_">measureMemory</span>({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'detailed'</span>, <span class="hljs-attr">execution</span>: <span class="hljs-string">'eager'</span> })
.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
<span class="hljs-comment">// Reference the context here so that it won't be GC'ed</span>
<span class="hljs-comment">// until the measurement is complete.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">a</span>);
<span class="hljs-comment">// {</span>
<span class="hljs-comment">// total: {</span>
<span class="hljs-comment">// jsMemoryEstimate: 2574732,</span>
<span class="hljs-comment">// jsMemoryRange: [ 2574732, 2904372 ]</span>
<span class="hljs-comment">// },</span>
<span class="hljs-comment">// current: {</span>
<span class="hljs-comment">// jsMemoryEstimate: 2438996,</span>
<span class="hljs-comment">// jsMemoryRange: [ 2438996, 2768636 ]</span>
<span class="hljs-comment">// },</span>
<span class="hljs-comment">// other: [</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">// jsMemoryEstimate: 135736,</span>
<span class="hljs-comment">// jsMemoryRange: [ 135736, 465376 ]</span>
<span class="hljs-comment">// }</span>
<span class="hljs-comment">// ]</span>
<span class="hljs-comment">// }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.runInContext(code, contextifiedObject[, options])</code><span><a class="mark" href="#all_vm_vmrunincontextcode-contextifiedobject-options" id="all_vm_vmrunincontextcode-contextifiedobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_runincontext_code_contextifiedobject_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile and run.</li>
<li><code>contextifiedObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> object that will be used
as the <code>global</code> when the <code>code</code> is compiled and run.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.<anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="#all_errors_class-error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="#all_errors_class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
<li><code>cachedData</code> <a href="#all_buffer_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> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_vm_vmconstantsuse_main_context_default_loader" class="type"><vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
</ul>
<p>The <code>vm.runInContext()</code> method compiles <code>code</code>, runs it within the context of
the <code>contextifiedObject</code>, then returns the result. Running code does not have
access to the local scope. The <code>contextifiedObject</code> object <em>must</em> have been
previously <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> using the <a href="#all_vm_vmcreatecontextcontextobject-options"><code>vm.createContext()</code></a> method.</p>
<p>If <code>options</code> is a string, then it specifies the filename.</p>
<p>The following example compiles and executes different scripts using a single
<a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> object:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> contextObject = { <span class="hljs-attr">globalVar</span>: <span class="hljs-number">1</span> };
vm.<span class="hljs-title function_">createContext</span>(contextObject);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">10</span>; ++i) {
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalVar *= 2;'</span>, contextObject);
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contextObject);
<span class="hljs-comment">// Prints: { globalVar: 1024 }</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.runInNewContext(code[, contextObject[, options]])</code><span><a class="mark" href="#all_vm_vmruninnewcontextcode-contextobject-options" id="all_vm_vmruninnewcontextcode-contextobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_runinnewcontext_code_contextobject_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>The <code>contextObject</code> argument now accepts <code>vm.constants.DONT_CONTEXTIFY</code>.</p></td></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
<tr><td>v14.6.0</td>
<td><p>The <code>microtaskMode</code> option is supported now.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile and run.</li>
<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="#all_vm_vmconstantsdont_contextify" class="type"><vm.constants.DONT_CONTEXTIFY></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a>
Either <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> or an object that will be <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a>.
If <code>undefined</code>, an empty contextified object will be created for backwards compatibility.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.<anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="#all_errors_class-error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="#all_errors_class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
<li><code>contextName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Human-readable name of the newly created context.
<strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of
the created context.</li>
<li><code>contextOrigin</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/Glossary/Origin">Origin</a> corresponding to the newly
created context for display purposes. The origin should be formatted like a
URL, but with only the scheme, host, and port (if necessary), like the
value of the <a href="#all_url_urlorigin"><code>url.origin</code></a> property of a <a href="#all_url_class-url"><code>URL</code></a> object. Most notably,
this string should omit the trailing slash, as that denotes a path.
<strong>Default:</strong> <code>''</code>.</li>
<li><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to false any calls to <code>eval</code> or function
constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an
<code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li>
<li><code>wasm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to false any attempt to compile a WebAssembly
module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li><code>cachedData</code> <a href="#all_buffer_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> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_vm_vmconstantsuse_main_context_default_loader" class="type"><vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
<li><code>microtaskMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If set to <code>afterEvaluate</code>, microtasks (tasks
scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately
after the script has run. They are included in the <code>timeout</code> and
<code>breakOnSigint</code> scopes in that case.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>This method is a shortcut to
<code>(new vm.Script(code, options)).runInContext(vm.createContext(options), options)</code>.
If <code>options</code> is a string, then it specifies the filename.</p>
<p>It does several things at once:</p>
<ol>
<li>Creates a new context.</li>
<li>If <code>contextObject</code> is an object, <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextifies</a> it with the new context.
If <code>contextObject</code> is undefined, creates a new object and <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextifies</a> it.
If <code>contextObject</code> is <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a>, don't <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextify</a> anything.</li>
<li>Compiles the code as a<code>vm.Script</code></li>
<li>Runs the compield code within the created context. The code does not have access to the scope in
which this method is called.</li>
<li>Returns the result.</li>
</ol>
<p>The following example compiles and executes code that increments a global
variable and sets a new one. These globals are contained in the <code>contextObject</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> contextObject = {
<span class="hljs-attr">animal</span>: <span class="hljs-string">'cat'</span>,
<span class="hljs-attr">count</span>: <span class="hljs-number">2</span>,
};
vm.<span class="hljs-title function_">runInNewContext</span>(<span class="hljs-string">'count += 1; name = "kitty"'</span>, contextObject);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contextObject);
<span class="hljs-comment">// Prints: { animal: 'cat', count: 3, name: 'kitty' }</span>
<span class="hljs-comment">// This would throw if the context is created from a contextified object.</span>
<span class="hljs-comment">// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary global objects that</span>
<span class="hljs-comment">// can be frozen.</span>
<span class="hljs-keyword">const</span> frozenContext = vm.<span class="hljs-title function_">runInNewContext</span>(<span class="hljs-string">'Object.freeze(globalThis); globalThis;'</span>, vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.runInThisContext(code[, options])</code><span><a class="mark" href="#all_vm_vmruninthiscontextcode-options" id="all_vm_vmruninthiscontextcode-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_runinthiscontext_code_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile and run.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.<anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the first-line column number offset that
is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="#all_errors_class-error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="#all_errors_class-error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
<li><code>cachedData</code> <a href="#all_buffer_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> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_vm_vmconstantsuse_main_context_default_loader" class="type"><vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> the result of the very last statement executed in the script.</li>
</ul>
<p><code>vm.runInThisContext()</code> compiles <code>code</code>, runs it within the context of the
current <code>global</code> and returns the result. Running code does not have access to
local scope, but does have access to the current <code>global</code> object.</p>
<p>If <code>options</code> is a string, then it specifies the filename.</p>
<p>The following example illustrates using both <code>vm.runInThisContext()</code> and
the JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> function to run the same code:</p>
<!-- eslint-disable prefer-const -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">let</span> localVar = <span class="hljs-string">'initial value'</span>;
<span class="hljs-keyword">const</span> vmResult = vm.<span class="hljs-title function_">runInThisContext</span>(<span class="hljs-string">'localVar = "vm";'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`vmResult: '<span class="hljs-subst">${vmResult}</span>', localVar: '<span class="hljs-subst">${localVar}</span>'`</span>);
<span class="hljs-comment">// Prints: vmResult: 'vm', localVar: 'initial value'</span>
<span class="hljs-keyword">const</span> evalResult = <span class="hljs-built_in">eval</span>(<span class="hljs-string">'localVar = "eval";'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`evalResult: '<span class="hljs-subst">${evalResult}</span>', localVar: '<span class="hljs-subst">${localVar}</span>'`</span>);
<span class="hljs-comment">// Prints: evalResult: 'eval', localVar: 'eval'</span></code> <button class="copy-button">copy</button></pre>
<p>Because <code>vm.runInThisContext()</code> does not have access to the local scope,
<code>localVar</code> is unchanged. In contrast, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> <em>does</em> have access to the
local scope, so the value <code>localVar</code> is changed. In this way
<code>vm.runInThisContext()</code> is much like an <a href="https://es5.github.io/#x10.4.2">indirect <code>eval()</code> call</a>, e.g.
<code>(0,eval)('code')</code>.</p>
</section><section><h3>Example: Running an HTTP server within a VM<span><a class="mark" href="#all_vm_example-running-an-http-server-within-a-vm" id="all_vm_example-running-an-http-server-within-a-vm">#</a></span><a aria-hidden="true" class="legacy" id="vm_example_running_an_http_server_within_a_vm"></a></h3>
<p>When using either <a href="#all_vm_scriptruninthiscontextoptions"><code>script.runInThisContext()</code></a> or
<a href="#all_vm_vmruninthiscontextcode-options"><code>vm.runInThisContext()</code></a>, the code is executed within the current V8 global
context. The code passed to this VM context will have its own isolated scope.</p>
<p>In order to run a simple web server using the <code>node:http</code> module the code passed
to the context must either call <code>require('node:http')</code> on its own, or have a
reference to the <code>node:http</code> module passed to it. For instance:</p>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> code = <span class="hljs-string">`
((require) => {
const http = require('node:http');
http.createServer((request, response) => {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end('Hello World\\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
})`</span>;
vm.<span class="hljs-title function_">runInThisContext</span>(code)(<span class="hljs-built_in">require</span>);</code> <button class="copy-button">copy</button></pre>
<p>The <code>require()</code> in the above case shares the state with the context it is
passed from. This may introduce risks when untrusted code is executed, e.g.
altering objects in the context in unwanted ways.</p>
</section><section><h3>What does it mean to "contextify" an object?<span><a class="mark" href="#all_vm_what-does-it-mean-to-contextify-an-object" id="all_vm_what-does-it-mean-to-contextify-an-object">#</a></span><a aria-hidden="true" class="legacy" id="vm_what_does_it_mean_to_contextify_an_object"></a></h3>
<p>All JavaScript executed within Node.js runs within the scope of a "context".
According to the <a href="https://v8.dev/docs/embed#contexts">V8 Embedder's Guide</a>:</p>
<blockquote>
<p>In V8, a context is an execution environment that allows separate, unrelated,
JavaScript applications to run in a single instance of V8. You must explicitly
specify the context in which you want any JavaScript code to be run.</p>
</blockquote>
<p>When the method <code>vm.createContext()</code> is called with an object, the <code>contextObject</code> argument
will be used to wrap the global object of a new instance of a V8 Context
(if <code>contextObject</code> is <code>undefined</code>, a new object will be created from the current context
before its contextified). This V8 Context provides the <code>code</code> run using the <code>node:vm</code>
module's methods with an isolated global environment within which it can operate.
The process of creating the V8 Context and associating it with the <code>contextObject</code>
in the outer context is what this document refers to as "contextifying" the object.</p>
<p>The contextifying would introduce some quirks to the <code>globalThis</code> value in the context.
For example, it cannot be frozen, and it is not reference equal to the <code>contextObject</code>
in the outer context.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-comment">// An undefined `contextObject` option makes the global object contextified.</span>
<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalThis'</span>, context) === context); <span class="hljs-comment">// false</span>
<span class="hljs-comment">// A contextified global object cannot be frozen.</span>
<span class="hljs-keyword">try</span> {
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'Object.freeze(globalThis);'</span>, context);
} <span class="hljs-keyword">catch</span> (e) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-comment">// TypeError: Cannot freeze</span>
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalThis.foo = 1; foo;'</span>, context)); <span class="hljs-comment">// 1</span></code> <button class="copy-button">copy</button></pre>
<p>To create a context with an ordinary global object and get access to a global proxy in
the outer context with fewer quirks, specify <code>vm.constants.DONT_CONTEXTIFY</code> as the
<code>contextObject</code> argument.</p>
<h4><code>vm.constants.DONT_CONTEXTIFY</code><span><a class="mark" href="#all_vm_vmconstantsdont_contextify" id="all_vm_vmconstantsdont_contextify">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_constants_dont_contextify"></a></h4>
<p>This constant, when used as the <code>contextObject</code> argument in vm APIs, instructs Node.js to create
a context without wrapping its global object with another object in a Node.js-specific manner.
As a result, the <code>globalThis</code> value inside the new context would behave more closely to an ordinary
one.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-comment">// Use vm.constants.DONT_CONTEXTIFY to freeze the global object.</span>
<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>(vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'Object.freeze(globalThis);'</span>, context);
<span class="hljs-keyword">try</span> {
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'bar = 1; bar;'</span>, context);
} <span class="hljs-keyword">catch</span> (e) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-comment">// Uncaught ReferenceError: bar is not defined</span>
}</code> <button class="copy-button">copy</button></pre>
<p>When <code>vm.constants.DONT_CONTEXTIFY</code> is used as the <code>contextObject</code> argument to <a href="#all_vm_vmcreatecontextcontextobject-options"><code>vm.createContext()</code></a>,
the returned object is a proxy-like object to the global object in the newly created context with
fewer Node.js-specific quirks. It is reference equal to the <code>globalThis</code> value in the new context,
can be modified from outside the context, and can be used to access built-ins in the new context directly.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>(vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);
<span class="hljs-comment">// Returned object is reference equal to globalThis in the new context.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalThis'</span>, context) === context); <span class="hljs-comment">// true</span>
<span class="hljs-comment">// Can be used to access globals in the new context directly.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">Array</span>); <span class="hljs-comment">// [Function: Array]</span>
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'foo = 1;'</span>, context);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">foo</span>); <span class="hljs-comment">// 1</span>
context.<span class="hljs-property">bar</span> = <span class="hljs-number">1</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'bar;'</span>, context)); <span class="hljs-comment">// 1</span>
<span class="hljs-comment">// Can be frozen and it affects the inner context.</span>
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">freeze</span>(context);
<span class="hljs-keyword">try</span> {
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'baz = 1; baz;'</span>, context);
} <span class="hljs-keyword">catch</span> (e) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-comment">// Uncaught ReferenceError: baz is not defined</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Timeout interactions with asynchronous tasks and Promises<span><a class="mark" href="#all_vm_timeout-interactions-with-asynchronous-tasks-and-promises" id="all_vm_timeout-interactions-with-asynchronous-tasks-and-promises">#</a></span><a aria-hidden="true" class="legacy" id="vm_timeout_interactions_with_asynchronous_tasks_and_promises"></a></h3>
<p><code>Promise</code>s and <code>async function</code>s can schedule tasks run by the JavaScript
engine asynchronously. By default, these tasks are run after all JavaScript
functions on the current stack are done executing.
This allows escaping the functionality of the <code>timeout</code> and
<code>breakOnSigint</code> options.</p>
<p>For example, the following code executed by <code>vm.runInNewContext()</code> with a
timeout of 5 milliseconds schedules an infinite loop to run after a promise
resolves. The scheduled loop is never interrupted by the timeout:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">loop</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'entering loop'</span>);
<span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>());
}
vm.<span class="hljs-title function_">runInNewContext</span>(
<span class="hljs-string">'Promise.resolve().then(() => loop());'</span>,
{ loop, <span class="hljs-variable language_">console</span> },
{ <span class="hljs-attr">timeout</span>: <span class="hljs-number">5</span> },
);
<span class="hljs-comment">// This is printed *before* 'entering loop' (!)</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done executing'</span>);</code> <button class="copy-button">copy</button></pre>
<p>This can be addressed by passing <code>microtaskMode: 'afterEvaluate'</code> to the code
that creates the <code>Context</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">loop</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>());
}
vm.<span class="hljs-title function_">runInNewContext</span>(
<span class="hljs-string">'Promise.resolve().then(() => loop());'</span>,
{ loop, <span class="hljs-variable language_">console</span> },
{ <span class="hljs-attr">timeout</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">microtaskMode</span>: <span class="hljs-string">'afterEvaluate'</span> },
);</code> <button class="copy-button">copy</button></pre>
<p>In this case, the microtask scheduled through <code>promise.then()</code> will be run
before returning from <code>vm.runInNewContext()</code>, and will be interrupted
by the <code>timeout</code> functionality. This applies only to code running in a
<code>vm.Context</code>, so e.g. <a href="#all_vm_vmruninthiscontextcode-options"><code>vm.runInThisContext()</code></a> does not take this option.</p>
<p>Promise callbacks are entered into the microtask queue of the context in which
they were created. For example, if <code>() => loop()</code> is replaced with just <code>loop</code>
in the above example, then <code>loop</code> will be pushed into the global microtask
queue, because it is a function from the outer (main) context, and thus will
also be able to escape the timeout.</p>
<p>If asynchronous scheduling functions such as <code>process.nextTick()</code>,
<code>queueMicrotask()</code>, <code>setTimeout()</code>, <code>setImmediate()</code>, etc. are made available
inside a <code>vm.Context</code>, functions passed to them will be added to global queues,
which are shared by all contexts. Therefore, callbacks passed to those functions
are not controllable through the timeout either.</p>
</section><section><h3>Support of dynamic <code>import()</code> in compilation APIs<span><a class="mark" href="#all_vm_support-of-dynamic-import-in-compilation-apis" id="all_vm_support-of-dynamic-import-in-compilation-apis">#</a></span><a aria-hidden="true" class="legacy" id="vm_support_of_dynamic_import_in_compilation_apis"></a></h3>
<p>The following APIs support an <code>importModuleDynamically</code> option to enable dynamic
<code>import()</code> in code compiled by the vm module.</p>
<ul>
<li><code>new vm.Script</code></li>
<li><code>vm.compileFunction()</code></li>
<li><code>new vm.SourceTextModule</code></li>
<li><code>vm.runInThisContext()</code></li>
<li><code>vm.runInContext()</code></li>
<li><code>vm.runInNewContext()</code></li>
<li><code>vm.createContext()</code></li>
</ul>
<p>This option is still part of the experimental modules API. We do not recommend
using it in a production environment.</p>
<h4>When the <code>importModuleDynamically</code> option is not specified or undefined<span><a class="mark" href="#all_vm_when-the-importmoduledynamically-option-is-not-specified-or-undefined" id="all_vm_when-the-importmoduledynamically-option-is-not-specified-or-undefined">#</a></span><a aria-hidden="true" class="legacy" id="vm_when_the_importmoduledynamically_option_is_not_specified_or_undefined"></a></h4>
<p>If this option is not specified, or if it's <code>undefined</code>, code containing
<code>import()</code> can still be compiled by the vm APIs, but when the compiled code is
executed and it actually calls <code>import()</code>, the result will reject with
<a href="#all_errors_err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.</p>
<h4>When <code>importModuleDynamically</code> is <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code><span><a class="mark" href="#all_vm_when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader" id="all_vm_when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader">#</a></span><a aria-hidden="true" class="legacy" id="vm_when_importmoduledynamically_is_vm_constants_use_main_context_default_loader"></a></h4>
<p>This option is currently not supported for <code>vm.SourceTextModule</code>.</p>
<p>With this option, when an <code>import()</code> is initiated in the compiled code, Node.js
would use the default ESM loader from the main context to load the requested
module and return it to the code being executed.</p>
<p>This gives access to Node.js built-in modules such as <code>fs</code> or <code>http</code>
to the code being compiled. If the code is executed in a different context,
be aware that the objects created by modules loaded from the main context
are still from the main context and not <code>instanceof</code> built-in classes in the
new context.</p>
<pre class="with-49-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> { <span class="hljs-title class_">Script</span>, constants } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
<span class="hljs-string">'import("node:fs").then(({readFile}) => readFile instanceof Function)'</span>,
{ <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span> });
<span class="hljs-comment">// false: URL loaded from the main context is not an instance of the Function</span>
<span class="hljs-comment">// class in the new context.</span>
script.<span class="hljs-title function_">runInNewContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Script</span>, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
<span class="hljs-string">'import("node:fs").then(({readFile}) => readFile instanceof Function)'</span>,
{ <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span> });
<span class="hljs-comment">// false: URL loaded from the main context is not an instance of the Function</span>
<span class="hljs-comment">// class in the new context.</span>
script.<span class="hljs-title function_">runInNewContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
<p>This option also allows the script or function to load user modules:</p>
<pre class="with-49-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_">Script</span>, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;
<span class="hljs-keyword">import</span> { resolve } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-keyword">import</span> { writeFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// Write test.js and test.txt to the directory where the current script</span>
<span class="hljs-comment">// being run is located.</span>
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">dirname</span>, <span class="hljs-string">'test.mjs'</span>),
<span class="hljs-string">'export const filename = "./test.json";'</span>);
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">dirname</span>, <span class="hljs-string">'test.json'</span>),
<span class="hljs-string">'{"hello": "world"}'</span>);
<span class="hljs-comment">// Compile a script that loads test.mjs and then test.json</span>
<span class="hljs-comment">// as if the script is placed in the same directory.</span>
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
<span class="hljs-string">`(async function() {
const { filename } = await import('./test.mjs');
return import(filename, { with: { type: 'json' } })
})();`</span>,
{
<span class="hljs-attr">filename</span>: <span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">dirname</span>, <span class="hljs-string">'test-with-default.js'</span>),
<span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span>,
});
<span class="hljs-comment">// { default: { hello: 'world' } }</span>
script.<span class="hljs-title function_">runInThisContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Script</span>, constants } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> { resolve } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">const</span> { writeFileSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-comment">// Write test.js and test.txt to the directory where the current script</span>
<span class="hljs-comment">// being run is located.</span>
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'test.mjs'</span>),
<span class="hljs-string">'export const filename = "./test.json";'</span>);
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'test.json'</span>),
<span class="hljs-string">'{"hello": "world"}'</span>);
<span class="hljs-comment">// Compile a script that loads test.mjs and then test.json</span>
<span class="hljs-comment">// as if the script is placed in the same directory.</span>
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
<span class="hljs-string">`(async function() {
const { filename } = await import('./test.mjs');
return import(filename, { with: { type: 'json' } })
})();`</span>,
{
<span class="hljs-attr">filename</span>: <span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'test-with-default.js'</span>),
<span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span>,
});
<span class="hljs-comment">// { default: { hello: 'world' } }</span>
script.<span class="hljs-title function_">runInThisContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
<p>There are a few caveats with loading user modules using the default loader
from the main context:</p>
<ol>
<li>The module being resolved would be relative to the <code>filename</code> option passed
to <code>vm.Script</code> or <code>vm.compileFunction()</code>. The resolution can work with a
<code>filename</code> that's either an absolute path or a URL string. If <code>filename</code> is
a string that's neither an absolute path or a URL, or if it's undefined,
the resolution will be relative to the current working directory
of the process. In the case of <code>vm.createContext()</code>, the resolution is always
relative to the current working directory since this option is only used when
there isn't a referrer script or module.</li>
<li>For any given <code>filename</code> that resolves to a specific path, once the process
manages to load a particular module from that path, the result may be cached,
and subsequent load of the same module from the same path would return the
same thing. If the <code>filename</code> is a URL string, the cache would not be hit
if it has different search parameters. For <code>filename</code>s that are not URL
strings, there is currently no way to bypass the caching behavior.</li>
</ol>
<h4>When <code>importModuleDynamically</code> is a function<span><a class="mark" href="#all_vm_when-importmoduledynamically-is-a-function" id="all_vm_when-importmoduledynamically-is-a-function">#</a></span><a aria-hidden="true" class="legacy" id="vm_when_importmoduledynamically_is_a_function"></a></h4>
<p>When <code>importModuleDynamically</code> is a function, it will be invoked when <code>import()</code>
is called in the compiled code for users to customize how the requested module
should be compiled and evaluated. Currently, the Node.js instance must be
launched with the <code>--experimental-vm-modules</code> flag for this option to work. If
the flag isn't set, this callback will be ignored. If the code evaluated
actually calls to <code>import()</code>, the result will reject with
<a href="#all_errors_err_vm_dynamic_import_callback_missing_flag"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code></a>.</p>
<p>The callback <code>importModuleDynamically(specifier, referrer, importAttributes)</code>
has the following signature:</p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> specifier passed to <code>import()</code></li>
<li><code>referrer</code> <a href="#all_vm_class-vmscript" class="type"><vm.Script></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="#all_vm_class-vmsourcetextmodule" class="type"><vm.SourceTextModule></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
The referrer is the compiled <code>vm.Script</code> for <code>new vm.Script</code>,
<code>vm.runInThisContext</code>, <code>vm.runInContext</code> and <code>vm.runInNewContext</code>. It's the
compiled <code>Function</code> for <code>vm.compileFunction</code>, the compiled
<code>vm.SourceTextModule</code> for <code>new vm.SourceTextModule</code>, and the context <code>Object</code>
for <code>vm.createContext()</code>.</li>
<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <code>"with"</code> value passed to the
<a href="https://tc39.es/proposal-import-attributes/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was
provided.</li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects" class="type"><Module Namespace Object></a> | <a href="#all_vm_class-vmmodule" class="type"><vm.Module></a> Returning a <code>vm.Module</code> is
recommended in order to take advantage of error tracking, and to avoid issues
with namespaces that contain <code>then</code> function exports.</li>
</ul>
<pre class="with-58-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// This script must be run with --experimental-vm-modules.</span>
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Script</span>, <span class="hljs-title class_">SyntheticModule</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(<span class="hljs-string">'import("foo.json", { with: { type: "json" } })'</span>, {
<span class="hljs-keyword">async</span> <span class="hljs-title function_">importModuleDynamically</span>(<span class="hljs-params">specifier, referrer, importAttributes</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(specifier); <span class="hljs-comment">// 'foo.json'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(referrer); <span class="hljs-comment">// The compiled script</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(importAttributes); <span class="hljs-comment">// { type: 'json' }</span>
<span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'bar'</span>], <span class="hljs-function">() =></span> { });
<span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> { });
m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'bar'</span>, { <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });
<span class="hljs-keyword">return</span> m;
},
});
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> script.<span class="hljs-title function_">runInThisContext</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); <span class="hljs-comment">// { bar: { hello: 'world' } }</span></code><code class="language-js cjs"><span class="hljs-comment">// This script must be run with --experimental-vm-modules.</span>
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Script</span>, <span class="hljs-title class_">SyntheticModule</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">main</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(<span class="hljs-string">'import("foo.json", { with: { type: "json" } })'</span>, {
<span class="hljs-keyword">async</span> <span class="hljs-title function_">importModuleDynamically</span>(<span class="hljs-params">specifier, referrer, importAttributes</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(specifier); <span class="hljs-comment">// 'foo.json'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(referrer); <span class="hljs-comment">// The compiled script</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(importAttributes); <span class="hljs-comment">// { type: 'json' }</span>
<span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'bar'</span>], <span class="hljs-function">() =></span> { });
<span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> { });
m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'bar'</span>, { <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });
<span class="hljs-keyword">return</span> m;
},
});
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> script.<span class="hljs-title function_">runInThisContext</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); <span class="hljs-comment">// { bar: { hello: 'world' } }</span>
})();</code><button class="copy-button">copy</button></pre></section>
</section>
<section><h2>WebAssembly System Interface (WASI)<span><a class="mark" href="#all_wasi_webassembly-system-interface-wasi" id="all_wasi_webassembly-system-interface-wasi">#</a></span><a aria-hidden="true" class="legacy" id="wasi_webassembly_system_interface_wasi"></a></h2>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p><strong class="critical">The <code>node:wasi</code> module does not currently provide the
comprehensive file system security properties provided by some WASI runtimes.
Full support for secure file system sandboxing may or may not be implemented in
future. In the mean time, do not rely on it to run untrusted code. </strong></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/wasi.js">lib/wasi.js</a></p>
<p>The WASI API provides an implementation of the <a href="https://wasi.dev/">WebAssembly System Interface</a>
specification. WASI gives WebAssembly applications access to the underlying
operating system via a collection of POSIX-like functions.</p>
<pre class="with-49-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> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-variable constant_">WASI</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:wasi'</span>;
<span class="hljs-keyword">import</span> { argv, env } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> wasi = <span class="hljs-keyword">new</span> <span class="hljs-title function_">WASI</span>({
<span class="hljs-attr">version</span>: <span class="hljs-string">'preview1'</span>,
<span class="hljs-attr">args</span>: argv,
env,
<span class="hljs-attr">preopens</span>: {
<span class="hljs-string">'/local'</span>: <span class="hljs-string">'/some/real/path/that/wasm/can/access'</span>,
},
});
<span class="hljs-keyword">const</span> wasm = <span class="hljs-keyword">await</span> <span class="hljs-title class_">WebAssembly</span>.<span class="hljs-title function_">compile</span>(
<span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'./demo.wasm'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>)),
);
<span class="hljs-keyword">const</span> instance = <span class="hljs-keyword">await</span> <span class="hljs-title class_">WebAssembly</span>.<span class="hljs-title function_">instantiate</span>(wasm, wasi.<span class="hljs-title function_">getImportObject</span>());
wasi.<span class="hljs-title function_">start</span>(instance);</code><code class="language-js cjs"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> { readFile } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-variable constant_">WASI</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:wasi'</span>);
<span class="hljs-keyword">const</span> { argv, env } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> { join } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">const</span> wasi = <span class="hljs-keyword">new</span> <span class="hljs-title function_">WASI</span>({
<span class="hljs-attr">version</span>: <span class="hljs-string">'preview1'</span>,
<span class="hljs-attr">args</span>: argv,
env,
<span class="hljs-attr">preopens</span>: {
<span class="hljs-string">'/local'</span>: <span class="hljs-string">'/some/real/path/that/wasm/can/access'</span>,
},
});
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">const</span> wasm = <span class="hljs-keyword">await</span> <span class="hljs-title class_">WebAssembly</span>.<span class="hljs-title function_">compile</span>(
<span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(<span class="hljs-title function_">join</span>(__dirname, <span class="hljs-string">'demo.wasm'</span>)),
);
<span class="hljs-keyword">const</span> instance = <span class="hljs-keyword">await</span> <span class="hljs-title class_">WebAssembly</span>.<span class="hljs-title function_">instantiate</span>(wasm, wasi.<span class="hljs-title function_">getImportObject</span>());
wasi.<span class="hljs-title function_">start</span>(instance);
})();</code><button class="copy-button">copy</button></pre>
<p>To run the above example, create a new WebAssembly text format file named
<code>demo.wat</code>:</p>
<pre><code class="language-text">(module
;; Import the required fd_write WASI function which will write the given io vectors to stdout
;; The function signature for fd_write is:
;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written
(import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)))
(memory 1)
(export "memory" (memory 0))
;; Write 'hello world\n' to memory at an offset of 8 bytes
;; Note the trailing newline which is required for the text to appear
(data (i32.const 8) "hello world\n")
(func $main (export "_start")
;; Creating a new io vector within linear memory
(i32.store (i32.const 0) (i32.const 8)) ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string
(i32.store (i32.const 4) (i32.const 12)) ;; iov.iov_len - The length of the 'hello world\n' string
(call $fd_write
(i32.const 1) ;; file_descriptor - 1 for stdout
(i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0
(i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.
(i32.const 20) ;; nwritten - A place in memory to store the number of bytes written
)
drop ;; Discard the number of bytes written from the top of the stack
)
)</code> <button class="copy-button">copy</button></pre>
<p>Use <a href="https://github.com/WebAssembly/wabt">wabt</a> to compile <code>.wat</code> to <code>.wasm</code></p>
<pre><code class="language-bash">wat2wasm demo.wat</code> <button class="copy-button">copy</button></pre>
<section><h3>Security<span><a class="mark" href="#all_wasi_security" id="all_wasi_security">#</a></span><a aria-hidden="true" class="legacy" id="wasi_security"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.11.0</td>
<td><p>Clarify WASI security properties.</p></td></tr>
<tr><td>v20.11.0</td>
<td><p><span>Added in: v20.11.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>WASI provides a capabilities-based model through which applications are provided
their own custom <code>env</code>, <code>preopens</code>, <code>stdin</code>, <code>stdout</code>, <code>stderr</code>, and <code>exit</code>
capabilities.</p>
<p><strong>The current Node.js threat model does not provide secure sandboxing as is
present in some WASI runtimes.</strong></p>
<p>While the capability features are supported, they do not form a security model
in Node.js. For example, the file system sandboxing can be escaped with various
techniques. The project is exploring whether these security guarantees could be
added in future.</p>
</section><section><h3>Class: <code>WASI</code><span><a class="mark" href="#all_wasi_class-wasi" id="all_wasi_class-wasi">#</a></span><a aria-hidden="true" class="legacy" id="wasi_class_wasi"></a></h3>
<div class="api_metadata">
<span>Added in: v13.3.0, v12.16.0</span>
</div>
<p>The <code>WASI</code> class provides the WASI system call API and additional convenience
methods for working with WASI-based applications. Each <code>WASI</code> instance
represents a distinct environment.</p>
<h4><code>new WASI([options])</code><span><a class="mark" href="#all_wasi_new-wasioptions" id="all_wasi_new-wasioptions">#</a></span><a aria-hidden="true" class="legacy" id="wasi_new_wasi_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>v20.1.0</td>
<td><p>default value of returnOnExit changed to true.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p>The version option is now required and has no default value.</p></td></tr>
<tr><td>v19.8.0</td>
<td><p>version field added to options.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p><span>Added in: v13.3.0, v12.16.0</span></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>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array of strings that the WebAssembly application will
see as command-line arguments. The first argument is the virtual path to the
WASI command itself. <strong>Default:</strong> <code>[]</code>.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object similar to <code>process.env</code> that the WebAssembly
application will see as its environment. <strong>Default:</strong> <code>{}</code>.</li>
<li><code>preopens</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> This object represents the WebAssembly application's
local directory structure. The string keys of <code>preopens</code> are treated as
directories within the file system. The corresponding values in <code>preopens</code>
are the real paths to those directories on the host machine.</li>
<li><code>returnOnExit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> By default, when WASI applications call
<code>__wasi_proc_exit()</code> <code>wasi.start()</code> will return with the exit code
specified rather than terminating the process. Setting this option to
<code>false</code> will cause the Node.js process to exit with the specified
exit code instead. <strong>Default:</strong> <code>true</code>.</li>
<li><code>stdin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The file descriptor used as standard input in the
WebAssembly application. <strong>Default:</strong> <code>0</code>.</li>
<li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The file descriptor used as standard output in the
WebAssembly application. <strong>Default:</strong> <code>1</code>.</li>
<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The file descriptor used as standard error in the
WebAssembly application. <strong>Default:</strong> <code>2</code>.</li>
<li><code>version</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The version of WASI requested. Currently the only
supported versions are <code>unstable</code> and <code>preview1</code>. This option is
mandatory.</li>
</ul>
</li>
</ul>
<h4><code>wasi.getImportObject()</code><span><a class="mark" href="#all_wasi_wasigetimportobject" id="all_wasi_wasigetimportobject">#</a></span><a aria-hidden="true" class="legacy" id="wasi_wasi_getimportobject"></a></h4>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p>Return an import object that can be passed to <code>WebAssembly.instantiate()</code> if
no other WASM imports are needed beyond those provided by WASI.</p>
<p>If version <code>unstable</code> was passed into the constructor it will return:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span> wasi_unstable<span class="hljs-punctuation">:</span> wasi.wasiImport <span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>If version <code>preview1</code> was passed into the constructor or no version was
specified it will return:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span> wasi_snapshot_preview1<span class="hljs-punctuation">:</span> wasi.wasiImport <span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h4><code>wasi.start(instance)</code><span><a class="mark" href="#all_wasi_wasistartinstance" id="all_wasi_wasistartinstance">#</a></span><a aria-hidden="true" class="legacy" id="wasi_wasi_start_instance"></a></h4>
<div class="api_metadata">
<span>Added in: v13.3.0, v12.16.0</span>
</div>
<ul>
<li><code>instance</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance" class="type"><WebAssembly.Instance></a></li>
</ul>
<p>Attempt to begin execution of <code>instance</code> as a WASI command by invoking its
<code>_start()</code> export. If <code>instance</code> does not contain a <code>_start()</code> export, or if
<code>instance</code> contains an <code>_initialize()</code> export, then an exception is thrown.</p>
<p><code>start()</code> requires that <code>instance</code> exports a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory"><code>WebAssembly.Memory</code></a> named
<code>memory</code>. If <code>instance</code> does not have a <code>memory</code> export an exception is thrown.</p>
<p>If <code>start()</code> is called more than once, an exception is thrown.</p>
<h4><code>wasi.initialize(instance)</code><span><a class="mark" href="#all_wasi_wasiinitializeinstance" id="all_wasi_wasiinitializeinstance">#</a></span><a aria-hidden="true" class="legacy" id="wasi_wasi_initialize_instance"></a></h4>
<div class="api_metadata">
<span>Added in: v14.6.0, v12.19.0</span>
</div>
<ul>
<li><code>instance</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance" class="type"><WebAssembly.Instance></a></li>
</ul>
<p>Attempt to initialize <code>instance</code> as a WASI reactor by invoking its
<code>_initialize()</code> export, if it is present. If <code>instance</code> contains a <code>_start()</code>
export, then an exception is thrown.</p>
<p><code>initialize()</code> requires that <code>instance</code> exports a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory"><code>WebAssembly.Memory</code></a> named
<code>memory</code>. If <code>instance</code> does not have a <code>memory</code> export an exception is thrown.</p>
<p>If <code>initialize()</code> is called more than once, an exception is thrown.</p>
<h4><code>wasi.wasiImport</code><span><a class="mark" href="#all_wasi_wasiwasiimport" id="all_wasi_wasiwasiimport">#</a></span><a aria-hidden="true" class="legacy" id="wasi_wasi_wasiimport"></a></h4>
<div class="api_metadata">
<span>Added in: v13.3.0, v12.16.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p><code>wasiImport</code> is an object that implements the WASI system call API. This object
should be passed as the <code>wasi_snapshot_preview1</code> import during the instantiation
of a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance"><code>WebAssembly.Instance</code></a>.</p></section>
</section>
<section><h2>Web Crypto API<span><a class="mark" href="#all_webcrypto_web-crypto-api" id="all_webcrypto_web-crypto-api">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_web_crypto_api"></a></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Arguments are now coerced and validated as per their WebIDL definitions like in other Web Crypto API implementations.</p></td></tr>
<tr><td>v19.0.0</td>
<td><p>No longer experimental except for the <code>Ed25519</code>, <code>Ed448</code>, <code>X25519</code>, and <code>X448</code> algorithms.</p></td></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Removed proprietary <code>'node.keyObject'</code> import/export format.</p></td></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Removed proprietary <code>'NODE-DSA'</code>, <code>'NODE-DH'</code>, and <code>'NODE-SCRYPT'</code> algorithms.</p></td></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Added <code>'Ed25519'</code>, <code>'Ed448'</code>, <code>'X25519'</code>, and <code>'X448'</code> algorithms.</p></td></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Removed proprietary <code>'NODE-ED25519'</code> and <code>'NODE-ED448'</code> algorithms.</p></td></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Removed proprietary <code>'NODE-X25519'</code> and <code>'NODE-X448'</code> named curves from the <code>'ECDH'</code> algorithm.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Node.js provides an implementation of the standard <a href="https://www.w3.org/TR/WebCryptoAPI/">Web Crypto API</a>.</p>
<p>Use <code>globalThis.crypto</code> or <code>require('node:crypto').webcrypto</code> to access this
module.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
<span class="hljs-attr">hash</span>: <span class="hljs-string">'SHA-256'</span>,
<span class="hljs-attr">length</span>: <span class="hljs-number">256</span>,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);
<span class="hljs-keyword">const</span> enc = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> message = enc.<span class="hljs-title function_">encode</span>(<span class="hljs-string">'I love cupcakes'</span>);
<span class="hljs-keyword">const</span> digest = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">sign</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
}, key, message);
})();</code> <button class="copy-button">copy</button></pre>
<section><h3>Examples<span><a class="mark" href="#all_webcrypto_examples" id="all_webcrypto_examples">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_examples"></a></h3>
<h4>Generating keys<span><a class="mark" href="#all_webcrypto_generating-keys" id="all_webcrypto_generating-keys">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_generating_keys"></a></h4>
<p>The <a href="#all_webcrypto_class-subtlecrypto" class="type"><SubtleCrypto></a> class can be used to generate symmetric (secret) keys
or asymmetric key pairs (public key and private key).</p>
<h5>AES keys<span><a class="mark" href="#all_webcrypto_aes-keys" id="all_webcrypto_aes-keys">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aes_keys"></a></h5>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateAesKey</span>(<span class="hljs-params">length = <span class="hljs-number">256</span></span>) {
<span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'AES-CBC'</span>,
length,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'encrypt'</span>, <span class="hljs-string">'decrypt'</span>]);
<span class="hljs-keyword">return</span> key;
}</code> <button class="copy-button">copy</button></pre>
<h5>ECDSA key pairs<span><a class="mark" href="#all_webcrypto_ecdsa-key-pairs" id="all_webcrypto_ecdsa-key-pairs">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ecdsa_key_pairs"></a></h5>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateEcKey</span>(<span class="hljs-params">namedCurve = <span class="hljs-string">'P-521'</span></span>) {
<span class="hljs-keyword">const</span> {
publicKey,
privateKey,
} = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'ECDSA'</span>,
namedCurve,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);
<span class="hljs-keyword">return</span> { publicKey, privateKey };
}</code> <button class="copy-button">copy</button></pre>
<h5>Ed25519/Ed448/X25519/X448 key pairs<span><a class="mark" href="#all_webcrypto_ed25519ed448x25519x448-key-pairs" id="all_webcrypto_ed25519ed448x25519x448-key-pairs">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ed25519_ed448_x25519_x448_key_pairs"></a></h5>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateEd25519Key</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">return</span> subtle.<span class="hljs-title function_">generateKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'Ed25519'</span>,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);
}
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateX25519Key</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">return</span> subtle.<span class="hljs-title function_">generateKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'X25519'</span>,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'deriveKey'</span>]);
}</code> <button class="copy-button">copy</button></pre>
<h5>HMAC keys<span><a class="mark" href="#all_webcrypto_hmac-keys" id="all_webcrypto_hmac-keys">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmac_keys"></a></h5>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateHmacKey</span>(<span class="hljs-params">hash = <span class="hljs-string">'SHA-256'</span></span>) {
<span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
hash,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);
<span class="hljs-keyword">return</span> key;
}</code> <button class="copy-button">copy</button></pre>
<h5>RSA key pairs<span><a class="mark" href="#all_webcrypto_rsa-key-pairs" id="all_webcrypto_rsa-key-pairs">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsa_key_pairs"></a></h5>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">const</span> publicExponent = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>([<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>]);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateRsaKey</span>(<span class="hljs-params">modulusLength = <span class="hljs-number">2048</span>, hash = <span class="hljs-string">'SHA-256'</span></span>) {
<span class="hljs-keyword">const</span> {
publicKey,
privateKey,
} = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'RSASSA-PKCS1-v1_5'</span>,
modulusLength,
publicExponent,
hash,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);
<span class="hljs-keyword">return</span> { publicKey, privateKey };
}</code> <button class="copy-button">copy</button></pre>
<h4>Encryption and decryption<span><a class="mark" href="#all_webcrypto_encryption-and-decryption" id="all_webcrypto_encryption-and-decryption">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_encryption_and_decryption"></a></h4>
<pre><code class="language-js"><span class="hljs-keyword">const</span> crypto = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">aesEncrypt</span>(<span class="hljs-params">plaintext</span>) {
<span class="hljs-keyword">const</span> ec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> <span class="hljs-title function_">generateAesKey</span>();
<span class="hljs-keyword">const</span> iv = crypto.<span class="hljs-title function_">getRandomValues</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>));
<span class="hljs-keyword">const</span> ciphertext = <span class="hljs-keyword">await</span> crypto.<span class="hljs-property">subtle</span>.<span class="hljs-title function_">encrypt</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'AES-CBC'</span>,
iv,
}, key, ec.<span class="hljs-title function_">encode</span>(plaintext));
<span class="hljs-keyword">return</span> {
key,
iv,
ciphertext,
};
}
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">aesDecrypt</span>(<span class="hljs-params">ciphertext, key, iv</span>) {
<span class="hljs-keyword">const</span> dec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextDecoder</span>();
<span class="hljs-keyword">const</span> plaintext = <span class="hljs-keyword">await</span> crypto.<span class="hljs-property">subtle</span>.<span class="hljs-title function_">decrypt</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'AES-CBC'</span>,
iv,
}, key, ciphertext);
<span class="hljs-keyword">return</span> dec.<span class="hljs-title function_">decode</span>(plaintext);
}</code> <button class="copy-button">copy</button></pre>
<h4>Exporting and importing keys<span><a class="mark" href="#all_webcrypto_exporting-and-importing-keys" id="all_webcrypto_exporting-and-importing-keys">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_exporting_and_importing_keys"></a></h4>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateAndExportHmacKey</span>(<span class="hljs-params">format = <span class="hljs-string">'jwk'</span>, hash = <span class="hljs-string">'SHA-512'</span></span>) {
<span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
hash,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);
<span class="hljs-keyword">return</span> subtle.<span class="hljs-title function_">exportKey</span>(format, key);
}
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">importHmacKey</span>(<span class="hljs-params">keyData, format = <span class="hljs-string">'jwk'</span>, hash = <span class="hljs-string">'SHA-512'</span></span>) {
<span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">importKey</span>(format, keyData, {
<span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
hash,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);
<span class="hljs-keyword">return</span> key;
}</code> <button class="copy-button">copy</button></pre>
<h4>Wrapping and unwrapping keys<span><a class="mark" href="#all_webcrypto_wrapping-and-unwrapping-keys" id="all_webcrypto_wrapping-and-unwrapping-keys">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_wrapping_and_unwrapping_keys"></a></h4>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateAndWrapHmacKey</span>(<span class="hljs-params">format = <span class="hljs-string">'jwk'</span>, hash = <span class="hljs-string">'SHA-512'</span></span>) {
<span class="hljs-keyword">const</span> [
key,
wrappingKey,
] = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([
subtle.<span class="hljs-title function_">generateKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>, hash,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]),
subtle.<span class="hljs-title function_">generateKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'AES-KW'</span>,
<span class="hljs-attr">length</span>: <span class="hljs-number">256</span>,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'wrapKey'</span>, <span class="hljs-string">'unwrapKey'</span>]),
]);
<span class="hljs-keyword">const</span> wrappedKey = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">wrapKey</span>(format, key, wrappingKey, <span class="hljs-string">'AES-KW'</span>);
<span class="hljs-keyword">return</span> { wrappedKey, wrappingKey };
}
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">unwrapHmacKey</span>(<span class="hljs-params">
wrappedKey,
wrappingKey,
format = <span class="hljs-string">'jwk'</span>,
hash = <span class="hljs-string">'SHA-512'</span></span>) {
<span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">unwrapKey</span>(
format,
wrappedKey,
wrappingKey,
<span class="hljs-string">'AES-KW'</span>,
{ <span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>, hash },
<span class="hljs-literal">true</span>,
[<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);
<span class="hljs-keyword">return</span> key;
}</code> <button class="copy-button">copy</button></pre>
<h4>Sign and verify<span><a class="mark" href="#all_webcrypto_sign-and-verify" id="all_webcrypto_sign-and-verify">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_sign_and_verify"></a></h4>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">sign</span>(<span class="hljs-params">key, data</span>) {
<span class="hljs-keyword">const</span> ec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> signature =
<span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">sign</span>(<span class="hljs-string">'RSASSA-PKCS1-v1_5'</span>, key, ec.<span class="hljs-title function_">encode</span>(data));
<span class="hljs-keyword">return</span> signature;
}
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">verify</span>(<span class="hljs-params">key, signature, data</span>) {
<span class="hljs-keyword">const</span> ec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> verified =
<span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">verify</span>(
<span class="hljs-string">'RSASSA-PKCS1-v1_5'</span>,
key,
signature,
ec.<span class="hljs-title function_">encode</span>(data));
<span class="hljs-keyword">return</span> verified;
}</code> <button class="copy-button">copy</button></pre>
<h4>Deriving bits and keys<span><a class="mark" href="#all_webcrypto_deriving-bits-and-keys" id="all_webcrypto_deriving-bits-and-keys">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_deriving_bits_and_keys"></a></h4>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">pbkdf2</span>(<span class="hljs-params">pass, salt, iterations = <span class="hljs-number">1000</span>, length = <span class="hljs-number">256</span></span>) {
<span class="hljs-keyword">const</span> ec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">importKey</span>(
<span class="hljs-string">'raw'</span>,
ec.<span class="hljs-title function_">encode</span>(pass),
<span class="hljs-string">'PBKDF2'</span>,
<span class="hljs-literal">false</span>,
[<span class="hljs-string">'deriveBits'</span>]);
<span class="hljs-keyword">const</span> bits = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">deriveBits</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'PBKDF2'</span>,
<span class="hljs-attr">hash</span>: <span class="hljs-string">'SHA-512'</span>,
<span class="hljs-attr">salt</span>: ec.<span class="hljs-title function_">encode</span>(salt),
iterations,
}, key, length);
<span class="hljs-keyword">return</span> bits;
}
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">pbkdf2Key</span>(<span class="hljs-params">pass, salt, iterations = <span class="hljs-number">1000</span>, length = <span class="hljs-number">256</span></span>) {
<span class="hljs-keyword">const</span> ec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> keyMaterial = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">importKey</span>(
<span class="hljs-string">'raw'</span>,
ec.<span class="hljs-title function_">encode</span>(pass),
<span class="hljs-string">'PBKDF2'</span>,
<span class="hljs-literal">false</span>,
[<span class="hljs-string">'deriveKey'</span>]);
<span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">deriveKey</span>({
<span class="hljs-attr">name</span>: <span class="hljs-string">'PBKDF2'</span>,
<span class="hljs-attr">hash</span>: <span class="hljs-string">'SHA-512'</span>,
<span class="hljs-attr">salt</span>: ec.<span class="hljs-title function_">encode</span>(salt),
iterations,
}, keyMaterial, {
<span class="hljs-attr">name</span>: <span class="hljs-string">'AES-GCM'</span>,
length,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'encrypt'</span>, <span class="hljs-string">'decrypt'</span>]);
<span class="hljs-keyword">return</span> key;
}</code> <button class="copy-button">copy</button></pre>
<h4>Digest<span><a class="mark" href="#all_webcrypto_digest" id="all_webcrypto_digest">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_digest"></a></h4>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">digest</span>(<span class="hljs-params">data, algorithm = <span class="hljs-string">'SHA-512'</span></span>) {
<span class="hljs-keyword">const</span> ec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> digest = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">digest</span>(algorithm, ec.<span class="hljs-title function_">encode</span>(data));
<span class="hljs-keyword">return</span> digest;
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Algorithm matrix<span><a class="mark" href="#all_webcrypto_algorithm-matrix" id="all_webcrypto_algorithm-matrix">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_algorithm_matrix"></a></h3>
<p>The table details the algorithms supported by the Node.js Web Crypto API
implementation and the APIs supported for each:</p>
<table><thead><tr><th>Algorithm</th><th><code>generateKey</code></th><th><code>exportKey</code></th><th><code>importKey</code></th><th><code>encrypt</code></th><th><code>decrypt</code></th><th><code>wrapKey</code></th><th><code>unwrapKey</code></th><th><code>deriveBits</code></th><th><code>deriveKey</code></th><th><code>sign</code></th><th><code>verify</code></th><th><code>digest</code></th></tr></thead><tbody><tr><td><code>'RSASSA-PKCS1-v1_5'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'RSA-PSS'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'RSA-OAEP'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'ECDSA'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-2" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'ECDH'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td></tr><tr><td><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-3" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td></tr><tr><td><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-4" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td></tr><tr><td><code>'AES-CTR'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'AES-CBC'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'AES-GCM'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'AES-KW'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'HMAC'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'HKDF'</code></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td></tr><tr><td><code>'PBKDF2'</code></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td></tr><tr><td><code>'SHA-1'</code></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td></tr><tr><td><code>'SHA-256'</code></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td></tr><tr><td><code>'SHA-384'</code></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td></tr><tr><td><code>'SHA-512'</code></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td></tr></tbody></table>
</section><section><h3>Class: <code>Crypto</code><span><a class="mark" href="#all_webcrypto_class-crypto" id="all_webcrypto_class-crypto">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_crypto"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p><code>globalThis.crypto</code> is an instance of the <code>Crypto</code>
class. <code>Crypto</code> is a singleton that provides access to the remainder of the
crypto API.</p>
<h4><code>crypto.subtle</code><span><a class="mark" href="#all_webcrypto_cryptosubtle" id="all_webcrypto_cryptosubtle">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_crypto_subtle"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webcrypto_class-subtlecrypto" class="type"><SubtleCrypto></a></li>
</ul>
<p>Provides access to the <code>SubtleCrypto</code> API.</p>
<h4><code>crypto.getRandomValues(typedArray)</code><span><a class="mark" href="#all_webcrypto_cryptogetrandomvaluestypedarray" id="all_webcrypto_cryptogetrandomvaluestypedarray">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_crypto_getrandomvalues_typedarray"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>typedArray</code> <a href="#all_buffer_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></li>
<li>Returns: <a href="#all_buffer_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></li>
</ul>
<p>Generates cryptographically strong random values. The given <code>typedArray</code> is
filled with random values, and a reference to <code>typedArray</code> is returned.</p>
<p>The given <code>typedArray</code> must be an integer-based instance of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a>,
i.e. <code>Float32Array</code> and <code>Float64Array</code> are not accepted.</p>
<p>An error will be thrown if the given <code>typedArray</code> is larger than 65,536 bytes.</p>
<h4><code>crypto.randomUUID()</code><span><a class="mark" href="#all_webcrypto_cryptorandomuuid" id="all_webcrypto_cryptorandomuuid">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_crypto_randomuuid"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Generates a random <a href="https://www.rfc-editor.org/rfc/rfc4122.txt">RFC 4122</a> version 4 UUID. The UUID is generated using a
cryptographic pseudorandom number generator.</p>
</section><section><h3>Class: <code>CryptoKey</code><span><a class="mark" href="#all_webcrypto_class-cryptokey" id="all_webcrypto_class-cryptokey">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_cryptokey"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h4><code>cryptoKey.algorithm</code><span><a class="mark" href="#all_webcrypto_cryptokeyalgorithm" id="all_webcrypto_cryptokeyalgorithm">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_cryptokey_algorithm"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li>Type: <a href="#all_webcrypto_class-aeskeygenparams" class="type"><AesKeyGenParams></a> | <a href="#all_webcrypto_class-rsahashedkeygenparams" class="type"><RsaHashedKeyGenParams></a> | <a href="#all_webcrypto_class-eckeygenparams" class="type"><EcKeyGenParams></a> | <a href="#all_webcrypto_class-hmackeygenparams" class="type"><HmacKeyGenParams></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>An object detailing the algorithm for which the key can be used along with
additional algorithm-specific parameters.</p>
<p>Read-only.</p>
<h4><code>cryptoKey.extractable</code><span><a class="mark" href="#all_webcrypto_cryptokeyextractable" id="all_webcrypto_cryptokeyextractable">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_cryptokey_extractable"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>When <code>true</code>, the <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> can be extracted using either
<code>subtleCrypto.exportKey()</code> or <code>subtleCrypto.wrapKey()</code>.</p>
<p>Read-only.</p>
<h4><code>cryptoKey.type</code><span><a class="mark" href="#all_webcrypto_cryptokeytype" id="all_webcrypto_cryptokeytype">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_cryptokey_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> One of <code>'secret'</code>, <code>'private'</code>, or <code>'public'</code>.</li>
</ul>
<p>A string identifying whether the key is a symmetric (<code>'secret'</code>) or
asymmetric (<code>'private'</code> or <code>'public'</code>) key.</p>
<h4><code>cryptoKey.usages</code><span><a class="mark" href="#all_webcrypto_cryptokeyusages" id="all_webcrypto_cryptokeyusages">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_cryptokey_usages"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
<p>An array of strings identifying the operations for which the
key may be used.</p>
<p>The possible usages are:</p>
<ul>
<li><code>'encrypt'</code> - The key may be used to encrypt data.</li>
<li><code>'decrypt'</code> - The key may be used to decrypt data.</li>
<li><code>'sign'</code> - The key may be used to generate digital signatures.</li>
<li><code>'verify'</code> - The key may be used to verify digital signatures.</li>
<li><code>'deriveKey'</code> - The key may be used to derive a new key.</li>
<li><code>'deriveBits'</code> - The key may be used to derive bits.</li>
<li><code>'wrapKey'</code> - The key may be used to wrap another key.</li>
<li><code>'unwrapKey'</code> - The key may be used to unwrap another key.</li>
</ul>
<p>Valid key usages depend on the key algorithm (identified by
<code>cryptokey.algorithm.name</code>).</p>
<table><thead><tr><th>Key Type</th><th><code>'encrypt'</code></th><th><code>'decrypt'</code></th><th><code>'sign'</code></th><th><code>'verify'</code></th><th><code>'deriveKey'</code></th><th><code>'deriveBits'</code></th><th><code>'wrapKey'</code></th><th><code>'unwrapKey'</code></th></tr></thead><tbody><tr><td><code>'AES-CBC'</code></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-CTR'</code></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-GCM'</code></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-KW'</code></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'ECDH'</code></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td></tr><tr><td><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-5" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td></tr><tr><td><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-6" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td></tr><tr><td><code>'ECDSA'</code></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td></tr><tr><td><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-7" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td></tr><tr><td><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-8" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td></tr><tr><td><code>'HDKF'</code></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td></tr><tr><td><code>'HMAC'</code></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td></tr><tr><td><code>'PBKDF2'</code></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td></tr><tr><td><code>'RSA-OAEP'</code></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'RSA-PSS'</code></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td></tr><tr><td><code>'RSASSA-PKCS1-v1_5'</code></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td></tr></tbody></table>
</section><section><h3>Class: <code>CryptoKeyPair</code><span><a class="mark" href="#all_webcrypto_class-cryptokeypair" id="all_webcrypto_class-cryptokeypair">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_cryptokeypair"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>The <code>CryptoKeyPair</code> is a simple dictionary object with <code>publicKey</code> and
<code>privateKey</code> properties, representing an asymmetric key pair.</p>
<h4><code>cryptoKeyPair.privateKey</code><span><a class="mark" href="#all_webcrypto_cryptokeypairprivatekey" id="all_webcrypto_cryptokeypairprivatekey">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_cryptokeypair_privatekey"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> A <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> whose <code>type</code> will be <code>'private'</code>.</li>
</ul>
<h4><code>cryptoKeyPair.publicKey</code><span><a class="mark" href="#all_webcrypto_cryptokeypairpublickey" id="all_webcrypto_cryptokeypairpublickey">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_cryptokeypair_publickey"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> A <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> whose <code>type</code> will be <code>'public'</code>.</li>
</ul>
</section><section><h3>Class: <code>SubtleCrypto</code><span><a class="mark" href="#all_webcrypto_class-subtlecrypto" id="all_webcrypto_class-subtlecrypto">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_subtlecrypto"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h4><code>subtle.decrypt(algorithm, key, data)</code><span><a class="mark" href="#all_webcrypto_subtledecryptalgorithm-key-data" id="all_webcrypto_subtledecryptalgorithm-key-data">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_decrypt_algorithm_key_data"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-rsaoaepparams" class="type"><RsaOaepParams></a> | <a href="#all_webcrypto_class-aesctrparams" class="type"><AesCtrParams></a> | <a href="#all_webcrypto_class-aescbcparams" class="type"><AesCbcParams></a> | <a href="#all_webcrypto_class-aesgcmparams" class="type"><AesGcmParams></a></li>
<li><code>key</code>: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li><code>data</code>: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a></li>
</ul>
<p>Using the method and parameters specified in <code>algorithm</code> and the keying
material provided by <code>key</code>, <code>subtle.decrypt()</code> attempts to decipher the
provided <code>data</code>. If successful, the returned promise will be resolved with
an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> containing the plaintext result.</p>
<p>The algorithms currently supported include:</p>
<ul>
<li><code>'RSA-OAEP'</code></li>
<li><code>'AES-CTR'</code></li>
<li><code>'AES-CBC'</code></li>
<li><code>'AES-GCM'</code></li>
</ul>
<h4><code>subtle.deriveBits(algorithm, baseKey[, length])</code><span><a class="mark" href="#all_webcrypto_subtlederivebitsalgorithm-basekey-length" id="all_webcrypto_subtlederivebitsalgorithm-basekey-length">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_derivebits_algorithm_basekey_length"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.17.0</td>
<td><p>The length parameter is now optional for <code>'ECDH'</code>, <code>'X25519'</code>, and <code>'X448'</code>.</p></td></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Added <code>'X25519'</code>, and <code>'X448'</code> algorithms.</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>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type"><AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-ecdhkeyderiveparams" class="type"><EcdhKeyDeriveParams></a> | <a href="#all_webcrypto_class-hkdfparams" class="type"><HkdfParams></a> | <a href="#all_webcrypto_class-pbkdf2params" class="type"><Pbkdf2Params></a></li>
<li><code>baseKey</code>: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li><code>length</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Using the method and parameters specified in <code>algorithm</code> and the keying
material provided by <code>baseKey</code>, <code>subtle.deriveBits()</code> attempts to generate
<code>length</code> bits.</p>
<p>The Node.js implementation requires that <code>length</code>, when a number, is a multiple
of <code>8</code>.</p>
<p>When <code>length</code> is not provided or <code>null</code> the maximum number of bits for a given
algorithm is generated. This is allowed for the <code>'ECDH'</code>, <code>'X25519'</code>, and <code>'X448'</code>
algorithms, for other algorithms <code>length</code> is required to be a number.</p>
<p>If successful, the returned promise will be resolved with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a>
containing the generated data.</p>
<p>The algorithms currently supported include:</p>
<ul>
<li><code>'ECDH'</code></li>
<li><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-9" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-10" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'HKDF'</code></li>
<li><code>'PBKDF2'</code></li>
</ul>
<h4><code>subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)</code><span><a class="mark" href="#all_webcrypto_subtlederivekeyalgorithm-basekey-derivedkeyalgorithm-extractable-keyusages" id="all_webcrypto_subtlederivekeyalgorithm-basekey-derivedkeyalgorithm-extractable-keyusages">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_derivekey_algorithm_basekey_derivedkeyalgorithm_extractable_keyusages"></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.4.0, v16.17.0</td>
<td><p>Added <code>'X25519'</code>, and <code>'X448'</code> algorithms.</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>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type"><AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-ecdhkeyderiveparams" class="type"><EcdhKeyDeriveParams></a> | <a href="#all_webcrypto_class-hkdfparams" class="type"><HkdfParams></a> | <a href="#all_webcrypto_class-pbkdf2params" class="type"><Pbkdf2Params></a></li>
<li><code>baseKey</code>: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li><code>derivedKeyAlgorithm</code>: <a href="#all_webcrypto_class-hmackeygenparams" class="type"><HmacKeyGenParams></a> | <a href="#all_webcrypto_class-aeskeygenparams" class="type"><AesKeyGenParams></a></li>
<li><code>extractable</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>keyUsages</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> See <a href="#all_webcrypto_cryptokeyusages">Key usages</a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with a <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Using the method and parameters specified in <code>algorithm</code>, and the keying
material provided by <code>baseKey</code>, <code>subtle.deriveKey()</code> attempts to generate
a new <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> based on the method and parameters in <code>derivedKeyAlgorithm</code>.</p>
<p>Calling <code>subtle.deriveKey()</code> is equivalent to calling <code>subtle.deriveBits()</code> to
generate raw keying material, then passing the result into the
<code>subtle.importKey()</code> method using the <code>deriveKeyAlgorithm</code>, <code>extractable</code>, and
<code>keyUsages</code> parameters as input.</p>
<p>The algorithms currently supported include:</p>
<ul>
<li><code>'ECDH'</code></li>
<li><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-11" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-12" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'HKDF'</code></li>
<li><code>'PBKDF2'</code></li>
</ul>
<h4><code>subtle.digest(algorithm, data)</code><span><a class="mark" href="#all_webcrypto_subtledigestalgorithm-data" id="all_webcrypto_subtledigestalgorithm-data">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_digest_algorithm_data"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>algorithm</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/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>data</code>: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a></li>
</ul>
<p>Using the method identified by <code>algorithm</code>, <code>subtle.digest()</code> attempts to
generate a digest of <code>data</code>. If successful, the returned promise is resolved
with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> containing the computed digest.</p>
<p>If <code>algorithm</code> is provided as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, it must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If <code>algorithm</code> is provided as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>, it must have a <code>name</code> property
whose value is one of the above.</p>
<h4><code>subtle.encrypt(algorithm, key, data)</code><span><a class="mark" href="#all_webcrypto_subtleencryptalgorithm-key-data" id="all_webcrypto_subtleencryptalgorithm-key-data">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_encrypt_algorithm_key_data"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-rsaoaepparams" class="type"><RsaOaepParams></a> | <a href="#all_webcrypto_class-aesctrparams" class="type"><AesCtrParams></a> | <a href="#all_webcrypto_class-aescbcparams" class="type"><AesCbcParams></a> | <a href="#all_webcrypto_class-aesgcmparams" class="type"><AesGcmParams></a></li>
<li><code>key</code>: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li><code>data</code>: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a></li>
</ul>
<p>Using the method and parameters specified by <code>algorithm</code> and the keying
material provided by <code>key</code>, <code>subtle.encrypt()</code> attempts to encipher <code>data</code>.
If successful, the returned promise is resolved with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a>
containing the encrypted result.</p>
<p>The algorithms currently supported include:</p>
<ul>
<li><code>'RSA-OAEP'</code></li>
<li><code>'AES-CTR'</code></li>
<li><code>'AES-CBC'</code></li>
<li><code>'AES-GCM'</code></li>
</ul>
<h4><code>subtle.exportKey(format, key)</code><span><a class="mark" href="#all_webcrypto_subtleexportkeyformat-key" id="all_webcrypto_subtleexportkeyformat-key">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_exportkey_format_key"></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.4.0, v16.17.0</td>
<td><p>Added <code>'Ed25519'</code>, <code>'Ed448'</code>, <code>'X25519'</code>, and <code>'X448'</code> algorithms.</p></td></tr>
<tr><td>v15.9.0</td>
<td><p>Removed <code>'NODE-DSA'</code> JWK export.</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>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'raw'</code>, <code>'pkcs8'</code>, <code>'spki'</code>, or <code>'jwk'</code>.</li>
<li><code>key</code>: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with an <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/Reference/Global_Objects/Object" class="type"><Object></a>.</li>
</ul>
<p>Exports the given key into the specified format, if supported.</p>
<p>If the <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> is not extractable, the returned promise will reject.</p>
<p>When <code>format</code> is either <code>'pkcs8'</code> or <code>'spki'</code> and the export is successful,
the returned promise will be resolved with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> containing the
exported key data.</p>
<p>When <code>format</code> is <code>'jwk'</code> and the export is successful, the returned promise
will be resolved with a JavaScript object conforming to the <a href="https://tools.ietf.org/html/rfc7517">JSON Web Key</a>
specification.</p>
<table><thead><tr><th>Key Type</th><th><code>'spki'</code></th><th><code>'pkcs8'</code></th><th><code>'jwk'</code></th><th><code>'raw'</code></th></tr></thead><tbody><tr><td><code>'AES-CBC'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-CTR'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-GCM'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-KW'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'ECDH'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'ECDSA'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-13" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-14" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'HDKF'</code></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'HMAC'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'PBKDF2'</code></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'RSA-OAEP'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'RSA-PSS'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'RSASSA-PKCS1-v1_5'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td></tr></tbody></table>
<h4><code>subtle.generateKey(algorithm, extractable, keyUsages)</code><span><a class="mark" href="#all_webcrypto_subtlegeneratekeyalgorithm-extractable-keyusages" id="all_webcrypto_subtlegeneratekeyalgorithm-extractable-keyusages">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_generatekey_algorithm_extractable_keyusages"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type"><AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsahashedkeygenparams" class="type"><RsaHashedKeyGenParams></a> | <a href="#all_webcrypto_class-eckeygenparams" class="type"><EcKeyGenParams></a> | <a href="#all_webcrypto_class-hmackeygenparams" class="type"><HmacKeyGenParams></a> | <a href="#all_webcrypto_class-aeskeygenparams" class="type"><AesKeyGenParams></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<ul>
<li><code>extractable</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>keyUsages</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> See <a href="#all_webcrypto_cryptokeyusages">Key usages</a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with a <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> | <a href="#all_webcrypto_class-cryptokeypair" class="type"><CryptoKeyPair></a></li>
</ul>
<p>Using the method and parameters provided in <code>algorithm</code>, <code>subtle.generateKey()</code>
attempts to generate new keying material. Depending the method used, the method
may generate either a single <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> or a <a href="#all_webcrypto_class-cryptokeypair" class="type"><CryptoKeyPair></a>.</p>
<p>The <a href="#all_webcrypto_class-cryptokeypair" class="type"><CryptoKeyPair></a> (public and private key) generating algorithms supported
include:</p>
<ul>
<li><code>'RSASSA-PKCS1-v1_5'</code></li>
<li><code>'RSA-PSS'</code></li>
<li><code>'RSA-OAEP'</code></li>
<li><code>'ECDSA'</code></li>
<li><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-15" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-16" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'ECDH'</code></li>
<li><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-17" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-18" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
</ul>
<p>The <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> (secret key) generating algorithms supported include:</p>
<ul>
<li><code>'HMAC'</code></li>
<li><code>'AES-CTR'</code></li>
<li><code>'AES-CBC'</code></li>
<li><code>'AES-GCM'</code></li>
<li><code>'AES-KW'</code></li>
</ul>
<h4><code>subtle.importKey(format, keyData, algorithm, extractable, keyUsages)</code><span><a class="mark" href="#all_webcrypto_subtleimportkeyformat-keydata-algorithm-extractable-keyusages" id="all_webcrypto_subtleimportkeyformat-keydata-algorithm-extractable-keyusages">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_importkey_format_keydata_algorithm_extractable_keyusages"></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.4.0, v16.17.0</td>
<td><p>Added <code>'Ed25519'</code>, <code>'Ed448'</code>, <code>'X25519'</code>, and <code>'X448'</code> algorithms.</p></td></tr>
<tr><td>v15.9.0</td>
<td><p>Removed <code>'NODE-DSA'</code> JWK import.</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>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'raw'</code>, <code>'pkcs8'</code>, <code>'spki'</code>, or <code>'jwk'</code>.</li>
<li><code>keyData</code>: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type"><AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsahashedimportparams" class="type"><RsaHashedImportParams></a> | <a href="#all_webcrypto_class-eckeyimportparams" class="type"><EcKeyImportParams></a> | <a href="#all_webcrypto_class-hmacimportparams" class="type"><HmacImportParams></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<ul>
<li><code>extractable</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>keyUsages</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> See <a href="#all_webcrypto_cryptokeyusages">Key usages</a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with a <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
</ul>
<p>The <code>subtle.importKey()</code> method attempts to interpret the provided <code>keyData</code>
as the given <code>format</code> to create a <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> instance using the provided
<code>algorithm</code>, <code>extractable</code>, and <code>keyUsages</code> arguments. If the import is
successful, the returned promise will be resolved with the created <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>.</p>
<p>If importing a <code>'PBKDF2'</code> key, <code>extractable</code> must be <code>false</code>.</p>
<p>The algorithms currently supported include:</p>
<table><thead><tr><th>Key Type</th><th><code>'spki'</code></th><th><code>'pkcs8'</code></th><th><code>'jwk'</code></th><th><code>'raw'</code></th></tr></thead><tbody><tr><td><code>'AES-CBC'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-CTR'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-GCM'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-KW'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'ECDH'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-19" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-20" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'ECDSA'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-21" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-22" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'HDKF'</code></td><td></td><td></td><td></td><td>✔</td></tr><tr><td><code>'HMAC'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'PBKDF2'</code></td><td></td><td></td><td></td><td>✔</td></tr><tr><td><code>'RSA-OAEP'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'RSA-PSS'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'RSASSA-PKCS1-v1_5'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td></tr></tbody></table>
<h4><code>subtle.sign(algorithm, key, data)</code><span><a class="mark" href="#all_webcrypto_subtlesignalgorithm-key-data" id="all_webcrypto_subtlesignalgorithm-key-data">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_sign_algorithm_key_data"></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.4.0, v16.17.0</td>
<td><p>Added <code>'Ed25519'</code>, and <code>'Ed448'</code> algorithms.</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>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type"><AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsapssparams" class="type"><RsaPssParams></a> | <a href="#all_webcrypto_class-ecdsaparams" class="type"><EcdsaParams></a> | <a href="#all_webcrypto_class-ed448params" class="type"><Ed448Params></a></li>
<li><code>key</code>: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li><code>data</code>: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Using the method and parameters given by <code>algorithm</code> and the keying material
provided by <code>key</code>, <code>subtle.sign()</code> attempts to generate a cryptographic
signature of <code>data</code>. If successful, the returned promise is resolved with
an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> containing the generated signature.</p>
<p>The algorithms currently supported include:</p>
<ul>
<li><code>'RSASSA-PKCS1-v1_5'</code></li>
<li><code>'RSA-PSS'</code></li>
<li><code>'ECDSA'</code></li>
<li><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-23" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-24" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'HMAC'</code></li>
</ul>
<h4><code>subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)</code><span><a class="mark" href="#all_webcrypto_subtleunwrapkeyformat-wrappedkey-unwrappingkey-unwrapalgo-unwrappedkeyalgo-extractable-keyusages" id="all_webcrypto_subtleunwrapkeyformat-wrappedkey-unwrappingkey-unwrapalgo-unwrappedkeyalgo-extractable-keyusages">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_unwrapkey_format_wrappedkey_unwrappingkey_unwrapalgo_unwrappedkeyalgo_extractable_keyusages"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'raw'</code>, <code>'pkcs8'</code>, <code>'spki'</code>, or <code>'jwk'</code>.</li>
<li><code>wrappedKey</code>: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
<li><code>unwrappingKey</code>: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
</ul>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>unwrapAlgo</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type"><AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsaoaepparams" class="type"><RsaOaepParams></a> | <a href="#all_webcrypto_class-aesctrparams" class="type"><AesCtrParams></a> | <a href="#all_webcrypto_class-aescbcparams" class="type"><AesCbcParams></a> | <a href="#all_webcrypto_class-aesgcmparams" class="type"><AesGcmParams></a></li>
<li><code>unwrappedKeyAlgo</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type"><AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsahashedimportparams" class="type"><RsaHashedImportParams></a> | <a href="#all_webcrypto_class-eckeyimportparams" class="type"><EcKeyImportParams></a> | <a href="#all_webcrypto_class-hmacimportparams" class="type"><HmacImportParams></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<ul>
<li><code>extractable</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>keyUsages</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> See <a href="#all_webcrypto_cryptokeyusages">Key usages</a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with a <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
</ul>
<p>In cryptography, "wrapping a key" refers to exporting and then encrypting the
keying material. The <code>subtle.unwrapKey()</code> method attempts to decrypt a wrapped
key and create a <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> instance. It is equivalent to calling
<code>subtle.decrypt()</code> first on the encrypted key data (using the <code>wrappedKey</code>,
<code>unwrapAlgo</code>, and <code>unwrappingKey</code> arguments as input) then passing the results
in to the <code>subtle.importKey()</code> method using the <code>unwrappedKeyAlgo</code>,
<code>extractable</code>, and <code>keyUsages</code> arguments as inputs. If successful, the returned
promise is resolved with a <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a> object.</p>
<p>The wrapping algorithms currently supported include:</p>
<ul>
<li><code>'RSA-OAEP'</code></li>
<li><code>'AES-CTR'</code></li>
<li><code>'AES-CBC'</code></li>
<li><code>'AES-GCM'</code></li>
<li><code>'AES-KW'</code></li>
</ul>
<p>The unwrapped key algorithms supported include:</p>
<ul>
<li><code>'RSASSA-PKCS1-v1_5'</code></li>
<li><code>'RSA-PSS'</code></li>
<li><code>'RSA-OAEP'</code></li>
<li><code>'ECDSA'</code></li>
<li><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-25" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-26" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'ECDH'</code></li>
<li><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-27" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-28" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'HMAC'</code></li>
<li><code>'AES-CTR'</code></li>
<li><code>'AES-CBC'</code></li>
<li><code>'AES-GCM'</code></li>
<li><code>'AES-KW'</code></li>
</ul>
<h4><code>subtle.verify(algorithm, key, signature, data)</code><span><a class="mark" href="#all_webcrypto_subtleverifyalgorithm-key-signature-data" id="all_webcrypto_subtleverifyalgorithm-key-signature-data">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_verify_algorithm_key_signature_data"></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.4.0, v16.17.0</td>
<td><p>Added <code>'Ed25519'</code>, and <code>'Ed448'</code> algorithms.</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>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type"><AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsapssparams" class="type"><RsaPssParams></a> | <a href="#all_webcrypto_class-ecdsaparams" class="type"><EcdsaParams></a> | <a href="#all_webcrypto_class-ed448params" class="type"><Ed448Params></a></li>
<li><code>key</code>: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li><code>signature</code>: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
<li><code>data</code>: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Using the method and parameters given in <code>algorithm</code> and the keying material
provided by <code>key</code>, <code>subtle.verify()</code> attempts to verify that <code>signature</code> is
a valid cryptographic signature of <code>data</code>. The returned promise is resolved
with either <code>true</code> or <code>false</code>.</p>
<p>The algorithms currently supported include:</p>
<ul>
<li><code>'RSASSA-PKCS1-v1_5'</code></li>
<li><code>'RSA-PSS'</code></li>
<li><code>'ECDSA'</code></li>
<li><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-29" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-30" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'HMAC'</code></li>
</ul>
<h4><code>subtle.wrapKey(format, key, wrappingKey, wrapAlgo)</code><span><a class="mark" href="#all_webcrypto_subtlewrapkeyformat-key-wrappingkey-wrapalgo" id="all_webcrypto_subtlewrapkeyformat-key-wrappingkey-wrapalgo">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_wrapkey_format_key_wrappingkey_wrapalgo"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'raw'</code>, <code>'pkcs8'</code>, <code>'spki'</code>, or <code>'jwk'</code>.</li>
<li><code>key</code>: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li><code>wrappingKey</code>: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
<li><code>wrapAlgo</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type"><AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsaoaepparams" class="type"><RsaOaepParams></a> | <a href="#all_webcrypto_class-aesctrparams" class="type"><AesCtrParams></a> | <a href="#all_webcrypto_class-aescbcparams" class="type"><AesCbcParams></a> | <a href="#all_webcrypto_class-aesgcmparams" class="type"><AesGcmParams></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>In cryptography, "wrapping a key" refers to exporting and then encrypting the
keying material. The <code>subtle.wrapKey()</code> method exports the keying material into
the format identified by <code>format</code>, then encrypts it using the method and
parameters specified by <code>wrapAlgo</code> and the keying material provided by
<code>wrappingKey</code>. It is the equivalent to calling <code>subtle.exportKey()</code> using
<code>format</code> and <code>key</code> as the arguments, then passing the result to the
<code>subtle.encrypt()</code> method using <code>wrappingKey</code> and <code>wrapAlgo</code> as inputs. If
successful, the returned promise will be resolved with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a>
containing the encrypted key data.</p>
<p>The wrapping algorithms currently supported include:</p>
<ul>
<li><code>'RSA-OAEP'</code></li>
<li><code>'AES-CTR'</code></li>
<li><code>'AES-CBC'</code></li>
<li><code>'AES-GCM'</code></li>
<li><code>'AES-KW'</code></li>
</ul>
</section><section><h3>Algorithm parameters<span><a class="mark" href="#all_webcrypto_algorithm-parameters" id="all_webcrypto_algorithm-parameters">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_algorithm_parameters"></a></h3>
<p>The algorithm parameter objects define the methods and parameters used by
the various <a href="#all_webcrypto_class-subtlecrypto" class="type"><SubtleCrypto></a> methods. While described here as "classes", they
are simple JavaScript dictionary objects.</p>
<h4>Class: <code>AlgorithmIdentifier</code><span><a class="mark" href="#all_webcrypto_class-algorithmidentifier" id="all_webcrypto_class-algorithmidentifier">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_algorithmidentifier"></a></h4>
<div class="api_metadata">
<span>Added in: v18.4.0, v16.17.0</span>
</div>
<h5><code>algorithmIdentifier.name</code><span><a class="mark" href="#all_webcrypto_algorithmidentifiername" id="all_webcrypto_algorithmidentifiername">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_algorithmidentifier_name"></a></h5>
<div class="api_metadata">
<span>Added in: v18.4.0, v16.17.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<h4>Class: <code>AesCbcParams</code><span><a class="mark" href="#all_webcrypto_class-aescbcparams" id="all_webcrypto_class-aescbcparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_aescbcparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>aesCbcParams.iv</code><span><a class="mark" href="#all_webcrypto_aescbcparamsiv" id="all_webcrypto_aescbcparamsiv">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aescbcparams_iv"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Provides the initialization vector. It must be exactly 16-bytes in length
and should be unpredictable and cryptographically random.</p>
<h5><code>aesCbcParams.name</code><span><a class="mark" href="#all_webcrypto_aescbcparamsname" id="all_webcrypto_aescbcparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aescbcparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'AES-CBC'</code>.</li>
</ul>
<h4>Class: <code>AesCtrParams</code><span><a class="mark" href="#all_webcrypto_class-aesctrparams" id="all_webcrypto_class-aesctrparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_aesctrparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>aesCtrParams.counter</code><span><a class="mark" href="#all_webcrypto_aesctrparamscounter" id="all_webcrypto_aesctrparamscounter">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesctrparams_counter"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>The initial value of the counter block. This must be exactly 16 bytes long.</p>
<p>The <code>AES-CTR</code> method uses the rightmost <code>length</code> bits of the block as the
counter and the remaining bits as the nonce.</p>
<h5><code>aesCtrParams.length</code><span><a class="mark" href="#all_webcrypto_aesctrparamslength" id="all_webcrypto_aesctrparamslength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesctrparams_length"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bits in the <code>aesCtrParams.counter</code> that are
to be used as the counter.</li>
</ul>
<h5><code>aesCtrParams.name</code><span><a class="mark" href="#all_webcrypto_aesctrparamsname" id="all_webcrypto_aesctrparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesctrparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'AES-CTR'</code>.</li>
</ul>
<h4>Class: <code>AesGcmParams</code><span><a class="mark" href="#all_webcrypto_class-aesgcmparams" id="all_webcrypto_class-aesgcmparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_aesgcmparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>aesGcmParams.additionalData</code><span><a class="mark" href="#all_webcrypto_aesgcmparamsadditionaldata" id="all_webcrypto_aesgcmparamsadditionaldata">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesgcmparams_additionaldata"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>With the AES-GCM method, the <code>additionalData</code> is extra input that is not
encrypted but is included in the authentication of the data. The use of
<code>additionalData</code> is optional.</p>
<h5><code>aesGcmParams.iv</code><span><a class="mark" href="#all_webcrypto_aesgcmparamsiv" id="all_webcrypto_aesgcmparamsiv">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesgcmparams_iv"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>The initialization vector must be unique for every encryption operation using a
given key.</p>
<p>Ideally, this is a deterministic 12-byte value that is computed in such a way
that it is guaranteed to be unique across all invocations that use the same key.
Alternatively, the initialization vector may consist of at least 12
cryptographically random bytes. For more information on constructing
initialization vectors for AES-GCM, refer to Section 8 of <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf">NIST SP 800-38D</a>.</p>
<h5><code>aesGcmParams.name</code><span><a class="mark" href="#all_webcrypto_aesgcmparamsname" id="all_webcrypto_aesgcmparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesgcmparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'AES-GCM'</code>.</li>
</ul>
<h5><code>aesGcmParams.tagLength</code><span><a class="mark" href="#all_webcrypto_aesgcmparamstaglength" id="all_webcrypto_aesgcmparamstaglength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesgcmparams_taglength"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The size in bits of the generated authentication tag.
This values must be one of <code>32</code>, <code>64</code>, <code>96</code>, <code>104</code>, <code>112</code>, <code>120</code>, or
<code>128</code>. <strong>Default:</strong> <code>128</code>.</li>
</ul>
<h4>Class: <code>AesKeyGenParams</code><span><a class="mark" href="#all_webcrypto_class-aeskeygenparams" id="all_webcrypto_class-aeskeygenparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_aeskeygenparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>aesKeyGenParams.length</code><span><a class="mark" href="#all_webcrypto_aeskeygenparamslength" id="all_webcrypto_aeskeygenparamslength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aeskeygenparams_length"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The length of the AES key to be generated. This must be either <code>128</code>, <code>192</code>,
or <code>256</code>.</p>
<h5><code>aesKeyGenParams.name</code><span><a class="mark" href="#all_webcrypto_aeskeygenparamsname" id="all_webcrypto_aeskeygenparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aeskeygenparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'AES-CBC'</code>, <code>'AES-CTR'</code>, <code>'AES-GCM'</code>, or
<code>'AES-KW'</code></li>
</ul>
<h4>Class: <code>EcdhKeyDeriveParams</code><span><a class="mark" href="#all_webcrypto_class-ecdhkeyderiveparams" id="all_webcrypto_class-ecdhkeyderiveparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_ecdhkeyderiveparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>ecdhKeyDeriveParams.name</code><span><a class="mark" href="#all_webcrypto_ecdhkeyderiveparamsname" id="all_webcrypto_ecdhkeyderiveparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ecdhkeyderiveparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'ECDH'</code>, <code>'X25519'</code>, or <code>'X448'</code>.</li>
</ul>
<h5><code>ecdhKeyDeriveParams.public</code><span><a class="mark" href="#all_webcrypto_ecdhkeyderiveparamspublic" id="all_webcrypto_ecdhkeyderiveparamspublic">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ecdhkeyderiveparams_public"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a></li>
</ul>
<p>ECDH key derivation operates by taking as input one parties private key and
another parties public key -- using both to generate a common shared secret.
The <code>ecdhKeyDeriveParams.public</code> property is set to the other parties public
key.</p>
<h4>Class: <code>EcdsaParams</code><span><a class="mark" href="#all_webcrypto_class-ecdsaparams" id="all_webcrypto_class-ecdsaparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_ecdsaparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>ecdsaParams.hash</code><span><a class="mark" href="#all_webcrypto_ecdsaparamshash" id="all_webcrypto_ecdsaparamshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ecdsaparams_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>ecdsaParams.name</code><span><a class="mark" href="#all_webcrypto_ecdsaparamsname" id="all_webcrypto_ecdsaparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ecdsaparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'ECDSA'</code>.</li>
</ul>
<h4>Class: <code>EcKeyGenParams</code><span><a class="mark" href="#all_webcrypto_class-eckeygenparams" id="all_webcrypto_class-eckeygenparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_eckeygenparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>ecKeyGenParams.name</code><span><a class="mark" href="#all_webcrypto_eckeygenparamsname" id="all_webcrypto_eckeygenparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_eckeygenparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'ECDSA'</code> or <code>'ECDH'</code>.</li>
</ul>
<h5><code>ecKeyGenParams.namedCurve</code><span><a class="mark" href="#all_webcrypto_eckeygenparamsnamedcurve" id="all_webcrypto_eckeygenparamsnamedcurve">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_eckeygenparams_namedcurve"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'P-256'</code>, <code>'P-384'</code>, <code>'P-521'</code>.</li>
</ul>
<h4>Class: <code>EcKeyImportParams</code><span><a class="mark" href="#all_webcrypto_class-eckeyimportparams" id="all_webcrypto_class-eckeyimportparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_eckeyimportparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>ecKeyImportParams.name</code><span><a class="mark" href="#all_webcrypto_eckeyimportparamsname" id="all_webcrypto_eckeyimportparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_eckeyimportparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'ECDSA'</code> or <code>'ECDH'</code>.</li>
</ul>
<h5><code>ecKeyImportParams.namedCurve</code><span><a class="mark" href="#all_webcrypto_eckeyimportparamsnamedcurve" id="all_webcrypto_eckeyimportparamsnamedcurve">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_eckeyimportparams_namedcurve"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'P-256'</code>, <code>'P-384'</code>, <code>'P-521'</code>.</li>
</ul>
<h4>Class: <code>Ed448Params</code><span><a class="mark" href="#all_webcrypto_class-ed448params" id="all_webcrypto_class-ed448params">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_ed448params"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>ed448Params.name</code><span><a class="mark" href="#all_webcrypto_ed448paramsname" id="all_webcrypto_ed448paramsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ed448params_name"></a></h5>
<div class="api_metadata">
<span>Added in: v18.4.0, v16.17.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'Ed448'</code>.</li>
</ul>
<h5><code>ed448Params.context</code><span><a class="mark" href="#all_webcrypto_ed448paramscontext" id="all_webcrypto_ed448paramscontext">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ed448params_context"></a></h5>
<div class="api_metadata">
<span>Added in: v18.4.0, v16.17.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
</ul>
<p>The <code>context</code> member represents the optional context data to associate with
the message.
The Node.js Web Crypto API implementation only supports zero-length context
which is equivalent to not providing context at all.</p>
<h4>Class: <code>HkdfParams</code><span><a class="mark" href="#all_webcrypto_class-hkdfparams" id="all_webcrypto_class-hkdfparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_hkdfparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>hkdfParams.hash</code><span><a class="mark" href="#all_webcrypto_hkdfparamshash" id="all_webcrypto_hkdfparamshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hkdfparams_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>hkdfParams.info</code><span><a class="mark" href="#all_webcrypto_hkdfparamsinfo" id="all_webcrypto_hkdfparamsinfo">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hkdfparams_info"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Provides application-specific contextual input to the HKDF algorithm.
This can be zero-length but must be provided.</p>
<h5><code>hkdfParams.name</code><span><a class="mark" href="#all_webcrypto_hkdfparamsname" id="all_webcrypto_hkdfparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hkdfparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'HKDF'</code>.</li>
</ul>
<h5><code>hkdfParams.salt</code><span><a class="mark" href="#all_webcrypto_hkdfparamssalt" id="all_webcrypto_hkdfparamssalt">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hkdfparams_salt"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>The salt value significantly improves the strength of the HKDF algorithm.
It should be random or pseudorandom and should be the same length as the
output of the digest function (for instance, if using <code>'SHA-256'</code> as the
digest, the salt should be 256-bits of random data).</p>
<h4>Class: <code>HmacImportParams</code><span><a class="mark" href="#all_webcrypto_class-hmacimportparams" id="all_webcrypto_class-hmacimportparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_hmacimportparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>hmacImportParams.hash</code><span><a class="mark" href="#all_webcrypto_hmacimportparamshash" id="all_webcrypto_hmacimportparamshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmacimportparams_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>hmacImportParams.length</code><span><a class="mark" href="#all_webcrypto_hmacimportparamslength" id="all_webcrypto_hmacimportparamslength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmacimportparams_length"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The optional number of bits in the HMAC key. This is optional and should
be omitted for most cases.</p>
<h5><code>hmacImportParams.name</code><span><a class="mark" href="#all_webcrypto_hmacimportparamsname" id="all_webcrypto_hmacimportparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmacimportparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'HMAC'</code>.</li>
</ul>
<h4>Class: <code>HmacKeyGenParams</code><span><a class="mark" href="#all_webcrypto_class-hmackeygenparams" id="all_webcrypto_class-hmackeygenparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_hmackeygenparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>hmacKeyGenParams.hash</code><span><a class="mark" href="#all_webcrypto_hmackeygenparamshash" id="all_webcrypto_hmackeygenparamshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmackeygenparams_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>hmacKeyGenParams.length</code><span><a class="mark" href="#all_webcrypto_hmackeygenparamslength" id="all_webcrypto_hmackeygenparamslength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmackeygenparams_length"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The number of bits to generate for the HMAC key. If omitted,
the length will be determined by the hash algorithm used.
This is optional and should be omitted for most cases.</p>
<h5><code>hmacKeyGenParams.name</code><span><a class="mark" href="#all_webcrypto_hmackeygenparamsname" id="all_webcrypto_hmackeygenparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmackeygenparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'HMAC'</code>.</li>
</ul>
<h4>Class: <code>Pbkdf2Params</code><span><a class="mark" href="#all_webcrypto_class-pbkdf2params" id="all_webcrypto_class-pbkdf2params">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_pbkdf2params"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>pbkdb2Params.hash</code><span><a class="mark" href="#all_webcrypto_pbkdb2paramshash" id="all_webcrypto_pbkdb2paramshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_pbkdb2params_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>pbkdf2Params.iterations</code><span><a class="mark" href="#all_webcrypto_pbkdf2paramsiterations" id="all_webcrypto_pbkdf2paramsiterations">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_pbkdf2params_iterations"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The number of iterations the PBKDF2 algorithm should make when deriving bits.</p>
<h5><code>pbkdf2Params.name</code><span><a class="mark" href="#all_webcrypto_pbkdf2paramsname" id="all_webcrypto_pbkdf2paramsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_pbkdf2params_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'PBKDF2'</code>.</li>
</ul>
<h5><code>pbkdf2Params.salt</code><span><a class="mark" href="#all_webcrypto_pbkdf2paramssalt" id="all_webcrypto_pbkdf2paramssalt">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_pbkdf2params_salt"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>Should be at least 16 random or pseudorandom bytes.</p>
<h4>Class: <code>RsaHashedImportParams</code><span><a class="mark" href="#all_webcrypto_class-rsahashedimportparams" id="all_webcrypto_class-rsahashedimportparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_rsahashedimportparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>rsaHashedImportParams.hash</code><span><a class="mark" href="#all_webcrypto_rsahashedimportparamshash" id="all_webcrypto_rsahashedimportparamshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsahashedimportparams_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>rsaHashedImportParams.name</code><span><a class="mark" href="#all_webcrypto_rsahashedimportparamsname" id="all_webcrypto_rsahashedimportparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsahashedimportparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'RSASSA-PKCS1-v1_5'</code>, <code>'RSA-PSS'</code>, or
<code>'RSA-OAEP'</code>.</li>
</ul>
<h4>Class: <code>RsaHashedKeyGenParams</code><span><a class="mark" href="#all_webcrypto_class-rsahashedkeygenparams" id="all_webcrypto_class-rsahashedkeygenparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_rsahashedkeygenparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>rsaHashedKeyGenParams.hash</code><span><a class="mark" href="#all_webcrypto_rsahashedkeygenparamshash" id="all_webcrypto_rsahashedkeygenparamshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsahashedkeygenparams_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/Global_Objects/Object" class="type"><Object></a></li>
</ul>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>rsaHashedKeyGenParams.modulusLength</code><span><a class="mark" href="#all_webcrypto_rsahashedkeygenparamsmoduluslength" id="all_webcrypto_rsahashedkeygenparamsmoduluslength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsahashedkeygenparams_moduluslength"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The length in bits of the RSA modulus. As a best practice, this should be
at least <code>2048</code>.</p>
<h5><code>rsaHashedKeyGenParams.name</code><span><a class="mark" href="#all_webcrypto_rsahashedkeygenparamsname" id="all_webcrypto_rsahashedkeygenparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsahashedkeygenparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'RSASSA-PKCS1-v1_5'</code>, <code>'RSA-PSS'</code>, or
<code>'RSA-OAEP'</code>.</li>
</ul>
<h5><code>rsaHashedKeyGenParams.publicExponent</code><span><a class="mark" href="#all_webcrypto_rsahashedkeygenparamspublicexponent" id="all_webcrypto_rsahashedkeygenparamspublicexponent">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsahashedkeygenparams_publicexponent"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li>
</ul>
<p>The RSA public exponent. This must be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> containing a big-endian,
unsigned integer that must fit within 32-bits. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> may contain an
arbitrary number of leading zero-bits. The value must be a prime number. Unless
there is reason to use a different value, use <code>new Uint8Array([1, 0, 1])</code>
(65537) as the public exponent.</p>
<h4>Class: <code>RsaOaepParams</code><span><a class="mark" href="#all_webcrypto_class-rsaoaepparams" id="all_webcrypto_class-rsaoaepparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_rsaoaepparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>rsaOaepParams.label</code><span><a class="mark" href="#all_webcrypto_rsaoaepparamslabel" id="all_webcrypto_rsaoaepparamslabel">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsaoaepparams_label"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type"><Buffer></a></li>
</ul>
<p>An additional collection of bytes that will not be encrypted, but will be bound
to the generated ciphertext.</p>
<p>The <code>rsaOaepParams.label</code> parameter is optional.</p>
<h5><code>rsaOaepParams.name</code><span><a class="mark" href="#all_webcrypto_rsaoaepparamsname" id="all_webcrypto_rsaoaepparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsaoaepparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> must be <code>'RSA-OAEP'</code>.</li>
</ul>
<h4>Class: <code>RsaPssParams</code><span><a class="mark" href="#all_webcrypto_class-rsapssparams" id="all_webcrypto_class-rsapssparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_rsapssparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>rsaPssParams.name</code><span><a class="mark" href="#all_webcrypto_rsapssparamsname" id="all_webcrypto_rsapssparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsapssparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'RSA-PSS'</code>.</li>
</ul>
<h5><code>rsaPssParams.saltLength</code><span><a class="mark" href="#all_webcrypto_rsapssparamssaltlength" id="all_webcrypto_rsapssparamssaltlength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsapssparams_saltlength"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The length (in bytes) of the random salt to use.</p>
<section data-footnotes="" class="footnotes"><h3 class="sr-only" id="footnote-label">Footnotes</h3>
<ol>
<li id="all_webcrypto_user-content-fn-1">
<p>An experimental implementation of
<a href="https://wicg.github.io/webcrypto-secure-curves/">Secure Curves in the Web Cryptography API</a> as of 30 August 2023 <a href="#all_webcrypto_user-content-fnref-1" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩</a> <a href="#all_webcrypto_user-content-fnref-1-2" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>2</sup></a> <a href="#all_webcrypto_user-content-fnref-1-3" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>3</sup></a> <a href="#all_webcrypto_user-content-fnref-1-4" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>4</sup></a> <a href="#all_webcrypto_user-content-fnref-1-5" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>5</sup></a> <a href="#all_webcrypto_user-content-fnref-1-6" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>6</sup></a> <a href="#all_webcrypto_user-content-fnref-1-7" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>7</sup></a> <a href="#all_webcrypto_user-content-fnref-1-8" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>8</sup></a> <a href="#all_webcrypto_user-content-fnref-1-9" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>9</sup></a> <a href="#all_webcrypto_user-content-fnref-1-10" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>10</sup></a> <a href="#all_webcrypto_user-content-fnref-1-11" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>11</sup></a> <a href="#all_webcrypto_user-content-fnref-1-12" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>12</sup></a> <a href="#all_webcrypto_user-content-fnref-1-13" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>13</sup></a> <a href="#all_webcrypto_user-content-fnref-1-14" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>14</sup></a> <a href="#all_webcrypto_user-content-fnref-1-15" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>15</sup></a> <a href="#all_webcrypto_user-content-fnref-1-16" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>16</sup></a> <a href="#all_webcrypto_user-content-fnref-1-17" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>17</sup></a> <a href="#all_webcrypto_user-content-fnref-1-18" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>18</sup></a> <a href="#all_webcrypto_user-content-fnref-1-19" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>19</sup></a> <a href="#all_webcrypto_user-content-fnref-1-20" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>20</sup></a> <a href="#all_webcrypto_user-content-fnref-1-21" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>21</sup></a> <a href="#all_webcrypto_user-content-fnref-1-22" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>22</sup></a> <a href="#all_webcrypto_user-content-fnref-1-23" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>23</sup></a> <a href="#all_webcrypto_user-content-fnref-1-24" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>24</sup></a> <a href="#all_webcrypto_user-content-fnref-1-25" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>25</sup></a> <a href="#all_webcrypto_user-content-fnref-1-26" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>26</sup></a> <a href="#all_webcrypto_user-content-fnref-1-27" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>27</sup></a> <a href="#all_webcrypto_user-content-fnref-1-28" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>28</sup></a> <a href="#all_webcrypto_user-content-fnref-1-29" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>29</sup></a> <a href="#all_webcrypto_user-content-fnref-1-30" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>30</sup></a></p>
</li>
</ol>
</section></section>
</section>
<section><h2>Web Streams API<span><a class="mark" href="#all_webstreams_web-streams-api" id="all_webstreams_web-streams-api">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_web_streams_api"></a></h2>
<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</td>
<td><p>Use of this API no longer emit a runtime warning.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>An implementation of the <a href="https://streams.spec.whatwg.org/">WHATWG Streams Standard</a>.</p>
<section><h3>Overview<span><a class="mark" href="#all_webstreams_overview" id="all_webstreams_overview">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_overview"></a></h3>
<p>The <a href="https://streams.spec.whatwg.org/">WHATWG Streams Standard</a> (or "web streams") defines an API for handling
streaming data. It is similar to the Node.js <a href="stream.html">Streams</a> API but emerged later
and has become the "standard" API for streaming data across many JavaScript
environments.</p>
<p>There are three primary types of objects:</p>
<ul>
<li><code>ReadableStream</code> - Represents a source of streaming data.</li>
<li><code>WritableStream</code> - Represents a destination for streaming data.</li>
<li><code>TransformStream</code> - Represents an algorithm for transforming streaming data.</li>
</ul>
<h4>Example <code>ReadableStream</code><span><a class="mark" href="#all_webstreams_example-readablestream" id="all_webstreams_example-readablestream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_example_readablestream"></a></h4>
<p>This example creates a simple <code>ReadableStream</code> that pushes the current
<code>performance.now()</code> timestamp once every second forever. An async iterable
is used to read the data from the stream.</p>
<pre class="with-17-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_">ReadableStream</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;
<span class="hljs-keyword">import</span> {
<span class="hljs-built_in">setInterval</span> <span class="hljs-keyword">as</span> every,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;
<span class="hljs-keyword">import</span> {
performance,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:perf_hooks'</span>;
<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">SECOND</span> = <span class="hljs-number">1000</span>;
<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({
<span class="hljs-keyword">async</span> <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> _ <span class="hljs-keyword">of</span> <span class="hljs-title function_">every</span>(<span class="hljs-variable constant_">SECOND</span>))
controller.<span class="hljs-title function_">enqueue</span>(performance.<span class="hljs-title function_">now</span>());
},
});
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> stream)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
<span class="hljs-title class_">ReadableStream</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>);
<span class="hljs-keyword">const</span> {
<span class="hljs-attr">setInterval</span>: every,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);
<span class="hljs-keyword">const</span> {
performance,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">SECOND</span> = <span class="hljs-number">1000</span>;
<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({
<span class="hljs-keyword">async</span> <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> _ <span class="hljs-keyword">of</span> <span class="hljs-title function_">every</span>(<span class="hljs-variable constant_">SECOND</span>))
controller.<span class="hljs-title function_">enqueue</span>(performance.<span class="hljs-title function_">now</span>());
},
});
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> stream)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);
})();</code><button class="copy-button">copy</button></pre>
</section><section><h3>API<span><a class="mark" href="#all_webstreams_api" id="all_webstreams_api">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_api"></a></h3>
<h4>Class: <code>ReadableStream</code><span><a class="mark" href="#all_webstreams_class-readablestream" id="all_webstreams_class-readablestream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_readablestream"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new ReadableStream([underlyingSource [, strategy]])</code><span><a class="mark" href="#all_webstreams_new-readablestreamunderlyingsource--strategy" id="all_webstreams_new-readablestreamunderlyingsource--strategy">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_readablestream_underlyingsource_strategy"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>underlyingSource</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A user-defined function that is invoked immediately when
the <code>ReadableStream</code> is created.
<ul>
<li><code>controller</code> <a href="#all_webstreams_class-readablestreamdefaultcontroller" class="type"><ReadableStreamDefaultController></a> | <a href="#all_webstreams_class-readablebytestreamcontroller" class="type"><ReadableByteStreamController></a></li>
<li>Returns: <code>undefined</code> or a promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>pull</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A user-defined function that is called repeatedly when the
<code>ReadableStream</code> internal queue is not full. The operation may be sync or
async. If async, the function will not be called again until the previously
returned promise is fulfilled.
<ul>
<li><code>controller</code> <a href="#all_webstreams_class-readablestreamdefaultcontroller" class="type"><ReadableStreamDefaultController></a> | <a href="#all_webstreams_class-readablebytestreamcontroller" class="type"><ReadableByteStreamController></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>cancel</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A user-defined function that is called when the
<code>ReadableStream</code> is canceled.
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'bytes'</code> or <code>undefined</code>.</li>
<li><code>autoAllocateChunkSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Used only when <code>type</code> is equal to
<code>'bytes'</code>. When set to a non-zero value a view buffer is automatically
allocated to <code>ReadableByteStreamController.byobRequest</code>. When not set
one must use stream's internal queues to transfer data via the default
reader <code>ReadableStreamDefaultReader</code>.</li>
</ul>
</li>
<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 before backpressure
is applied.</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 user-defined function used to identify the size of each
chunk of data.
<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>
<!--lint enable maximum-line-length remark-lint-->
<h5><code>readableStream.locked</code><span><a class="mark" href="#all_webstreams_readablestreamlocked" id="all_webstreams_readablestreamlocked">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_locked"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Set to <code>true</code> if there is an active reader for this
<a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>.</li>
</ul>
<p>The <code>readableStream.locked</code> property is <code>false</code> by default, and is
switched to <code>true</code> while there is an active reader consuming the
stream's data.</p>
<h5><code>readableStream.cancel([reason])</code><span><a class="mark" href="#all_webstreams_readablestreamcancelreason" id="all_webstreams_readablestreamcancelreason">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_cancel_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code> once cancelation has
been completed.</li>
</ul>
<h5><code>readableStream.getReader([options])</code><span><a class="mark" href="#all_webstreams_readablestreamgetreaderoptions" id="all_webstreams_readablestreamgetreaderoptions">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_getreader_options"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.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>
<ul>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <code>'byob'</code> or <code>undefined</code></li>
</ul>
</li>
<li>Returns: <a href="#all_webstreams_class-readablestreamdefaultreader" class="type"><ReadableStreamDefaultReader></a> | <a href="#all_webstreams_class-readablestreambyobreader" class="type"><ReadableStreamBYOBReader></a></li>
</ul>
<pre class="with-54-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_">ReadableStream</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;
<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>();
<span class="hljs-keyword">const</span> reader = stream.<span class="hljs-title function_">getReader</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">await</span> reader.<span class="hljs-title function_">read</span>());</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">ReadableStream</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>);
<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>();
<span class="hljs-keyword">const</span> reader = stream.<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-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
<p>Causes the <code>readableStream.locked</code> to be <code>true</code>.</p>
<h5><code>readableStream.pipeThrough(transform[, options])</code><span><a class="mark" href="#all_webstreams_readablestreampipethroughtransform-options" id="all_webstreams_readablestreampipethroughtransform-options">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_pipethrough_transform_options"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>transform</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="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> The <code>ReadableStream</code> to which
<code>transform.writable</code> will push the potentially modified data
it receives from this <code>ReadableStream</code>.</li>
<li><code>writable</code> <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a> The <code>WritableStream</code> to which this
<code>ReadableStream</code>'s data will be written.</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>preventAbort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, errors in this <code>ReadableStream</code>
will not cause <code>transform.writable</code> to be aborted.</li>
<li><code>preventCancel</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, errors in the destination
<code>transform.writable</code> do not cause this <code>ReadableStream</code> to be
canceled.</li>
<li><code>preventClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, closing this <code>ReadableStream</code>
does not cause <code>transform.writable</code> to be closed.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows the transfer of data to be canceled
using an <a href="#all_globals_class-abortcontroller" class="type"><AbortController></a>.</li>
</ul>
</li>
<li>Returns: <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> From <code>transform.readable</code>.</li>
</ul>
<p>Connects this <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> to the pair of <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> and
<a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a> provided in the <code>transform</code> argument such that the
data from this <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> is written in to <code>transform.writable</code>,
possibly transformed, then pushed to <code>transform.readable</code>. Once the
pipeline is configured, <code>transform.readable</code> is returned.</p>
<p>Causes the <code>readableStream.locked</code> to be <code>true</code> while the pipe operation
is active.</p>
<pre class="with-17-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_">ReadableStream</span>,
<span class="hljs-title class_">TransformStream</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;
<span class="hljs-keyword">const</span> stream = <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">'a'</span>);
},
});
<span class="hljs-keyword">const</span> transform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TransformStream</span>({
<span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, controller</span>) {
controller.<span class="hljs-title function_">enqueue</span>(chunk.<span class="hljs-title function_">toUpperCase</span>());
},
});
<span class="hljs-keyword">const</span> transformedStream = stream.<span class="hljs-title function_">pipeThrough</span>(transform);
<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> transformedStream)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
<span class="hljs-comment">// Prints: A</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
<span class="hljs-title class_">ReadableStream</span>,
<span class="hljs-title class_">TransformStream</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>);
<span class="hljs-keyword">const</span> stream = <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">'a'</span>);
},
});
<span class="hljs-keyword">const</span> transform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TransformStream</span>({
<span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, controller</span>) {
controller.<span class="hljs-title function_">enqueue</span>(chunk.<span class="hljs-title function_">toUpperCase</span>());
},
});
<span class="hljs-keyword">const</span> transformedStream = stream.<span class="hljs-title function_">pipeThrough</span>(transform);
(<span class="hljs-title function_">async</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> transformedStream)
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
<span class="hljs-comment">// Prints: A</span>
})();</code><button class="copy-button">copy</button></pre>
<h5><code>readableStream.pipeTo(destination[, options])</code><span><a class="mark" href="#all_webstreams_readablestreampipetodestination-options" id="all_webstreams_readablestreampipetodestination-options">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_pipeto_destination_options"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>destination</code> <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a> A <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a> to which this
<code>ReadableStream</code>'s data will be written.</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>preventAbort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, errors in this <code>ReadableStream</code>
will not cause <code>destination</code> to be aborted.</li>
<li><code>preventCancel</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, errors in the <code>destination</code>
will not cause this <code>ReadableStream</code> to be canceled.</li>
<li><code>preventClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, closing this <code>ReadableStream</code>
does not cause <code>destination</code> to be closed.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> Allows the transfer of data to be canceled
using an <a href="#all_globals_class-abortcontroller" class="type"><AbortController></a>.</li>
</ul>
</li>
<li>Returns: A promise fulfilled with <code>undefined</code></li>
</ul>
<p>Causes the <code>readableStream.locked</code> to be <code>true</code> while the pipe operation
is active.</p>
<h5><code>readableStream.tee()</code><span><a class="mark" href="#all_webstreams_readablestreamtee" id="all_webstreams_readablestreamtee">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_tee"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.10.0, v16.18.0</td>
<td><p>Support teeing a readable byte stream.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream[]></a></li>
</ul>
<p>Returns a pair of new <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> instances to which this
<code>ReadableStream</code>'s data will be forwarded. Each will receive the
same data.</p>
<p>Causes the <code>readableStream.locked</code> to be <code>true</code>.</p>
<h5><code>readableStream.values([options])</code><span><a class="mark" href="#all_webstreams_readablestreamvaluesoptions" id="all_webstreams_readablestreamvaluesoptions">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_values_options"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.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>
<ul>
<li><code>preventCancel</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, prevents the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>
from being closed when the async iterator abruptly terminates.
<strong>Default</strong>: <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Creates and returns an async iterator usable for consuming this
<code>ReadableStream</code>'s data.</p>
<p>Causes the <code>readableStream.locked</code> to be <code>true</code> while the async iterator
is active.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>(<span class="hljs-title function_">getSomeSource</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-title function_">values</span>({ <span class="hljs-attr">preventCancel</span>: <span class="hljs-literal">true</span> }))
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(chunk).<span class="hljs-title function_">toString</span>());</code> <button class="copy-button">copy</button></pre>
<h5>Async Iteration<span><a class="mark" href="#all_webstreams_async-iteration" id="all_webstreams_async-iteration">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_async_iteration"></a></h5>
<p>The <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> object supports the async iterator protocol using
<code>for await</code> syntax.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>(<span class="hljs-title function_">getSomeSource</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-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(chunk).<span class="hljs-title function_">toString</span>());</code> <button class="copy-button">copy</button></pre>
<p>The async iterator will consume the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> until it terminates.</p>
<p>By default, if the async iterator exits early (via either a <code>break</code>,
<code>return</code>, or a <code>throw</code>), the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> will be closed. To prevent
automatic closing of the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>, use the <code>readableStream.values()</code>
method to acquire the async iterator and set the <code>preventCancel</code> option to
<code>true</code>.</p>
<p>The <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> must not be locked (that is, it must not have an existing
active reader). During the async iteration, the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> will be locked.</p>
<h5>Transferring with <code>postMessage()</code><span><a class="mark" href="#all_webstreams_transferring-with-postmessage" id="all_webstreams_transferring-with-postmessage">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transferring_with_postmessage"></a></h5>
<p>A <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> instance can be transferred using a <a href="#all_worker_threads_class-messageport" class="type"><MessagePort></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>(<span class="hljs-title function_">getReadableSourceSomehow</span>());
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> {
data.<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">chunk</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
});
};
port2.<span class="hljs-title function_">postMessage</span>(stream, [stream]);</code> <button class="copy-button">copy</button></pre>
<h4><code>ReadableStream.from(iterable)</code><span><a class="mark" href="#all_webstreams_readablestreamfromiterable" id="all_webstreams_readablestreamfromiterable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_from_iterable"></a></h4>
<div class="api_metadata">
<span>Added in: v20.6.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.</li>
</ul>
<p>A utility method that creates a new <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> from an iterable.</p>
<pre class="with-54-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_">ReadableStream</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* <span class="hljs-title function_">asyncIterableGenerator</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>;
<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> stream = <span class="hljs-title class_">ReadableStream</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">asyncIterableGenerator</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-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// Prints: 'a', 'b', 'c'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">ReadableStream</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* <span class="hljs-title function_">asyncIterableGenerator</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>;
<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-title function_">async</span> () => {
<span class="hljs-keyword">const</span> stream = <span class="hljs-title class_">ReadableStream</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">asyncIterableGenerator</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-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// Prints: 'a', 'b', 'c'</span>
})();</code><button class="copy-button">copy</button></pre>
<p>To pipe the resulting <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> into a <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a> the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a>
should yield a sequence of <a href="#all_buffer_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> objects.</p>
<pre class="with-54-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_">ReadableStream</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* <span class="hljs-title function_">asyncIterableGenerator</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">yield</span> <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a'</span>);
<span class="hljs-keyword">yield</span> <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'b'</span>);
<span class="hljs-keyword">yield</span> <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'c'</span>);
}
<span class="hljs-keyword">const</span> stream = <span class="hljs-title class_">ReadableStream</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">asyncIterableGenerator</span>());
<span class="hljs-keyword">await</span> stream.<span class="hljs-title function_">pipeTo</span>(<span class="hljs-title function_">createWritableStreamSomehow</span>());</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">ReadableStream</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* <span class="hljs-title function_">asyncIterableGenerator</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">yield</span> <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a'</span>);
<span class="hljs-keyword">yield</span> <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'b'</span>);
<span class="hljs-keyword">yield</span> <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'c'</span>);
}
<span class="hljs-keyword">const</span> stream = <span class="hljs-title class_">ReadableStream</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">asyncIterableGenerator</span>());
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">await</span> stream.<span class="hljs-title function_">pipeTo</span>(<span class="hljs-title function_">createWritableStreamSomehow</span>());
})();</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>ReadableStreamDefaultReader</code><span><a class="mark" href="#all_webstreams_class-readablestreamdefaultreader" id="all_webstreams_class-readablestreamdefaultreader">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_readablestreamdefaultreader"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>By default, calling <code>readableStream.getReader()</code> with no arguments
will return an instance of <code>ReadableStreamDefaultReader</code>. The default
reader treats the chunks of data passed through the stream as opaque
values, which allows the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> to work with generally any
JavaScript value.</p>
<h5><code>new ReadableStreamDefaultReader(stream)</code><span><a class="mark" href="#all_webstreams_new-readablestreamdefaultreaderstream" id="all_webstreams_new-readablestreamdefaultreaderstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_readablestreamdefaultreader_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a></li>
</ul>
<p>Creates a new <a href="#all_webstreams_class-readablestreamdefaultreader" class="type"><ReadableStreamDefaultReader></a> that is locked to the
given <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>.</p>
<h5><code>readableStreamDefaultReader.cancel([reason])</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultreadercancelreason" id="all_webstreams_readablestreamdefaultreadercancelreason">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultreader_cancel_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Cancels the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> and returns a promise that is fulfilled
when the underlying stream has been canceled.</p>
<h5><code>readableStreamDefaultReader.closed</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultreaderclosed" id="all_webstreams_readablestreamdefaultreaderclosed">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultreader_closed"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfilled with <code>undefined</code> when the associated
<a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> is closed or rejected if the stream errors or the reader's
lock is released before the stream finishes closing.</li>
</ul>
<h5><code>readableStreamDefaultReader.read()</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultreaderread" id="all_webstreams_readablestreamdefaultreaderread">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultreader_read"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Returns: A promise fulfilled with an object:
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>done</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
</li>
</ul>
<p>Requests the next chunk of data from the underlying <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>
and returns a promise that is fulfilled with the data once it is
available.</p>
<h5><code>readableStreamDefaultReader.releaseLock()</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultreaderreleaselock" id="all_webstreams_readablestreamdefaultreaderreleaselock">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultreader_releaselock"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Releases this reader's lock on the underlying <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>.</p>
<h4>Class: <code>ReadableStreamBYOBReader</code><span><a class="mark" href="#all_webstreams_class-readablestreambyobreader" id="all_webstreams_class-readablestreambyobreader">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_readablestreambyobreader"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>ReadableStreamBYOBReader</code> is an alternative consumer for
byte-oriented <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>s (those that are created with
<code>underlyingSource.type</code> set equal to <code>'bytes'</code> when the
<code>ReadableStream</code> was created).</p>
<p>The <code>BYOB</code> is short for "bring your own buffer". This is a
pattern that allows for more efficient reading of byte-oriented
data that avoids extraneous copying.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> {
open,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> {
<span class="hljs-title class_">ReadableStream</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Source</span> {
type = <span class="hljs-string">'bytes'</span>;
autoAllocateChunkSize = <span class="hljs-number">1024</span>;
<span class="hljs-keyword">async</span> <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">file</span> = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>));
<span class="hljs-variable language_">this</span>.<span class="hljs-property">controller</span> = controller;
}
<span class="hljs-keyword">async</span> <span class="hljs-title function_">pull</span>(<span class="hljs-params">controller</span>) {
<span class="hljs-keyword">const</span> view = controller.<span class="hljs-property">byobRequest</span>?.<span class="hljs-property">view</span>;
<span class="hljs-keyword">const</span> {
bytesRead,
} = <span class="hljs-keyword">await</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">file</span>.<span class="hljs-title function_">read</span>({
<span class="hljs-attr">buffer</span>: view,
<span class="hljs-attr">offset</span>: view.<span class="hljs-property">byteOffset</span>,
<span class="hljs-attr">length</span>: view.<span class="hljs-property">byteLength</span>,
});
<span class="hljs-keyword">if</span> (bytesRead === <span class="hljs-number">0</span>) {
<span class="hljs-keyword">await</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">file</span>.<span class="hljs-title function_">close</span>();
<span class="hljs-variable language_">this</span>.<span class="hljs-property">controller</span>.<span class="hljs-title function_">close</span>();
}
controller.<span class="hljs-property">byobRequest</span>.<span class="hljs-title function_">respond</span>(bytesRead);
}
}
<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Source</span>());
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">read</span>(<span class="hljs-params">stream</span>) {
<span class="hljs-keyword">const</span> reader = stream.<span class="hljs-title function_">getReader</span>({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'byob'</span> });
<span class="hljs-keyword">const</span> chunks = [];
<span class="hljs-keyword">let</span> result;
<span class="hljs-keyword">do</span> {
result = <span class="hljs-keyword">await</span> reader.<span class="hljs-title function_">read</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">100</span>));
<span class="hljs-keyword">if</span> (result.<span class="hljs-property">value</span> !== <span class="hljs-literal">undefined</span>)
chunks.<span class="hljs-title function_">push</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(result.<span class="hljs-property">value</span>));
} <span class="hljs-keyword">while</span> (!result.<span class="hljs-property">done</span>);
<span class="hljs-keyword">return</span> <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">concat</span>(chunks);
}
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">read</span>(stream);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(data).<span class="hljs-title function_">toString</span>());</code> <button class="copy-button">copy</button></pre>
<h5><code>new ReadableStreamBYOBReader(stream)</code><span><a class="mark" href="#all_webstreams_new-readablestreambyobreaderstream" id="all_webstreams_new-readablestreambyobreaderstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_readablestreambyobreader_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a></li>
</ul>
<p>Creates a new <code>ReadableStreamBYOBReader</code> that is locked to the
given <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>.</p>
<h5><code>readableStreamBYOBReader.cancel([reason])</code><span><a class="mark" href="#all_webstreams_readablestreambyobreadercancelreason" id="all_webstreams_readablestreambyobreadercancelreason">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobreader_cancel_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Cancels the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> and returns a promise that is fulfilled
when the underlying stream has been canceled.</p>
<h5><code>readableStreamBYOBReader.closed</code><span><a class="mark" href="#all_webstreams_readablestreambyobreaderclosed" id="all_webstreams_readablestreambyobreaderclosed">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobreader_closed"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfilled with <code>undefined</code> when the associated
<a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> is closed or rejected if the stream errors or the reader's
lock is released before the stream finishes closing.</li>
</ul>
<h5><code>readableStreamBYOBReader.read(view[, options])</code><span><a class="mark" href="#all_webstreams_readablestreambyobreaderreadview-options" id="all_webstreams_readablestreambyobreaderreadview-options">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobreader_read_view_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>v20.17.0</td>
<td><p>Added <code>min</code> option.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>view</code> <a href="#all_buffer_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></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>min</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> When set, the returned promise will only be
fulfilled as soon as <code>min</code> number of elements are available.
When not set, the promise fulfills when at least one element
is available.</li>
</ul>
</li>
<li>Returns: A promise fulfilled with an object:
<ul>
<li><code>value</code> <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></li>
<li><code>done</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
</li>
</ul>
<p>Requests the next chunk of data from the underlying <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>
and returns a promise that is fulfilled with the data once it is
available.</p>
<p>Do not pass a pooled <a href="#all_buffer_class-buffer" class="type"><Buffer></a> object instance in to this method.
Pooled <code>Buffer</code> objects are created using <code>Buffer.allocUnsafe()</code>,
or <code>Buffer.from()</code>, or are often returned by various <code>node:fs</code> module
callbacks. These types of <code>Buffer</code>s use a shared underlying
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> object that contains all of the data from all of
the pooled <code>Buffer</code> instances. When a <code>Buffer</code>, <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> is passed in to <code>readableStreamBYOBReader.read()</code>,
the view's underlying <code>ArrayBuffer</code> is <em>detached</em>, invalidating
all existing views that may exist on that <code>ArrayBuffer</code>. This
can have disastrous consequences for your application.</p>
<h5><code>readableStreamBYOBReader.releaseLock()</code><span><a class="mark" href="#all_webstreams_readablestreambyobreaderreleaselock" id="all_webstreams_readablestreambyobreaderreleaselock">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobreader_releaselock"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Releases this reader's lock on the underlying <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>.</p>
<h4>Class: <code>ReadableStreamDefaultController</code><span><a class="mark" href="#all_webstreams_class-readablestreamdefaultcontroller" id="all_webstreams_class-readablestreamdefaultcontroller">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_readablestreamdefaultcontroller"></a></h4>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Every <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> has a controller that is responsible for
the internal state and management of the stream's queue. The
<code>ReadableStreamDefaultController</code> is the default controller
implementation for <code>ReadableStream</code>s that are not byte-oriented.</p>
<h5><code>readableStreamDefaultController.close()</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultcontrollerclose" id="all_webstreams_readablestreamdefaultcontrollerclose">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultcontroller_close"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Closes the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> to which this controller is associated.</p>
<h5><code>readableStreamDefaultController.desiredSize</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultcontrollerdesiredsize" id="all_webstreams_readablestreamdefaultcontrollerdesiredsize">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultcontroller_desiredsize"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Returns the amount of data remaining to fill the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>'s
queue.</p>
<h5><code>readableStreamDefaultController.enqueue([chunk])</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultcontrollerenqueuechunk" id="all_webstreams_readablestreamdefaultcontrollerenqueuechunk">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultcontroller_enqueue_chunk"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<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>
</ul>
<p>Appends a new chunk of data to the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>'s queue.</p>
<h5><code>readableStreamDefaultController.error([error])</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultcontrollererrorerror" id="all_webstreams_readablestreamdefaultcontrollererrorerror">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultcontroller_error_error"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Signals an error that causes the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> to error and close.</p>
<h4>Class: <code>ReadableByteStreamController</code><span><a class="mark" href="#all_webstreams_class-readablebytestreamcontroller" id="all_webstreams_class-readablebytestreamcontroller">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_readablebytestreamcontroller"></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.10.0</td>
<td><p>Support handling a BYOB pull request from a released reader.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Every <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> has a controller that is responsible for
the internal state and management of the stream's queue. The
<code>ReadableByteStreamController</code> is for byte-oriented <code>ReadableStream</code>s.</p>
<h5><code>readableByteStreamController.byobRequest</code><span><a class="mark" href="#all_webstreams_readablebytestreamcontrollerbyobrequest" id="all_webstreams_readablebytestreamcontrollerbyobrequest">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablebytestreamcontroller_byobrequest"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-readablestreambyobrequest" class="type"><ReadableStreamBYOBRequest></a></li>
</ul>
<h5><code>readableByteStreamController.close()</code><span><a class="mark" href="#all_webstreams_readablebytestreamcontrollerclose" id="all_webstreams_readablebytestreamcontrollerclose">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablebytestreamcontroller_close"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Closes the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> to which this controller is associated.</p>
<h5><code>readableByteStreamController.desiredSize</code><span><a class="mark" href="#all_webstreams_readablebytestreamcontrollerdesiredsize" id="all_webstreams_readablebytestreamcontrollerdesiredsize">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablebytestreamcontroller_desiredsize"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Returns the amount of data remaining to fill the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>'s
queue.</p>
<h5><code>readableByteStreamController.enqueue(chunk)</code><span><a class="mark" href="#all_webstreams_readablebytestreamcontrollerenqueuechunk" id="all_webstreams_readablebytestreamcontrollerenqueuechunk">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablebytestreamcontroller_enqueue_chunk"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>chunk</code>: <a href="#all_buffer_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></li>
</ul>
<p>Appends a new chunk of data to the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>'s queue.</p>
<h5><code>readableByteStreamController.error([error])</code><span><a class="mark" href="#all_webstreams_readablebytestreamcontrollererrorerror" id="all_webstreams_readablebytestreamcontrollererrorerror">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablebytestreamcontroller_error_error"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Signals an error that causes the <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> to error and close.</p>
<h4>Class: <code>ReadableStreamBYOBRequest</code><span><a class="mark" href="#all_webstreams_class-readablestreambyobrequest" id="all_webstreams_class-readablestreambyobrequest">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_readablestreambyobrequest"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>When using <code>ReadableByteStreamController</code> in byte-oriented
streams, and when using the <code>ReadableStreamBYOBReader</code>,
the <code>readableByteStreamController.byobRequest</code> property
provides access to a <code>ReadableStreamBYOBRequest</code> instance
that represents the current read request. The object
is used to gain access to the <code>ArrayBuffer</code>/<code>TypedArray</code>
that has been provided for the read request to fill,
and provides methods for signaling that the data has
been provided.</p>
<h5><code>readableStreamBYOBRequest.respond(bytesWritten)</code><span><a class="mark" href="#all_webstreams_readablestreambyobrequestrespondbyteswritten" id="all_webstreams_readablestreambyobrequestrespondbyteswritten">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobrequest_respond_byteswritten"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Signals that a <code>bytesWritten</code> number of bytes have been written
to <code>readableStreamBYOBRequest.view</code>.</p>
<h5><code>readableStreamBYOBRequest.respondWithNewView(view)</code><span><a class="mark" href="#all_webstreams_readablestreambyobrequestrespondwithnewviewview" id="all_webstreams_readablestreambyobrequestrespondwithnewviewview">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobrequest_respondwithnewview_view"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>view</code> <a href="#all_buffer_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></li>
</ul>
<p>Signals that the request has been fulfilled with bytes written
to a new <code>Buffer</code>, <code>TypedArray</code>, or <code>DataView</code>.</p>
<h5><code>readableStreamBYOBRequest.view</code><span><a class="mark" href="#all_webstreams_readablestreambyobrequestview" id="all_webstreams_readablestreambyobrequestview">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobrequest_view"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="#all_buffer_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></li>
</ul>
<h4>Class: <code>WritableStream</code><span><a class="mark" href="#all_webstreams_class-writablestream" id="all_webstreams_class-writablestream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_writablestream"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>WritableStream</code> is a destination to which stream data is sent.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</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> stream = <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>(chunk);
},
});
<span class="hljs-keyword">await</span> stream.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'Hello World'</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>new WritableStream([underlyingSink[, strategy]])</code><span><a class="mark" href="#all_webstreams_new-writablestreamunderlyingsink-strategy" id="all_webstreams_new-writablestreamunderlyingsink-strategy">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_writablestream_underlyingsink_strategy"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>underlyingSink</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A user-defined function that is invoked immediately when
the <code>WritableStream</code> is created.
<ul>
<li><code>controller</code> <a href="#all_webstreams_class-writablestreamdefaultcontroller" class="type"><WritableStreamDefaultController></a></li>
<li>Returns: <code>undefined</code> or a promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>write</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A user-defined function that is invoked when a chunk of
data has been written to the <code>WritableStream</code>.
<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><code>controller</code> <a href="#all_webstreams_class-writablestreamdefaultcontroller" class="type"><WritableStreamDefaultController></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>close</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A user-defined function that is called when the
<code>WritableStream</code> is closed.
<ul>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>abort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A user-defined function that is called to abruptly close
the <code>WritableStream</code>.
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The <code>type</code> option is reserved for future use and <em>must</em> be
undefined.</li>
</ul>
</li>
<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 before backpressure
is applied.</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 user-defined function used to identify the size of each
chunk of data.
<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>
<h5><code>writableStream.abort([reason])</code><span><a class="mark" href="#all_webstreams_writablestreamabortreason" id="all_webstreams_writablestreamabortreason">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestream_abort_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Abruptly terminates the <code>WritableStream</code>. All queued writes will be
canceled with their associated promises rejected.</p>
<h5><code>writableStream.close()</code><span><a class="mark" href="#all_webstreams_writablestreamclose" id="all_webstreams_writablestreamclose">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestream_close"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Closes the <code>WritableStream</code> when no additional writes are expected.</p>
<h5><code>writableStream.getWriter()</code><span><a class="mark" href="#all_webstreams_writablestreamgetwriter" id="all_webstreams_writablestreamgetwriter">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestream_getwriter"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Returns: <a href="#all_webstreams_class-writablestreamdefaultwriter" class="type"><WritableStreamDefaultWriter></a></li>
</ul>
<p>Creates and returns a new writer instance that can be used to write
data into the <code>WritableStream</code>.</p>
<h5><code>writableStream.locked</code><span><a class="mark" href="#all_webstreams_writablestreamlocked" id="all_webstreams_writablestreamlocked">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestream_locked"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>The <code>writableStream.locked</code> property is <code>false</code> by default, and is
switched to <code>true</code> while there is an active writer attached to this
<code>WritableStream</code>.</p>
<h5>Transferring with postMessage()<span><a class="mark" href="#all_webstreams_transferring-with-postmessage_1" id="all_webstreams_transferring-with-postmessage_1">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transferring_with_postmessage_1"></a></h5>
<p>A <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a> instance can be transferred using a <a href="#all_worker_threads_class-messageport" class="type"><MessagePort></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WritableStream</span>(<span class="hljs-title function_">getWritableSinkSomehow</span>());
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> {
data.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>);
};
port2.<span class="hljs-title function_">postMessage</span>(stream, [stream]);</code> <button class="copy-button">copy</button></pre>
<h4>Class: <code>WritableStreamDefaultWriter</code><span><a class="mark" href="#all_webstreams_class-writablestreamdefaultwriter" id="all_webstreams_class-writablestreamdefaultwriter">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_writablestreamdefaultwriter"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new WritableStreamDefaultWriter(stream)</code><span><a class="mark" href="#all_webstreams_new-writablestreamdefaultwriterstream" id="all_webstreams_new-writablestreamdefaultwriterstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_writablestreamdefaultwriter_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a></li>
</ul>
<p>Creates a new <code>WritableStreamDefaultWriter</code> that is locked to the given
<code>WritableStream</code>.</p>
<h5><code>writableStreamDefaultWriter.abort([reason])</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterabortreason" id="all_webstreams_writablestreamdefaultwriterabortreason">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_abort_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Abruptly terminates the <code>WritableStream</code>. All queued writes will be
canceled with their associated promises rejected.</p>
<h5><code>writableStreamDefaultWriter.close()</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterclose" id="all_webstreams_writablestreamdefaultwriterclose">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_close"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Closes the <code>WritableStream</code> when no additional writes are expected.</p>
<h5><code>writableStreamDefaultWriter.closed</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterclosed" id="all_webstreams_writablestreamdefaultwriterclosed">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_closed"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfilled with <code>undefined</code> when the associated
<a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a> is closed or rejected if the stream errors or the writer's
lock is released before the stream finishes closing.</li>
</ul>
<h5><code>writableStreamDefaultWriter.desiredSize</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterdesiredsize" id="all_webstreams_writablestreamdefaultwriterdesiredsize">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_desiredsize"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The amount of data required to fill the <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a>'s queue.</p>
<h5><code>writableStreamDefaultWriter.ready</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterready" id="all_webstreams_writablestreamdefaultwriterready">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_ready"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfilled with <code>undefined</code> when the writer is ready
to be used.</li>
</ul>
<h5><code>writableStreamDefaultWriter.releaseLock()</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterreleaselock" id="all_webstreams_writablestreamdefaultwriterreleaselock">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_releaselock"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Releases this writer's lock on the underlying <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a>.</p>
<h5><code>writableStreamDefaultWriter.write([chunk])</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterwritechunk" id="all_webstreams_writablestreamdefaultwriterwritechunk">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_write_chunk"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<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 promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Appends a new chunk of data to the <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a>'s queue.</p>
<h4>Class: <code>WritableStreamDefaultController</code><span><a class="mark" href="#all_webstreams_class-writablestreamdefaultcontroller" id="all_webstreams_class-writablestreamdefaultcontroller">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_writablestreamdefaultcontroller"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>WritableStreamDefaultController</code> manages the <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a>'s
internal state.</p>
<h5><code>writableStreamDefaultController.error([error])</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultcontrollererrorerror" id="all_webstreams_writablestreamdefaultcontrollererrorerror">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultcontroller_error_error"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Called by user-code to signal that an error has occurred while processing
the <code>WritableStream</code> data. When called, the <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a> will be aborted,
with currently pending writes canceled.</p>
<h5><code>writableStreamDefaultController.signal</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultcontrollersignal" id="all_webstreams_writablestreamdefaultcontrollersignal">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultcontroller_signal"></a></h5>
<ul>
<li>Type: <a href="#all_globals_class-abortsignal" class="type"><AbortSignal></a> An <code>AbortSignal</code> that can be used to cancel pending
write or close operations when a <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a> is aborted.</li>
</ul>
<h4>Class: <code>TransformStream</code><span><a class="mark" href="#all_webstreams_class-transformstream" id="all_webstreams_class-transformstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_transformstream"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>A <code>TransformStream</code> consists of a <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> and a <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a> that
are connected such that the data written to the <code>WritableStream</code> is received,
and potentially transformed, before being pushed into the <code>ReadableStream</code>'s
queue.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> {
<span class="hljs-title class_">TransformStream</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;
<span class="hljs-keyword">const</span> transform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TransformStream</span>({
<span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, controller</span>) {
controller.<span class="hljs-title function_">enqueue</span>(chunk.<span class="hljs-title function_">toUpperCase</span>());
},
});
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([
transform.<span class="hljs-property">writable</span>.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'A'</span>),
transform.<span class="hljs-property">readable</span>.<span class="hljs-title function_">getReader</span>().<span class="hljs-title function_">read</span>(),
]);</code> <button class="copy-button">copy</button></pre>
<h5><code>new TransformStream([transformer[, writableStrategy[, readableStrategy]]])</code><span><a class="mark" href="#all_webstreams_new-transformstreamtransformer-writablestrategy-readablestrategy" id="all_webstreams_new-transformstreamtransformer-writablestrategy-readablestrategy">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_transformstream_transformer_writablestrategy_readablestrategy"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>transformer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A user-defined function that is invoked immediately when
the <code>TransformStream</code> is created.
<ul>
<li><code>controller</code> <a href="#all_webstreams_class-transformstreamdefaultcontroller" class="type"><TransformStreamDefaultController></a></li>
<li>Returns: <code>undefined</code> or a promise fulfilled with <code>undefined</code></li>
</ul>
</li>
<li><code>transform</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A user-defined function that receives, and
potentially modifies, a chunk of data written to <code>transformStream.writable</code>,
before forwarding that on to <code>transformStream.readable</code>.
<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><code>controller</code> <a href="#all_webstreams_class-transformstreamdefaultcontroller" class="type"><TransformStreamDefaultController></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A user-defined function that is called immediately before
the writable side of the <code>TransformStream</code> is closed, signaling the end of
the transformation process.
<ul>
<li><code>controller</code> <a href="#all_webstreams_class-transformstreamdefaultcontroller" class="type"><TransformStreamDefaultController></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>readableType</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> the <code>readableType</code> option is reserved for future use
and <em>must</em> be <code>undefined</code>.</li>
<li><code>writableType</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> the <code>writableType</code> option is reserved for future use
and <em>must</em> be <code>undefined</code>.</li>
</ul>
</li>
<li><code>writableStrategy</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 before backpressure
is applied.</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 user-defined function used to identify the size of each
chunk of data.
<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>
<li><code>readableStrategy</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 before backpressure
is applied.</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 user-defined function used to identify the size of each
chunk of data.
<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>
<h5><code>transformStream.readable</code><span><a class="mark" href="#all_webstreams_transformstreamreadable" id="all_webstreams_transformstreamreadable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transformstream_readable"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a></li>
</ul>
<h5><code>transformStream.writable</code><span><a class="mark" href="#all_webstreams_transformstreamwritable" id="all_webstreams_transformstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transformstream_writable"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a></li>
</ul>
<h5>Transferring with postMessage()<span><a class="mark" href="#all_webstreams_transferring-with-postmessage_2" id="all_webstreams_transferring-with-postmessage_2">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transferring_with_postmessage_2"></a></h5>
<p>A <a href="#all_webstreams_class-transformstream" class="type"><TransformStream></a> instance can be transferred using a <a href="#all_worker_threads_class-messageport" class="type"><MessagePort></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TransformStream</span>();
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> {
<span class="hljs-keyword">const</span> { writable, readable } = data;
<span class="hljs-comment">// ...</span>
};
port2.<span class="hljs-title function_">postMessage</span>(stream, [stream]);</code> <button class="copy-button">copy</button></pre>
<h4>Class: <code>TransformStreamDefaultController</code><span><a class="mark" href="#all_webstreams_class-transformstreamdefaultcontroller" id="all_webstreams_class-transformstreamdefaultcontroller">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_transformstreamdefaultcontroller"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>TransformStreamDefaultController</code> manages the internal state
of the <code>TransformStream</code>.</p>
<h5><code>transformStreamDefaultController.desiredSize</code><span><a class="mark" href="#all_webstreams_transformstreamdefaultcontrollerdesiredsize" id="all_webstreams_transformstreamdefaultcontrollerdesiredsize">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transformstreamdefaultcontroller_desiredsize"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>The amount of data required to fill the readable side's queue.</p>
<h5><code>transformStreamDefaultController.enqueue([chunk])</code><span><a class="mark" href="#all_webstreams_transformstreamdefaultcontrollerenqueuechunk" id="all_webstreams_transformstreamdefaultcontrollerenqueuechunk">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transformstreamdefaultcontroller_enqueue_chunk"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<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>
</ul>
<p>Appends a chunk of data to the readable side's queue.</p>
<h5><code>transformStreamDefaultController.error([reason])</code><span><a class="mark" href="#all_webstreams_transformstreamdefaultcontrollererrorreason" id="all_webstreams_transformstreamdefaultcontrollererrorreason">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transformstreamdefaultcontroller_error_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Signals to both the readable and writable side that an error has occurred
while processing the transform data, causing both sides to be abruptly
closed.</p>
<h5><code>transformStreamDefaultController.terminate()</code><span><a class="mark" href="#all_webstreams_transformstreamdefaultcontrollerterminate" id="all_webstreams_transformstreamdefaultcontrollerterminate">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transformstreamdefaultcontroller_terminate"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Closes the readable side of the transport and causes the writable side
to be abruptly closed with an error.</p>
<h4>Class: <code>ByteLengthQueuingStrategy</code><span><a class="mark" href="#all_webstreams_class-bytelengthqueuingstrategy" id="all_webstreams_class-bytelengthqueuingstrategy">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_bytelengthqueuingstrategy"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new ByteLengthQueuingStrategy(init)</code><span><a class="mark" href="#all_webstreams_new-bytelengthqueuingstrategyinit" id="all_webstreams_new-bytelengthqueuingstrategyinit">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_bytelengthqueuingstrategy_init"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>init</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></li>
</ul>
</li>
</ul>
<h5><code>byteLengthQueuingStrategy.highWaterMark</code><span><a class="mark" href="#all_webstreams_bytelengthqueuingstrategyhighwatermark" id="all_webstreams_bytelengthqueuingstrategyhighwatermark">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_bytelengthqueuingstrategy_highwatermark"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<h5><code>byteLengthQueuingStrategy.size</code><span><a class="mark" href="#all_webstreams_bytelengthqueuingstrategysize" id="all_webstreams_bytelengthqueuingstrategysize">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_bytelengthqueuingstrategy_size"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
<h4>Class: <code>CountQueuingStrategy</code><span><a class="mark" href="#all_webstreams_class-countqueuingstrategy" id="all_webstreams_class-countqueuingstrategy">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_countqueuingstrategy"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new CountQueuingStrategy(init)</code><span><a class="mark" href="#all_webstreams_new-countqueuingstrategyinit" id="all_webstreams_new-countqueuingstrategyinit">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_countqueuingstrategy_init"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>init</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></li>
</ul>
</li>
</ul>
<h5><code>countQueuingStrategy.highWaterMark</code><span><a class="mark" href="#all_webstreams_countqueuingstrategyhighwatermark" id="all_webstreams_countqueuingstrategyhighwatermark">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_countqueuingstrategy_highwatermark"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<h5><code>countQueuingStrategy.size</code><span><a class="mark" href="#all_webstreams_countqueuingstrategysize" id="all_webstreams_countqueuingstrategysize">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_countqueuingstrategy_size"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<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>
<h4>Class: <code>TextEncoderStream</code><span><a class="mark" href="#all_webstreams_class-textencoderstream" id="all_webstreams_class-textencoderstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_textencoderstream"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.6.0</td>
<td><p><span>Added in: v16.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new TextEncoderStream()</code><span><a class="mark" href="#all_webstreams_new-textencoderstream" id="all_webstreams_new-textencoderstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_textencoderstream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<p>Creates a new <code>TextEncoderStream</code> instance.</p>
<h5><code>textEncoderStream.encoding</code><span><a class="mark" href="#all_webstreams_textencoderstreamencoding" id="all_webstreams_textencoderstreamencoding">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textencoderstream_encoding"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The encoding supported by the <code>TextEncoderStream</code> instance.</p>
<h5><code>textEncoderStream.readable</code><span><a class="mark" href="#all_webstreams_textencoderstreamreadable" id="all_webstreams_textencoderstreamreadable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textencoderstream_readable"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a></li>
</ul>
<h5><code>textEncoderStream.writable</code><span><a class="mark" href="#all_webstreams_textencoderstreamwritable" id="all_webstreams_textencoderstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textencoderstream_writable"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a></li>
</ul>
<h4>Class: <code>TextDecoderStream</code><span><a class="mark" href="#all_webstreams_class-textdecoderstream" id="all_webstreams_class-textdecoderstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_textdecoderstream"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.6.0</td>
<td><p><span>Added in: v16.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new TextDecoderStream([encoding[, options]])</code><span><a class="mark" href="#all_webstreams_new-textdecoderstreamencoding-options" id="all_webstreams_new-textdecoderstreamencoding-options">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_textdecoderstream_encoding_options"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</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> Identifies the <code>encoding</code> that this <code>TextDecoder</code> instance
supports. <strong>Default:</strong> <code>'utf-8'</code>.</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>fatal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if decoding failures are fatal.</li>
<li><code>ignoreBOM</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>TextDecoderStream</code> will include the
byte order mark in the decoded result. When <code>false</code>, the byte order mark
will be removed from the output. This option is only used when <code>encoding</code> is
<code>'utf-8'</code>, <code>'utf-16be'</code>, or <code>'utf-16le'</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>TextDecoderStream</code> instance.</p>
<h5><code>textDecoderStream.encoding</code><span><a class="mark" href="#all_webstreams_textdecoderstreamencoding" id="all_webstreams_textdecoderstreamencoding">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textdecoderstream_encoding"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>The encoding supported by the <code>TextDecoderStream</code> instance.</p>
<h5><code>textDecoderStream.fatal</code><span><a class="mark" href="#all_webstreams_textdecoderstreamfatal" id="all_webstreams_textdecoderstreamfatal">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textdecoderstream_fatal"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>The value will be <code>true</code> if decoding errors result in a <code>TypeError</code> being
thrown.</p>
<h5><code>textDecoderStream.ignoreBOM</code><span><a class="mark" href="#all_webstreams_textdecoderstreamignorebom" id="all_webstreams_textdecoderstreamignorebom">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textdecoderstream_ignorebom"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>The value will be <code>true</code> if the decoding result will include the byte order
mark.</p>
<h5><code>textDecoderStream.readable</code><span><a class="mark" href="#all_webstreams_textdecoderstreamreadable" id="all_webstreams_textdecoderstreamreadable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textdecoderstream_readable"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a></li>
</ul>
<h5><code>textDecoderStream.writable</code><span><a class="mark" href="#all_webstreams_textdecoderstreamwritable" id="all_webstreams_textdecoderstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textdecoderstream_writable"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a></li>
</ul>
<h4>Class: <code>CompressionStream</code><span><a class="mark" href="#all_webstreams_class-compressionstream" id="all_webstreams_class-compressionstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_compressionstream"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p><span>Added in: v17.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new CompressionStream(format)</code><span><a class="mark" href="#all_webstreams_new-compressionstreamformat" id="all_webstreams_new-compressionstreamformat">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_compressionstream_format"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>format now accepts <code>deflate-raw</code> value.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p><span>Added in: v17.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> One of <code>'deflate'</code>, <code>'deflate-raw'</code>, or <code>'gzip'</code>.</li>
</ul>
<h5><code>compressionStream.readable</code><span><a class="mark" href="#all_webstreams_compressionstreamreadable" id="all_webstreams_compressionstreamreadable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_compressionstream_readable"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a></li>
</ul>
<h5><code>compressionStream.writable</code><span><a class="mark" href="#all_webstreams_compressionstreamwritable" id="all_webstreams_compressionstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_compressionstream_writable"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a></li>
</ul>
<h4>Class: <code>DecompressionStream</code><span><a class="mark" href="#all_webstreams_class-decompressionstream" id="all_webstreams_class-decompressionstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_decompressionstream"></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</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p><span>Added in: v17.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new DecompressionStream(format)</code><span><a class="mark" href="#all_webstreams_new-decompressionstreamformat" id="all_webstreams_new-decompressionstreamformat">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_decompressionstream_format"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>format now accepts <code>deflate-raw</code> value.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p><span>Added in: v17.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> One of <code>'deflate'</code>, <code>'deflate-raw'</code>, or <code>'gzip'</code>.</li>
</ul>
<h5><code>decompressionStream.readable</code><span><a class="mark" href="#all_webstreams_decompressionstreamreadable" id="all_webstreams_decompressionstreamreadable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_decompressionstream_readable"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a></li>
</ul>
<h5><code>decompressionStream.writable</code><span><a class="mark" href="#all_webstreams_decompressionstreamwritable" id="all_webstreams_decompressionstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_decompressionstream_writable"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-writablestream" class="type"><WritableStream></a></li>
</ul>
<h4>Utility Consumers<span><a class="mark" href="#all_webstreams_utility-consumers" id="all_webstreams_utility-consumers">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_utility_consumers"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>The utility consumer functions provide common options for consuming
streams.</p>
<p>They are accessed using:</p>
<pre class="with-14-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> {
arrayBuffer,
blob,
buffer,
json,
text,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/consumers'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
arrayBuffer,
blob,
buffer,
json,
text,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/consumers'</span>);</code><button class="copy-button">copy</button></pre>
<h5><code>streamConsumers.arrayBuffer(stream)</code><span><a class="mark" href="#all_webstreams_streamconsumersarraybufferstream" id="all_webstreams_streamconsumersarraybufferstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_streamconsumers_arraybuffer_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> | <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with an <code>ArrayBuffer</code> containing the full
contents of the stream.</li>
</ul>
<pre class="with-57-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> { arrayBuffer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/consumers'</span>;
<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_">TextEncoder</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> encoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> dataArray = encoder.<span class="hljs-title function_">encode</span>(<span class="hljs-string">'hello world from consumers!'</span>);
<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(dataArray);
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">arrayBuffer</span>(readable);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.byteLength}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 76</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { arrayBuffer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/consumers'</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> { <span class="hljs-title class_">TextEncoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> encoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> dataArray = encoder.<span class="hljs-title function_">encode</span>(<span class="hljs-string">'hello world from consumers!'</span>);
<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(dataArray);
<span class="hljs-title function_">arrayBuffer</span>(readable).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.byteLength}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 76</span>
});</code><button class="copy-button">copy</button></pre>
<h5><code>streamConsumers.blob(stream)</code><span><a class="mark" href="#all_webstreams_streamconsumersblobstream" id="all_webstreams_streamconsumersblobstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_streamconsumers_blob_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> | <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with a <a href="#all_buffer_class-blob" class="type"><Blob></a> containing the full contents
of the stream.</li>
</ul>
<pre class="with-50-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> { blob } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/consumers'</span>;
<span class="hljs-keyword">const</span> dataBlob = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Blob</span>([<span class="hljs-string">'hello world from consumers!'</span>]);
<span class="hljs-keyword">const</span> readable = dataBlob.<span class="hljs-title function_">stream</span>();
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">blob</span>(readable);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.size}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 27</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { blob } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/consumers'</span>);
<span class="hljs-keyword">const</span> dataBlob = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Blob</span>([<span class="hljs-string">'hello world from consumers!'</span>]);
<span class="hljs-keyword">const</span> readable = dataBlob.<span class="hljs-title function_">stream</span>();
<span class="hljs-title function_">blob</span>(readable).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.size}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 27</span>
});</code><button class="copy-button">copy</button></pre>
<h5><code>streamConsumers.buffer(stream)</code><span><a class="mark" href="#all_webstreams_streamconsumersbufferstream" id="all_webstreams_streamconsumersbufferstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_streamconsumers_buffer_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> | <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with a <a href="#all_buffer_class-buffer" class="type"><Buffer></a> containing the full
contents of the stream.</li>
</ul>
<pre class="with-52-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> { buffer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/consumers'</span>;
<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_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> dataBuffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello world from consumers!'</span>);
<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(dataBuffer);
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">buffer</span>(readable);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.length}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 27</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { buffer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/consumers'</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> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> dataBuffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello world from consumers!'</span>);
<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(dataBuffer);
<span class="hljs-title function_">buffer</span>(readable).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.length}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 27</span>
});</code><button class="copy-button">copy</button></pre>
<h5><code>streamConsumers.json(stream)</code><span><a class="mark" href="#all_webstreams_streamconsumersjsonstream" id="all_webstreams_streamconsumersjsonstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_streamconsumers_json_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> | <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with the contents of the stream parsed as a
UTF-8 encoded string that is then passed through <code>JSON.parse()</code>.</li>
</ul>
<pre class="with-50-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> { json } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/consumers'</span>;
<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">const</span> items = <span class="hljs-title class_">Array</span>.<span class="hljs-title function_">from</span>(
{
<span class="hljs-attr">length</span>: <span class="hljs-number">100</span>,
},
<span class="hljs-function">() =></span> ({
<span class="hljs-attr">message</span>: <span class="hljs-string">'hello world from consumers!'</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 class_">JSON</span>.<span class="hljs-title function_">stringify</span>(items));
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">json</span>(readable);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.length}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 100</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { json } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/consumers'</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> items = <span class="hljs-title class_">Array</span>.<span class="hljs-title function_">from</span>(
{
<span class="hljs-attr">length</span>: <span class="hljs-number">100</span>,
},
<span class="hljs-function">() =></span> ({
<span class="hljs-attr">message</span>: <span class="hljs-string">'hello world from consumers!'</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 class_">JSON</span>.<span class="hljs-title function_">stringify</span>(items));
<span class="hljs-title function_">json</span>(readable).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.length}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 100</span>
});</code><button class="copy-button">copy</button></pre>
<h5><code>streamConsumers.text(stream)</code><span><a class="mark" href="#all_webstreams_streamconsumerstextstream" id="all_webstreams_streamconsumerstextstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_streamconsumers_text_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type"><ReadableStream></a> | <a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills with the contents of the stream parsed as a
UTF-8 encoded string.</li>
</ul>
<pre class="with-50-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> { text } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/consumers'</span>;
<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">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello world from consumers!'</span>);
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">text</span>(readable);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.length}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 27</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { text } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/consumers'</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> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello world from consumers!'</span>);
<span class="hljs-title function_">text</span>(readable).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.length}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 27</span>
});</code><button class="copy-button">copy</button></pre></section>
</section>
<section><h2>Worker threads<span><a class="mark" href="#all_worker_threads_worker-threads" id="all_worker_threads_worker-threads">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_threads"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/worker_threads.js">lib/worker_threads.js</a></p>
<p>The <code>node:worker_threads</code> module enables the use of threads that execute
JavaScript in parallel. To access it:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> worker = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);</code> <button class="copy-button">copy</button></pre>
<p>Workers (threads) are useful for performing CPU-intensive JavaScript operations.
They do not help much with I/O-intensive work. The Node.js built-in
asynchronous I/O operations are more efficient than Workers can be.</p>
<p>Unlike <code>child_process</code> or <code>cluster</code>, <code>worker_threads</code> can share memory. They do
so by transferring <code>ArrayBuffer</code> instances or sharing <code>SharedArrayBuffer</code>
instances.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
<span class="hljs-title class_">Worker</span>, isMainThread, parentPort, workerData,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">if</span> (isMainThread) {
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">parseJSAsync</span>(<span class="hljs-params">script</span>) {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename, {
<span class="hljs-attr">workerData</span>: script,
});
worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, resolve);
worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, reject);
worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
<span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</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">`Worker stopped with exit code <span class="hljs-subst">${code}</span>`</span>));
});
});
};
} <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">const</span> { parse } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'some-js-parsing-library'</span>);
<span class="hljs-keyword">const</span> script = workerData;
parentPort.<span class="hljs-title function_">postMessage</span>(<span class="hljs-title function_">parse</span>(script));
}</code> <button class="copy-button">copy</button></pre>
<p>The above example spawns a Worker thread for each <code>parseJSAsync()</code> call. In
practice, use a pool of Workers for these kinds of tasks. Otherwise, the
overhead of creating Workers would likely exceed their benefit.</p>
<p>When implementing a worker pool, use the <a href="#all_async_hooks_class-asyncresource"><code>AsyncResource</code></a> API to inform
diagnostic tools (e.g. to provide asynchronous stack traces) about the
correlation between tasks and their outcomes. See
<a href="#all_async_context_using-asyncresource-for-a-worker-thread-pool">"Using <code>AsyncResource</code> for a <code>Worker</code> thread pool"</a>
in the <code>async_hooks</code> documentation for an example implementation.</p>
<p>Worker threads inherit non-process-specific options by default. Refer to
<a href="#all_worker_threads_new-workerfilename-options"><code>Worker constructor options</code></a> to know how to customize worker thread options,
specifically <code>argv</code> and <code>execArgv</code> options.</p>
<section><h3><code>worker.getEnvironmentData(key)</code><span><a class="mark" href="#all_worker_threads_workergetenvironmentdatakey" id="all_worker_threads_workergetenvironmentdatakey">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_getenvironmentdata_key"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.12.0, v14.18.0</td>
<td><p><span>Added in: v15.12.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any arbitrary, cloneable JavaScript value that can be used as a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type"><Map></a> key.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>Within a worker thread, <code>worker.getEnvironmentData()</code> returns a clone
of data passed to the spawning thread's <code>worker.setEnvironmentData()</code>.
Every new <code>Worker</code> receives its own copy of the environment data
automatically.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
<span class="hljs-title class_">Worker</span>,
isMainThread,
setEnvironmentData,
getEnvironmentData,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">if</span> (isMainThread) {
<span class="hljs-title function_">setEnvironmentData</span>(<span class="hljs-string">'Hello'</span>, <span class="hljs-string">'World!'</span>);
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEnvironmentData</span>(<span class="hljs-string">'Hello'</span>)); <span class="hljs-comment">// Prints 'World!'.</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.isMainThread</code><span><a class="mark" href="#all_worker_threads_workerismainthread" id="all_worker_threads_workerismainthread">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_ismainthread"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.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 this code is not running inside of a <a href="#all_worker_threads_class-worker"><code>Worker</code></a> thread.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">if</span> (isMainThread) {
<span class="hljs-comment">// This re-loads the current file inside a Worker instance.</span>
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Inside Worker!'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(isMainThread); <span class="hljs-comment">// Prints 'false'.</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.markAsUntransferable(object)</code><span><a class="mark" href="#all_worker_threads_workermarkasuntransferableobject" id="all_worker_threads_workermarkasuntransferableobject">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_markasuntransferable_object"></a></h3>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</div>
<p>Mark an object as not transferable. If <code>object</code> occurs in the transfer list of
a <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> call, it is ignored.</p>
<p>In particular, this makes sense for objects that can be cloned, rather than
transferred, and which are used by other objects on the sending side.
For example, Node.js marks the <code>ArrayBuffer</code>s it uses for its
<a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer</code> pool</a> with this.</p>
<p>This operation cannot be undone.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span>, markAsUntransferable } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> pooledBuffer = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">8</span>);
<span class="hljs-keyword">const</span> typedArray1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(pooledBuffer);
<span class="hljs-keyword">const</span> typedArray2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>(pooledBuffer);
<span class="hljs-title function_">markAsUntransferable</span>(pooledBuffer);
<span class="hljs-keyword">const</span> { port1 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">postMessage</span>(typedArray1, [ typedArray1.<span class="hljs-property">buffer</span> ]);
<span class="hljs-comment">// The following line prints the contents of typedArray1 -- it still owns</span>
<span class="hljs-comment">// its memory and has been cloned, not transferred. Without</span>
<span class="hljs-comment">// `markAsUntransferable()`, this would print an empty Uint8Array.</span>
<span class="hljs-comment">// typedArray2 is intact as well.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(typedArray1);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(typedArray2);</code> <button class="copy-button">copy</button></pre>
<p>There is no equivalent to this API in browsers.</p>
</section><section><h3><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code><span><a class="mark" href="#all_worker_threads_workermovemessageporttocontextport-contextifiedsandbox" id="all_worker_threads_workermovemessageporttocontextport-contextifiedsandbox">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_movemessageporttocontext_port_contextifiedsandbox"></a></h3>
<div class="api_metadata">
<span>Added in: v11.13.0</span>
</div>
<ul>
<li>
<p><code>port</code> <a href="#all_worker_threads_class-messageport" class="type"><MessagePort></a> The message port to transfer.</p>
</li>
<li>
<p><code>contextifiedSandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> object as returned by the
<code>vm.createContext()</code> method.</p>
</li>
<li>
<p>Returns: <a href="#all_worker_threads_class-messageport" class="type"><MessagePort></a></p>
</li>
</ul>
<p>Transfer a <code>MessagePort</code> to a different <a href="vm.html"><code>vm</code></a> Context. The original <code>port</code>
object is rendered unusable, and the returned <code>MessagePort</code> instance
takes its place.</p>
<p>The returned <code>MessagePort</code> is an object in the target context and
inherits from its global <code>Object</code> class. Objects passed to the
<a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage"><code>port.onmessage()</code></a> listener are also created in the target context
and inherit from its global <code>Object</code> class.</p>
<p>However, the created <code>MessagePort</code> no longer inherits from
<a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget"><code>EventTarget</code></a>, and only <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage"><code>port.onmessage()</code></a> can be used to receive
events using it.</p>
</section><section><h3><code>worker.parentPort</code><span><a class="mark" href="#all_worker_threads_workerparentport" id="all_worker_threads_workerparentport">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_parentport"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.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="#all_worker_threads_class-messageport" class="type"><MessagePort></a></li>
</ul>
<p>If this thread is a <a href="#all_worker_threads_class-worker"><code>Worker</code></a>, this is a <a href="#all_worker_threads_class-messageport"><code>MessagePort</code></a>
allowing communication with the parent thread. Messages sent using
<code>parentPort.postMessage()</code> are available in the parent thread
using <code>worker.on('message')</code>, and messages sent from the parent thread
using <code>worker.postMessage()</code> are available in this thread using
<code>parentPort.on('message')</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">if</span> (isMainThread) {
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
worker.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message); <span class="hljs-comment">// Prints 'Hello, world!'.</span>
});
worker.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'Hello, world!'</span>);
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// When a message from the parent thread is received, send it back:</span>
parentPort.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
parentPort.<span class="hljs-title function_">postMessage</span>(message);
});
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.postMessageToThread(threadId, value[, transferList][, timeout])</code><span><a class="mark" href="#all_worker_threads_workerpostmessagetothreadthreadid-value-transferlist-timeout" id="all_worker_threads_workerpostmessagetothreadthreadid-value-transferlist-timeout">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_postmessagetothread_threadid_value_transferlist_timeout"></a></h3>
<div class="api_metadata">
<span>Added in: v20.19.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<ul>
<li><code>destination</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The target thread ID. If the thread ID is invalid, a
<a href="#all_errors_err_worker_messaging_failed"><code>ERR_WORKER_MESSAGING_FAILED</code></a> error will be thrown. If the target thread ID is the current thread ID,
a <a href="#all_errors_err_worker_messaging_same_thread"><code>ERR_WORKER_MESSAGING_SAME_THREAD</code></a> error will be thrown.</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The value to send.</li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> If one or more <code>MessagePort</code>-like objects are passed in <code>value</code>,
a <code>transferList</code> is required for those items or <a href="#all_errors_err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a> is thrown.
See <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more information.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Time to wait for the message to be delivered in milliseconds.
By default it's <code>undefined</code>, which means wait forever. If the operation times out,
a <a href="#all_errors_err_worker_messaging_timeout"><code>ERR_WORKER_MESSAGING_TIMEOUT</code></a> error is thrown.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> A promise which is fulfilled if the message was successfully processed by destination thread.</li>
</ul>
<p>Sends a value to another worker, identified by its thread ID.</p>
<p>If the target thread has no listener for the <code>workerMessage</code> event, then the operation will throw
a <a href="#all_errors_err_worker_messaging_failed"><code>ERR_WORKER_MESSAGING_FAILED</code></a> error.</p>
<p>If the target thread threw an error while processing the <code>workerMessage</code> event, then the operation will throw
a <a href="#all_errors_err_worker_messaging_errored"><code>ERR_WORKER_MESSAGING_ERRORED</code></a> error.</p>
<p>This method should be used when the target thread is not the direct
parent or child of the current thread.
If the two threads are parent-children, use the <a href="#all_worker_threads_workerpostmessagevalue-transferlist"><code>require('node:worker_threads').parentPort.postMessage()</code></a>
and the <a href="#all_worker_threads_workerpostmessagevalue-transferlist"><code>worker.postMessage()</code></a> to let the threads communicate.</p>
<p>The example below shows the use of of <code>postMessageToThread</code>: it creates 10 nested threads,
the last one will try to communicate with the main thread.</p>
<pre class="with-41-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> { fileURLToPath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">import</span> { once } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> {
isMainThread,
postMessageToThread,
threadId,
workerData,
<span class="hljs-title class_">Worker</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
<span class="hljs-keyword">const</span> channel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">BroadcastChannel</span>(<span class="hljs-string">'sync'</span>);
<span class="hljs-keyword">const</span> level = workerData?.<span class="hljs-property">level</span> ?? <span class="hljs-number">0</span>;
<span class="hljs-keyword">if</span> (level < <span class="hljs-number">10</span>) {
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>), {
<span class="hljs-attr">workerData</span>: { <span class="hljs-attr">level</span>: level + <span class="hljs-number">1</span> },
});
}
<span class="hljs-keyword">if</span> (level === <span class="hljs-number">0</span>) {
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'workerMessage'</span>, <span class="hljs-function">(<span class="hljs-params">value, source</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${source}</span> -> <span class="hljs-subst">${threadId}</span>:`</span>, value);
<span class="hljs-title function_">postMessageToThread</span>(source, { <span class="hljs-attr">message</span>: <span class="hljs-string">'pong'</span> });
});
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (level === <span class="hljs-number">10</span>) {
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'workerMessage'</span>, <span class="hljs-function">(<span class="hljs-params">value, source</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${source}</span> -> <span class="hljs-subst">${threadId}</span>:`</span>, value);
channel.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'done'</span>);
channel.<span class="hljs-title function_">close</span>();
});
<span class="hljs-keyword">await</span> <span class="hljs-title function_">postMessageToThread</span>(<span class="hljs-number">0</span>, { <span class="hljs-attr">message</span>: <span class="hljs-string">'ping'</span> });
}
channel.<span class="hljs-property">onmessage</span> = channel.<span class="hljs-property">close</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> {
isMainThread,
postMessageToThread,
threadId,
workerData,
<span class="hljs-title class_">Worker</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> channel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">BroadcastChannel</span>(<span class="hljs-string">'sync'</span>);
<span class="hljs-keyword">const</span> level = workerData?.<span class="hljs-property">level</span> ?? <span class="hljs-number">0</span>;
<span class="hljs-keyword">if</span> (level < <span class="hljs-number">10</span>) {
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename, {
<span class="hljs-attr">workerData</span>: { <span class="hljs-attr">level</span>: level + <span class="hljs-number">1</span> },
});
}
<span class="hljs-keyword">if</span> (level === <span class="hljs-number">0</span>) {
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'workerMessage'</span>, <span class="hljs-function">(<span class="hljs-params">value, source</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${source}</span> -> <span class="hljs-subst">${threadId}</span>:`</span>, value);
<span class="hljs-title function_">postMessageToThread</span>(source, { <span class="hljs-attr">message</span>: <span class="hljs-string">'pong'</span> });
});
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (level === <span class="hljs-number">10</span>) {
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'workerMessage'</span>, <span class="hljs-function">(<span class="hljs-params">value, source</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${source}</span> -> <span class="hljs-subst">${threadId}</span>:`</span>, value);
channel.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'done'</span>);
channel.<span class="hljs-title function_">close</span>();
});
<span class="hljs-title function_">postMessageToThread</span>(<span class="hljs-number">0</span>, { <span class="hljs-attr">message</span>: <span class="hljs-string">'ping'</span> });
}
channel.<span class="hljs-property">onmessage</span> = channel.<span class="hljs-property">close</span>;</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.receiveMessageOnPort(port)</code><span><a class="mark" href="#all_worker_threads_workerreceivemessageonportport" id="all_worker_threads_workerreceivemessageonportport">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_receivemessageonport_port"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.12.0</td>
<td><p>The port argument can also refer to a <code>BroadcastChannel</code> now.</p></td></tr>
<tr><td>v12.3.0</td>
<td><p><span>Added in: v12.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>port</code> <a href="#all_worker_threads_class-messageport" class="type"><MessagePort></a> | <a href="#all_worker_threads_class-broadcastchannel-extends-eventtarget" class="type"><BroadcastChannel></a></p>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></p>
</li>
</ul>
<p>Receive a single message from a given <code>MessagePort</code>. If no message is available,
<code>undefined</code> is returned, otherwise an object with a single <code>message</code> property
that contains the message payload, corresponding to the oldest message in the
<code>MessagePort</code>'s queue.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span>, receiveMessageOnPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">receiveMessageOnPort</span>(port2));
<span class="hljs-comment">// Prints: { message: { hello: 'world' } }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">receiveMessageOnPort</span>(port2));
<span class="hljs-comment">// Prints: undefined</span></code> <button class="copy-button">copy</button></pre>
<p>When this function is used, no <code>'message'</code> event is emitted and the
<code>onmessage</code> listener is not invoked.</p>
</section><section><h3><code>worker.resourceLimits</code><span><a class="mark" href="#all_worker_threads_workerresourcelimits" id="all_worker_threads_workerresourcelimits">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_resourcelimits"></a></h3>
<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/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</li>
</ul>
<p>Provides the set of JS engine resource constraints inside this Worker thread.
If the <code>resourceLimits</code> option was passed to the <a href="#all_worker_threads_class-worker"><code>Worker</code></a> constructor,
this matches its values.</p>
<p>If this is used in the main thread, its value is an empty object.</p>
</section><section><h3><code>worker.SHARE_ENV</code><span><a class="mark" href="#all_worker_threads_workershare_env" id="all_worker_threads_workershare_env">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_share_env"></a></h3>
<div class="api_metadata">
<span>Added in: v11.14.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></li>
</ul>
<p>A special value that can be passed as the <code>env</code> option of the <a href="#all_worker_threads_class-worker"><code>Worker</code></a>
constructor, to indicate that the current thread and the Worker thread should
share read and write access to the same set of environment variables.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, <span class="hljs-variable constant_">SHARE_ENV</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-string">'process.env.SET_IN_WORKER = "foo"'</span>, { <span class="hljs-attr">eval</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">env</span>: <span class="hljs-variable constant_">SHARE_ENV</span> })
.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-property">env</span>.<span class="hljs-property">SET_IN_WORKER</span>); <span class="hljs-comment">// Prints 'foo'.</span>
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.setEnvironmentData(key[, value])</code><span><a class="mark" href="#all_worker_threads_workersetenvironmentdatakey-value" id="all_worker_threads_workersetenvironmentdatakey-value">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_setenvironmentdata_key_value"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.12.0, v14.18.0</td>
<td><p><span>Added in: v15.12.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any arbitrary, cloneable JavaScript value that can be used as a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type"><Map></a> key.</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any arbitrary, cloneable JavaScript value that will be cloned
and passed automatically to all new <code>Worker</code> instances. If <code>value</code> is passed
as <code>undefined</code>, any previously set value for the <code>key</code> will be deleted.</li>
</ul>
<p>The <code>worker.setEnvironmentData()</code> API sets the content of
<code>worker.getEnvironmentData()</code> in the current thread and all new <code>Worker</code>
instances spawned from the current context.</p>
</section><section><h3><code>worker.threadId</code><span><a class="mark" href="#all_worker_threads_workerthreadid" id="all_worker_threads_workerthreadid">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_threadid"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.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>An integer identifier for the current thread. On the corresponding worker object
(if there is any), it is available as <a href="#all_worker_threads_workerthreadid_1"><code>worker.threadId</code></a>.
This value is unique for each <a href="#all_worker_threads_class-worker"><code>Worker</code></a> instance inside a single process.</p>
</section><section><h3><code>worker.workerData</code><span><a class="mark" href="#all_worker_threads_workerworkerdata" id="all_worker_threads_workerworkerdata">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_workerdata"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>An arbitrary JavaScript value that contains a clone of the data passed
to this thread's <code>Worker</code> constructor.</p>
<p>The data is cloned as if using <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>postMessage()</code></a>,
according to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, workerData } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">if</span> (isMainThread) {
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename, { <span class="hljs-attr">workerData</span>: <span class="hljs-string">'Hello, world!'</span> });
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(workerData); <span class="hljs-comment">// Prints 'Hello, world!'.</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>BroadcastChannel extends EventTarget</code><span><a class="mark" href="#all_worker_threads_class-broadcastchannel-extends-eventtarget" id="all_worker_threads_class-broadcastchannel-extends-eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_broadcastchannel_extends_eventtarget"></a></h3>
<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</td>
<td><p>No longer experimental.</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>
<p>Instances of <code>BroadcastChannel</code> allow asynchronous one-to-many communication
with all other <code>BroadcastChannel</code> instances bound to the same channel name.</p>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> {
isMainThread,
<span class="hljs-title class_">BroadcastChannel</span>,
<span class="hljs-title class_">Worker</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> bc = <span class="hljs-keyword">new</span> <span class="hljs-title class_">BroadcastChannel</span>(<span class="hljs-string">'hello'</span>);
<span class="hljs-keyword">if</span> (isMainThread) {
<span class="hljs-keyword">let</span> c = <span class="hljs-number">0</span>;
bc.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">event</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">data</span>);
<span class="hljs-keyword">if</span> (++c === <span class="hljs-number">10</span>) bc.<span class="hljs-title function_">close</span>();
};
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n < <span class="hljs-number">10</span>; n++)
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
} <span class="hljs-keyword">else</span> {
bc.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'hello from every worker'</span>);
bc.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<h4><code>new BroadcastChannel(name)</code><span><a class="mark" href="#all_worker_threads_new-broadcastchannelname" id="all_worker_threads_new-broadcastchannelname">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_new_broadcastchannel_name"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The name of the channel to connect to. Any JavaScript value
that can be converted to a string using <code>`${name}`</code> is permitted.</li>
</ul>
<h4><code>broadcastChannel.close()</code><span><a class="mark" href="#all_worker_threads_broadcastchannelclose" id="all_worker_threads_broadcastchannelclose">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_close"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<p>Closes the <code>BroadcastChannel</code> connection.</p>
<h4><code>broadcastChannel.onmessage</code><span><a class="mark" href="#all_worker_threads_broadcastchannelonmessage" id="all_worker_threads_broadcastchannelonmessage">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_onmessage"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Invoked with a single <code>MessageEvent</code> argument
when a message is received.</li>
</ul>
<h4><code>broadcastChannel.onmessageerror</code><span><a class="mark" href="#all_worker_threads_broadcastchannelonmessageerror" id="all_worker_threads_broadcastchannelonmessageerror">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_onmessageerror"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Invoked with a received message cannot be
deserialized.</li>
</ul>
<h4><code>broadcastChannel.postMessage(message)</code><span><a class="mark" href="#all_worker_threads_broadcastchannelpostmessagemessage" id="all_worker_threads_broadcastchannelpostmessagemessage">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_postmessage_message"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any cloneable JavaScript value.</li>
</ul>
<h4><code>broadcastChannel.ref()</code><span><a class="mark" href="#all_worker_threads_broadcastchannelref" id="all_worker_threads_broadcastchannelref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<p>Opposite of <code>unref()</code>. Calling <code>ref()</code> on a previously <code>unref()</code>ed
BroadcastChannel does <em>not</em> let the program exit if it's the only active handle
left (the default behavior). If the port is <code>ref()</code>ed, calling <code>ref()</code> again
has no effect.</p>
<h4><code>broadcastChannel.unref()</code><span><a class="mark" href="#all_worker_threads_broadcastchannelunref" id="all_worker_threads_broadcastchannelunref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<p>Calling <code>unref()</code> on a BroadcastChannel allows the thread to exit if this
is the only active handle in the event system. If the BroadcastChannel is
already <code>unref()</code>ed calling <code>unref()</code> again has no effect.</p>
</section><section><h3>Class: <code>MessageChannel</code><span><a class="mark" href="#all_worker_threads_class-messagechannel" id="all_worker_threads_class-messagechannel">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_messagechannel"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Instances of the <code>worker.MessageChannel</code> class represent an asynchronous,
two-way communications channel.
The <code>MessageChannel</code> has no methods of its own. <code>new MessageChannel()</code>
yields an object with <code>port1</code> and <code>port2</code> properties, which refer to linked
<a href="#all_worker_threads_class-messageport"><code>MessagePort</code></a> instances.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'received'</span>, message));
port2.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span> });
<span class="hljs-comment">// Prints: received { foo: 'bar' } from the `port1.on('message')` listener</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>MessagePort</code><span><a class="mark" href="#all_worker_threads_class-messageport" id="all_worker_threads_class-messageport">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_messageport"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.7.0</td>
<td><p>This class now inherits from <code>EventTarget</code> rather than from <code>EventEmitter</code>.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventtarget" class="type"><EventTarget></a></li>
</ul>
<p>Instances of the <code>worker.MessagePort</code> class represent one end of an
asynchronous, two-way communications channel. It can be used to transfer
structured data, memory regions and other <code>MessagePort</code>s between different
<a href="#all_worker_threads_class-worker"><code>Worker</code></a>s.</p>
<p>This implementation matches <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort">browser <code>MessagePort</code></a>s.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_worker_threads_event-close" id="all_worker_threads_event-close">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_close"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>The <code>'close'</code> event is emitted once either side of the channel has been
disconnected.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// foobar</span>
<span class="hljs-comment">// closed!</span>
port2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message));
port2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'closed!'</span>));
port1.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'foobar'</span>);
port1.<span class="hljs-title function_">close</span>();</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'message'</code><span><a class="mark" href="#all_worker_threads_event-message" id="all_worker_threads_event-message">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_message"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The transmitted value</li>
</ul>
<p>The <code>'message'</code> event is emitted for any incoming message, containing the cloned
input of <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>port.postMessage()</code></a>.</p>
<p>Listeners on this event receive a clone of the <code>value</code> parameter as passed
to <code>postMessage()</code> and no further arguments.</p>
<h4>Event: <code>'messageerror'</code><span><a class="mark" href="#all_worker_threads_event-messageerror" id="all_worker_threads_event-messageerror">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_messageerror"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</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> An Error object</li>
</ul>
<p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p>
<p>Currently, this event is emitted when there is an error occurring while
instantiating the posted JS object on the receiving end. Such situations
are rare, but can happen, for instance, when certain Node.js API objects
are received in a <code>vm.Context</code> (where Node.js APIs are currently
unavailable).</p>
<h4><code>port.close()</code><span><a class="mark" href="#all_worker_threads_portclose" id="all_worker_threads_portclose">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_close"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Disables further sending of messages on either side of the connection.
This method can be called when no further communication will happen over this
<code>MessagePort</code>.</p>
<p>The <a href="#all_worker_threads_event-close"><code>'close'</code> event</a> is emitted on both <code>MessagePort</code> instances that
are part of the channel.</p>
<h4><code>port.postMessage(value[, transferList])</code><span><a class="mark" href="#all_worker_threads_portpostmessagevalue-transferlist" id="all_worker_threads_portpostmessagevalue-transferlist">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_postmessage_value_transferlist"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.6.0</td>
<td><p>Added <code>X509Certificate</code> to the list of cloneable types.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Added <code>CryptoKey</code> to the list of cloneable types.</p></td></tr>
<tr><td>v15.14.0, v14.18.0</td>
<td><p>Add 'BlockList' to the list of cloneable types.</p></td></tr>
<tr><td>v15.9.0, v14.18.0</td>
<td><p>Add 'Histogram' types to the list of cloneable types.</p></td></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Added <code>KeyObject</code> to the list of cloneable types.</p></td></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Added <code>FileHandle</code> to the list of transferable types.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li>
</ul>
<p>Sends a JavaScript value to the receiving side of this channel.
<code>value</code> is transferred in a way which is compatible with
the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>.</p>
<p>In particular, the significant differences to <code>JSON</code> are:</p>
<ul>
<li><code>value</code> may contain circular references.</li>
<li><code>value</code> may contain instances of builtin JS types such as <code>RegExp</code>s,
<code>BigInt</code>s, <code>Map</code>s, <code>Set</code>s, etc.</li>
<li><code>value</code> may contain typed arrays, both using <code>ArrayBuffer</code>s
and <code>SharedArrayBuffer</code>s.</li>
<li><code>value</code> may contain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module"><code>WebAssembly.Module</code></a> instances.</li>
<li><code>value</code> may not contain native (C++-backed) objects other than:
<ul>
<li><a href="#all_webcrypto_class-cryptokey" class="type"><CryptoKey></a>s,</li>
<li><a href="#all_fs_class-filehandle" class="type"><FileHandle></a>s,</li>
<li><a href="#all_perf_hooks_class-histogram" class="type"><Histogram></a>s,</li>
<li><a href="#all_crypto_class-keyobject" class="type"><KeyObject></a>s,</li>
<li><a href="#all_worker_threads_class-messageport" class="type"><MessagePort></a>s,</li>
<li><a href="#all_net_class-netblocklist" class="type"><net.BlockList></a>s,</li>
<li><a href="#all_net_class-netsocketaddress" class="type"><net.SocketAddress></a>es,</li>
<li><a href="#all_crypto_class-x509certificate" class="type"><X509Certificate></a>s.</li>
</ul>
</li>
</ul>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message));
<span class="hljs-keyword">const</span> circularData = {};
circularData.<span class="hljs-property">foo</span> = circularData;
<span class="hljs-comment">// Prints: { foo: [Circular] }</span>
port2.<span class="hljs-title function_">postMessage</span>(circularData);</code> <button class="copy-button">copy</button></pre>
<p><code>transferList</code> may be a list of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="#all_worker_threads_class-messageport"><code>MessagePort</code></a>, and
<a href="#all_fs_class-filehandle"><code>FileHandle</code></a> objects.
After transferring, they are not usable on the sending side of the channel
anymore (even if they are not contained in <code>value</code>). Unlike with
<a href="child_process.html">child processes</a>, transferring handles such as network sockets is currently
not supported.</p>
<p>If <code>value</code> contains <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instances, those are accessible
from either thread. They cannot be listed in <code>transferList</code>.</p>
<p><code>value</code> may still contain <code>ArrayBuffer</code> instances that are not in
<code>transferList</code>; in that case, the underlying memory is copied rather than moved.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message));
<span class="hljs-keyword">const</span> uint8Array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</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-comment">// This posts a copy of `uint8Array`:</span>
port2.<span class="hljs-title function_">postMessage</span>(uint8Array);
<span class="hljs-comment">// This does not copy data, but renders `uint8Array` unusable:</span>
port2.<span class="hljs-title function_">postMessage</span>(uint8Array, [ uint8Array.<span class="hljs-property">buffer</span> ]);
<span class="hljs-comment">// The memory for the `sharedUint8Array` is accessible from both the</span>
<span class="hljs-comment">// original and the copy received by `.on('message')`:</span>
<span class="hljs-keyword">const</span> sharedUint8Array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">SharedArrayBuffer</span>(<span class="hljs-number">4</span>));
port2.<span class="hljs-title function_">postMessage</span>(sharedUint8Array);
<span class="hljs-comment">// This transfers a freshly created message port to the receiver.</span>
<span class="hljs-comment">// This can be used, for example, to create communication channels between</span>
<span class="hljs-comment">// multiple `Worker` threads that are children of the same parent thread.</span>
<span class="hljs-keyword">const</span> otherChannel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port2.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">port</span>: otherChannel.<span class="hljs-property">port1</span> }, [ otherChannel.<span class="hljs-property">port1</span> ]);</code> <button class="copy-button">copy</button></pre>
<p>The message object is cloned immediately, and can be modified after
posting without having side effects.</p>
<p>For more information on the serialization and deserialization mechanisms
behind this API, see the <a href="#all_v8_serialization-api">serialization API of the <code>node:v8</code> module</a>.</p>
<h5>Considerations when transferring TypedArrays and Buffers<span><a class="mark" href="#all_worker_threads_considerations-when-transferring-typedarrays-and-buffers" id="all_worker_threads_considerations-when-transferring-typedarrays-and-buffers">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_considerations_when_transferring_typedarrays_and_buffers"></a></h5>
<p>All <code>TypedArray</code> and <code>Buffer</code> instances are views over an underlying
<code>ArrayBuffer</code>. That is, it is the <code>ArrayBuffer</code> that actually stores
the raw data while the <code>TypedArray</code> and <code>Buffer</code> objects provide a
way of viewing and manipulating the data. It is possible and common
for multiple views to be created over the same <code>ArrayBuffer</code> instance.
Great care must be taken when using a transfer list to transfer an
<code>ArrayBuffer</code> as doing so causes all <code>TypedArray</code> and <code>Buffer</code>
instances that share that same <code>ArrayBuffer</code> to become unusable.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> u1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(ab);
<span class="hljs-keyword">const</span> u2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(ab);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u2.<span class="hljs-property">length</span>); <span class="hljs-comment">// prints 5</span>
port.<span class="hljs-title function_">postMessage</span>(u1, [u1.<span class="hljs-property">buffer</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u2.<span class="hljs-property">length</span>); <span class="hljs-comment">// prints 0</span></code> <button class="copy-button">copy</button></pre>
<p>For <code>Buffer</code> instances, specifically, whether the underlying
<code>ArrayBuffer</code> can be transferred or cloned depends entirely on how
instances were created, which often cannot be reliably determined.</p>
<p>An <code>ArrayBuffer</code> can be marked with <a href="#all_worker_threads_workermarkasuntransferableobject"><code>markAsUntransferable()</code></a> to indicate
that it should always be cloned and never transferred.</p>
<p>Depending on how a <code>Buffer</code> instance was created, it may or may
not own its underlying <code>ArrayBuffer</code>. An <code>ArrayBuffer</code> must not
be transferred unless it is known that the <code>Buffer</code> instance
owns it. In particular, for <code>Buffer</code>s created from the internal
<code>Buffer</code> pool (using, for instance <code>Buffer.from()</code> or <code>Buffer.allocUnsafe()</code>),
transferring them is not possible and they are always cloned,
which sends a copy of the entire <code>Buffer</code> pool.
This behavior may come with unintended higher memory
usage and possible security concerns.</p>
<p>See <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> for more details on <code>Buffer</code> pooling.</p>
<p>The <code>ArrayBuffer</code>s for <code>Buffer</code> instances created using
<code>Buffer.alloc()</code> or <code>Buffer.allocUnsafeSlow()</code> can always be
transferred but doing so renders all other existing views of
those <code>ArrayBuffer</code>s unusable.</p>
<h5>Considerations when cloning objects with prototypes, classes, and accessors<span><a class="mark" href="#all_worker_threads_considerations-when-cloning-objects-with-prototypes-classes-and-accessors" id="all_worker_threads_considerations-when-cloning-objects-with-prototypes-classes-and-accessors">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_considerations_when_cloning_objects_with_prototypes_classes_and_accessors"></a></h5>
<p>Because object cloning uses the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>,
non-enumerable properties, property accessors, and object prototypes are
not preserved. In particular, <a href="buffer.html"><code>Buffer</code></a> objects will be read as
plain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>s on the receiving side, and instances of JavaScript
classes will be cloned as plain JavaScript objects.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'b'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
#a = <span class="hljs-number">1</span>;
<span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">this</span>[b] = <span class="hljs-number">2</span>;
<span class="hljs-variable language_">this</span>.<span class="hljs-property">c</span> = <span class="hljs-number">3</span>;
}
<span class="hljs-keyword">get</span> <span class="hljs-title function_">d</span>() { <span class="hljs-keyword">return</span> <span class="hljs-number">4</span>; }
}
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
port2.<span class="hljs-title function_">postMessage</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>());
<span class="hljs-comment">// Prints: { c: 3 }</span></code> <button class="copy-button">copy</button></pre>
<p>This limitation extends to many built-in objects, such as the global <code>URL</code>
object:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
port2.<span class="hljs-title function_">postMessage</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org'</span>));
<span class="hljs-comment">// Prints: { }</span></code> <button class="copy-button">copy</button></pre>
<h4><code>port.hasRef()</code><span><a class="mark" href="#all_worker_threads_porthasref" id="all_worker_threads_porthasref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_hasref"></a></h4>
<div class="api_metadata">
<span>Added in: v18.1.0, v16.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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>If true, the <code>MessagePort</code> object will keep the Node.js event loop active.</p>
<h4><code>port.ref()</code><span><a class="mark" href="#all_worker_threads_portref" id="all_worker_threads_portref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Opposite of <code>unref()</code>. Calling <code>ref()</code> on a previously <code>unref()</code>ed port does
<em>not</em> let the program exit if it's the only active handle left (the default
behavior). If the port is <code>ref()</code>ed, calling <code>ref()</code> again has no effect.</p>
<p>If listeners are attached or removed using <code>.on('message')</code>, the port
is <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether
listeners for the event exist.</p>
<h4><code>port.start()</code><span><a class="mark" href="#all_worker_threads_portstart" id="all_worker_threads_portstart">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_start"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Starts receiving messages on this <code>MessagePort</code>. When using this port
as an event emitter, this is called automatically once <code>'message'</code>
listeners are attached.</p>
<p>This method exists for parity with the Web <code>MessagePort</code> API. In Node.js,
it is only useful for ignoring messages when no event listener is present.
Node.js also diverges in its handling of <code>.onmessage</code>. Setting it
automatically calls <code>.start()</code>, but unsetting it lets messages queue up
until a new handler is set or the port is discarded.</p>
<h4><code>port.unref()</code><span><a class="mark" href="#all_worker_threads_portunref" id="all_worker_threads_portunref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Calling <code>unref()</code> on a port allows the thread to exit if this is the only
active handle in the event system. If the port is already <code>unref()</code>ed calling
<code>unref()</code> again has no effect.</p>
<p>If listeners are attached or removed using <code>.on('message')</code>, the port is
<code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether
listeners for the event exist.</p>
</section><section><h3>Class: <code>Worker</code><span><a class="mark" href="#all_worker_threads_class-worker" id="all_worker_threads_class-worker">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_worker"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventemitter" class="type"><EventEmitter></a></li>
</ul>
<p>The <code>Worker</code> class represents an independent JavaScript execution thread.
Most Node.js APIs are available inside of it.</p>
<p>Notable differences inside a Worker environment are:</p>
<ul>
<li>The <a href="#all_process_processstdin"><code>process.stdin</code></a>, <a href="#all_process_processstdout"><code>process.stdout</code></a>, and <a href="#all_process_processstderr"><code>process.stderr</code></a>
streams may be redirected by the parent thread.</li>
<li>The <a href="#all_worker_threads_workerismainthread"><code>require('node:worker_threads').isMainThread</code></a> property is set to <code>false</code>.</li>
<li>The <a href="#all_worker_threads_workerparentport"><code>require('node:worker_threads').parentPort</code></a> message port is available.</li>
<li><a href="#all_process_processexitcode"><code>process.exit()</code></a> does not stop the whole program, just the single thread,
and <a href="#all_process_processabort"><code>process.abort()</code></a> is not available.</li>
<li><a href="#all_process_processchdirdirectory"><code>process.chdir()</code></a> and <code>process</code> methods that set group or user ids
are not available.</li>
<li><a href="#all_process_processenv"><code>process.env</code></a> is a copy of the parent thread's environment variables,
unless otherwise specified. Changes to one copy are not visible in other
threads, and are not visible to native add-ons (unless
<a href="#all_worker_threads_workershare_env"><code>worker.SHARE_ENV</code></a> is passed as the <code>env</code> option to the
<a href="#all_worker_threads_class-worker"><code>Worker</code></a> constructor). On Windows, unlike the main thread, a copy of the
environment variables operates in a case-sensitive manner.</li>
<li><a href="#all_process_processtitle"><code>process.title</code></a> cannot be modified.</li>
<li>Signals are not delivered through <a href="#all_process_signal-events"><code>process.on('...')</code></a>.</li>
<li>Execution may stop at any point as a result of <a href="#all_worker_threads_workerterminate"><code>worker.terminate()</code></a>
being invoked.</li>
<li>IPC channels from parent processes are not accessible.</li>
<li>The <a href="tracing.html"><code>trace_events</code></a> module is not supported.</li>
<li>Native add-ons can only be loaded from multiple threads if they fulfill
<a href="#all_addons_worker-support">certain conditions</a>.</li>
</ul>
<p>Creating <code>Worker</code> instances inside of other <code>Worker</code>s is possible.</p>
<p>Like <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Workers</a> and the <a href="cluster.html"><code>node:cluster</code> module</a>, two-way communication
can be achieved through inter-thread message passing. Internally, a <code>Worker</code> has
a built-in pair of <a href="#all_worker_threads_class-messageport"><code>MessagePort</code></a>s that are already associated with each
other when the <code>Worker</code> is created. While the <code>MessagePort</code> object on the parent
side is not directly exposed, its functionalities are exposed through
<a href="#all_worker_threads_workerpostmessagevalue-transferlist"><code>worker.postMessage()</code></a> and the <a href="#all_worker_threads_event-message_1"><code>worker.on('message')</code></a> event
on the <code>Worker</code> object for the parent thread.</p>
<p>To create custom messaging channels (which is encouraged over using the default
global channel because it facilitates separation of concerns), users can create
a <code>MessageChannel</code> object on either thread and pass one of the
<code>MessagePort</code>s on that <code>MessageChannel</code> to the other thread through a
pre-existing channel, such as the global one.</p>
<p>See <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more information on how messages are passed,
and what kind of JavaScript values can be successfully transported through
the thread barrier.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> {
<span class="hljs-title class_">Worker</span>, <span class="hljs-title class_">MessageChannel</span>, <span class="hljs-title class_">MessagePort</span>, isMainThread, parentPort,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">if</span> (isMainThread) {
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
<span class="hljs-keyword">const</span> subChannel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
worker.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">hereIsYourPort</span>: subChannel.<span class="hljs-property">port1</span> }, [subChannel.<span class="hljs-property">port1</span>]);
subChannel.<span class="hljs-property">port2</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</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>(<span class="hljs-string">'received:'</span>, value);
});
} <span class="hljs-keyword">else</span> {
parentPort.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> {
<span class="hljs-title function_">assert</span>(value.<span class="hljs-property">hereIsYourPort</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MessagePort</span>);
value.<span class="hljs-property">hereIsYourPort</span>.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'the worker is sending this'</span>);
value.<span class="hljs-property">hereIsYourPort</span>.<span class="hljs-title function_">close</span>();
});
}</code> <button class="copy-button">copy</button></pre>
<h4><code>new Worker(filename[, options])</code><span><a class="mark" href="#all_worker_threads_new-workerfilename-options" id="all_worker_threads_new-workerfilename-options">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_new_worker_filename_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.8.0</td>
<td><p>Added support for a <code>name</code> option, which allows adding a name to worker title for debugging.</p></td></tr>
<tr><td>v14.9.0</td>
<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>data:</code> protocol.</p></td></tr>
<tr><td>v14.9.0</td>
<td><p>The <code>trackUnmanagedFds</code> option was set to <code>true</code> by default.</p></td></tr>
<tr><td>v14.6.0, v12.19.0</td>
<td><p>The <code>trackUnmanagedFds</code> option was introduced.</p></td></tr>
<tr><td>v13.13.0, v12.17.0</td>
<td><p>The <code>transferList</code> option was introduced.</p></td></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v13.4.0, v12.16.0</td>
<td><p>The <code>argv</code> option was introduced.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>The <code>resourceLimits</code> option was introduced.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_url_the-whatwg-url-api" class="type"><URL></a> The path to the Worker's main script or module. Must
be either an absolute path or a relative path (i.e. relative to the
current working directory) starting with <code>./</code> or <code>../</code>, or a WHATWG <code>URL</code>
object using <code>file:</code> or <code>data:</code> protocol.
When using a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs"><code>data:</code> URL</a>, the data is interpreted based on MIME type using
the <a href="#all_esm_data-imports">ECMAScript module loader</a>.
If <code>options.eval</code> is <code>true</code>, this is a string containing JavaScript code
rather than a path.</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>argv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any[]></a> List of arguments which would be stringified and appended to
<code>process.argv</code> in the worker. This is mostly similar to the <code>workerData</code>
but the values are available on the global <code>process.argv</code> as if they
were passed as CLI options to the script.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> If set, specifies the initial value of <code>process.env</code> inside
the Worker thread. As a special value, <a href="#all_worker_threads_workershare_env"><code>worker.SHARE_ENV</code></a> may be used
to specify that the parent thread and the child thread should share their
environment variables; in that case, changes to one thread's <code>process.env</code>
object affect the other thread as well. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>eval</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code> and the first argument is a <code>string</code>, interpret
the first argument to the constructor as a script that is executed once the
worker is online.</li>
<li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of node CLI options passed to the worker.
V8 options (such as <code>--max-old-space-size</code>) and options that affect the
process (such as <code>--title</code>) are not supported. If set, this is provided
as <a href="#all_process_processexecargv"><code>process.execArgv</code></a> inside the worker. By default, options are
inherited from the parent thread.</li>
<li><code>stdin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then <code>worker.stdin</code>
provides a writable stream whose contents appear as <code>process.stdin</code>
inside the Worker. By default, no data is provided.</li>
<li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then <code>worker.stdout</code> is
not automatically piped through to <code>process.stdout</code> in the parent.</li>
<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then <code>worker.stderr</code> is
not automatically piped through to <code>process.stderr</code> in the parent.</li>
<li><code>workerData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any JavaScript value that is cloned and made
available as <a href="#all_worker_threads_workerworkerdata"><code>require('node:worker_threads').workerData</code></a>. The cloning
occurs as described in the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>, and an error
is thrown if the object cannot be cloned (e.g. because it contains
<code>function</code>s).</li>
<li><code>trackUnmanagedFds</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then the Worker
tracks raw file descriptors managed through <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a> and
<a href="#all_fs_fsclosefd-callback"><code>fs.close()</code></a>, and closes them when the Worker exits, similar to other
resources like network sockets or file descriptors managed through
the <a href="#all_fs_class-filehandle"><code>FileHandle</code></a> API. This option is automatically inherited by all
nested <code>Worker</code>s. <strong>Default:</strong> <code>true</code>.</li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> If one or more <code>MessagePort</code>-like objects
are passed in <code>workerData</code>, a <code>transferList</code> is required for those
items or <a href="#all_errors_err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a> is thrown.
See <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more information.</li>
<li><code>resourceLimits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An optional set of resource limits for the new JS
engine instance. Reaching these limits leads to termination of the <code>Worker</code>
instance. These limits only affect the JS engine, and no external data,
including no <code>ArrayBuffer</code>s. Even if these limits are set, the process may
still abort if it encounters a global out-of-memory situation.
<ul>
<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum size of the main heap in
MB. If the command-line argument <a href="#all_cli_--max-old-space-sizesize-in-mib"><code>--max-old-space-size</code></a> is set, it
overrides this setting.</li>
<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum size of a heap space for
recently created objects. If the command-line argument
<a href="#all_cli_--max-semi-space-sizesize-in-mib"><code>--max-semi-space-size</code></a> is set, it overrides this setting.</li>
<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The size of a pre-allocated memory range
used for generated code.</li>
<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The default maximum stack size for the thread.
Small values may lead to unusable Worker instances. <strong>Default:</strong> <code>4</code>.</li>
</ul>
</li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> An optional <code>name</code> to be appended to the worker title
for debugging/identification purposes, making the final title as
<code>[worker ${id}] ${name}</code>. <strong>Default:</strong> <code>''</code>.</li>
</ul>
</li>
</ul>
<h4>Event: <code>'error'</code><span><a class="mark" href="#all_worker_threads_event-error" id="all_worker_threads_event-error">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_error"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.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></li>
</ul>
<p>The <code>'error'</code> event is emitted if the worker thread throws an uncaught
exception. In that case, the worker is terminated.</p>
<h4>Event: <code>'exit'</code><span><a class="mark" href="#all_worker_threads_event-exit" id="all_worker_threads_event-exit">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_exit"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>exitCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>The <code>'exit'</code> event is emitted once the worker has stopped. If the worker
exited by calling <a href="#all_process_processexitcode"><code>process.exit()</code></a>, the <code>exitCode</code> parameter is the
passed exit code. If the worker was terminated, the <code>exitCode</code> parameter is
<code>1</code>.</p>
<p>This is the final event emitted by any <code>Worker</code> instance.</p>
<h4>Event: <code>'message'</code><span><a class="mark" href="#all_worker_threads_event-message_1" id="all_worker_threads_event-message_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_message_1"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The transmitted value</li>
</ul>
<p>The <code>'message'</code> event is emitted when the worker thread has invoked
<a href="#all_worker_threads_workerpostmessagevalue-transferlist"><code>require('node:worker_threads').parentPort.postMessage()</code></a>.
See the <a href="#all_worker_threads_event-message"><code>port.on('message')</code></a> event for more details.</p>
<p>All messages sent from the worker thread are emitted before the
<a href="#all_worker_threads_event-exit"><code>'exit'</code> event</a> is emitted on the <code>Worker</code> object.</p>
<h4>Event: <code>'messageerror'</code><span><a class="mark" href="#all_worker_threads_event-messageerror_1" id="all_worker_threads_event-messageerror_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_messageerror_1"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</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> An Error object</li>
</ul>
<p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p>
<h4>Event: <code>'online'</code><span><a class="mark" href="#all_worker_threads_event-online" id="all_worker_threads_event-online">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_online"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>The <code>'online'</code> event is emitted when the worker thread has started executing
JavaScript code.</p>
<h4><code>worker.getHeapSnapshot([options])</code><span><a class="mark" href="#all_worker_threads_workergetheapsnapshotoptions" id="all_worker_threads_workergetheapsnapshotoptions">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_getheapsnapshot_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.1.0</td>
<td><p>Support options to configure the heap snapshot.</p></td></tr>
<tr><td>v13.9.0, v12.17.0</td>
<td><p><span>Added in: v13.9.0, v12.17.0</span></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>exposeInternals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If true, expose internals in the heap snapshot.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>exposeNumericValues</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If true, expose numeric values in
artificial fields. <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> A promise for a Readable Stream containing
a V8 heap snapshot</li>
</ul>
<p>Returns a readable stream for a V8 snapshot of the current state of the Worker.
See <a href="#all_v8_v8getheapsnapshotoptions"><code>v8.getHeapSnapshot()</code></a> for more details.</p>
<p>If the Worker thread is no longer running, which may occur before the
<a href="#all_worker_threads_event-exit"><code>'exit'</code> event</a> is emitted, the returned <code>Promise</code> is rejected
immediately with an <a href="#all_errors_err_worker_not_running"><code>ERR_WORKER_NOT_RUNNING</code></a> error.</p>
<h4><code>worker.performance</code><span><a class="mark" href="#all_worker_threads_workerperformance" id="all_worker_threads_workerperformance">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_performance"></a></h4>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0, v12.22.0</span>
</div>
<p>An object that can be used to query performance information from a worker
instance. Similar to <a href="#all_perf_hooks_perf_hooksperformance"><code>perf_hooks.performance</code></a>.</p>
<h5><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code><span><a class="mark" href="#all_worker_threads_performanceeventlooputilizationutilization1-utilization2" id="all_worker_threads_performanceeventlooputilizationutilization1-utilization2">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_performance_eventlooputilization_utilization1_utilization2"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0, v12.22.0</span>
</div>
<ul>
<li><code>utilization1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The result of a previous call to
<code>eventLoopUtilization()</code>.</li>
<li><code>utilization2</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The result of a previous call to
<code>eventLoopUtilization()</code> prior to <code>utilization1</code>.</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>idle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>active</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>utilization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</li>
</ul>
<p>The same call as <a href="#all_perf_hooks_performanceeventlooputilizationutilization1-utilization2"><code>perf_hooks</code> <code>eventLoopUtilization()</code></a>, except the values
of the worker instance are returned.</p>
<p>One difference is that, unlike the main thread, bootstrapping within a worker
is done within the event loop. So the event loop utilization is
immediately available once the worker's script begins execution.</p>
<p>An <code>idle</code> time that does not increase does not indicate that the worker is
stuck in bootstrap. The following examples shows how the worker's entire
lifetime never accumulates any <code>idle</code> time, but is still be able to process
messages.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">if</span> (isMainThread) {
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
<span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
worker.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'hi'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(worker.<span class="hljs-property">performance</span>.<span class="hljs-title function_">eventLoopUtilization</span>());
}, <span class="hljs-number">100</span>).<span class="hljs-title function_">unref</span>();
<span class="hljs-keyword">return</span>;
}
parentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'msg'</span>)).<span class="hljs-title function_">unref</span>();
(<span class="hljs-keyword">function</span> <span class="hljs-title function_">r</span>(<span class="hljs-params">n</span>) {
<span class="hljs-keyword">if</span> (--n < <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span>;
<span class="hljs-keyword">const</span> t = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
<span class="hljs-keyword">while</span> (<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>() - t < <span class="hljs-number">300</span>);
<span class="hljs-title function_">setImmediate</span>(r, n);
})(<span class="hljs-number">10</span>);</code> <button class="copy-button">copy</button></pre>
<p>The event loop utilization of a worker is available only after the <a href="#all_worker_threads_event-online"><code>'online'</code>
event</a> emitted, and if called before this, or after the <a href="#all_worker_threads_event-exit"><code>'exit'</code>
event</a>, then all properties have the value of <code>0</code>.</p>
<h4><code>worker.postMessage(value[, transferList])</code><span><a class="mark" href="#all_worker_threads_workerpostmessagevalue-transferlist" id="all_worker_threads_workerpostmessagevalue-transferlist">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_postmessage_value_transferlist"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li>
</ul>
<p>Send a message to the worker that is received via
<a href="#all_worker_threads_event-message"><code>require('node:worker_threads').parentPort.on('message')</code></a>.
See <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more details.</p>
<h4><code>worker.ref()</code><span><a class="mark" href="#all_worker_threads_workerref" id="all_worker_threads_workerref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref()</code>ed worker does
<em>not</em> let the program exit if it's the only active handle left (the default
behavior). If the worker is <code>ref()</code>ed, calling <code>ref()</code> again has
no effect.</p>
<h4><code>worker.resourceLimits</code><span><a class="mark" href="#all_worker_threads_workerresourcelimits_1" id="all_worker_threads_workerresourcelimits_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_resourcelimits_1"></a></h4>
<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/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</li>
</ul>
<p>Provides the set of JS engine resource constraints for this Worker thread.
If the <code>resourceLimits</code> option was passed to the <a href="#all_worker_threads_class-worker"><code>Worker</code></a> constructor,
this matches its values.</p>
<p>If the worker has stopped, the return value is an empty object.</p>
<h4><code>worker.stderr</code><span><a class="mark" href="#all_worker_threads_workerstderr" id="all_worker_threads_workerstderr">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_stderr"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a></li>
</ul>
<p>This is a readable stream which contains data written to <a href="#all_process_processstderr"><code>process.stderr</code></a>
inside the worker thread. If <code>stderr: true</code> was not passed to the
<a href="#all_worker_threads_class-worker"><code>Worker</code></a> constructor, then data is piped to the parent thread's
<a href="#all_process_processstderr"><code>process.stderr</code></a> stream.</p>
<h4><code>worker.stdin</code><span><a class="mark" href="#all_worker_threads_workerstdin" id="all_worker_threads_workerstdin">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_stdin"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.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="#all_stream_class-streamwritable" class="type"><stream.Writable></a></li>
</ul>
<p>If <code>stdin: true</code> was passed to the <a href="#all_worker_threads_class-worker"><code>Worker</code></a> constructor, this is a
writable stream. The data written to this stream will be made available in
the worker thread as <a href="#all_process_processstdin"><code>process.stdin</code></a>.</p>
<h4><code>worker.stdout</code><span><a class="mark" href="#all_worker_threads_workerstdout" id="all_worker_threads_workerstdout">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_stdout"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="#all_stream_class-streamreadable" class="type"><stream.Readable></a></li>
</ul>
<p>This is a readable stream which contains data written to <a href="#all_process_processstdout"><code>process.stdout</code></a>
inside the worker thread. If <code>stdout: true</code> was not passed to the
<a href="#all_worker_threads_class-worker"><code>Worker</code></a> constructor, then data is piped to the parent thread's
<a href="#all_process_processstdout"><code>process.stdout</code></a> stream.</p>
<h4><code>worker.terminate()</code><span><a class="mark" href="#all_worker_threads_workerterminate" id="all_worker_threads_workerterminate">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_terminate"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.5.0</td>
<td><p>This function now returns a Promise. Passing a callback is deprecated, and was useless up to this version, as the Worker was actually terminated synchronously. Terminating is now a fully asynchronous operation.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
<p>Stop all JavaScript execution in the worker thread as soon as possible.
Returns a Promise for the exit code that is fulfilled when the
<a href="#all_worker_threads_event-exit"><code>'exit'</code> event</a> is emitted.</p>
<h4><code>worker.threadId</code><span><a class="mark" href="#all_worker_threads_workerthreadid_1" id="all_worker_threads_workerthreadid_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_threadid_1"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.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>An integer identifier for the referenced thread. Inside the worker thread,
it is available as <a href="#all_worker_threads_workerthreadid"><code>require('node:worker_threads').threadId</code></a>.
This value is unique for each <code>Worker</code> instance inside a single process.</p>
<h4><code>worker.unref()</code><span><a class="mark" href="#all_worker_threads_workerunref" id="all_worker_threads_workerunref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Calling <code>unref()</code> on a worker allows the thread to exit if this is the only
active handle in the event system. If the worker is already <code>unref()</code>ed calling
<code>unref()</code> again has no effect.</p>
</section><section><h3>Notes<span><a class="mark" href="#all_worker_threads_notes" id="all_worker_threads_notes">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_notes"></a></h3>
<h4>Synchronous blocking of stdio<span><a class="mark" href="#all_worker_threads_synchronous-blocking-of-stdio" id="all_worker_threads_synchronous-blocking-of-stdio">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_synchronous_blocking_of_stdio"></a></h4>
<p><code>Worker</code>s utilize message passing via <a href="#all_worker_threads_class-messageport" class="type"><MessagePort></a> to implement interactions
with <code>stdio</code>. This means that <code>stdio</code> output originating from a <code>Worker</code> can
get blocked by synchronous code on the receiving end that is blocking the
Node.js event loop.</p>
<pre class="with-13-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_">Worker</span>,
isMainThread,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
<span class="hljs-keyword">if</span> (isMainThread) {
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>));
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n < <span class="hljs-number">1e10</span>; n++) {
<span class="hljs-comment">// Looping to simulate work.</span>
}
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// This output will be blocked by the for loop in the main thread.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>);
}</code><code class="language-js cjs"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> {
<span class="hljs-title class_">Worker</span>,
isMainThread,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">if</span> (isMainThread) {
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n < <span class="hljs-number">1e10</span>; n++) {
<span class="hljs-comment">// Looping to simulate work.</span>
}
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// This output will be blocked by the for loop in the main thread.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>);
}</code><button class="copy-button">copy</button></pre>
<h4>Launching worker threads from preload scripts<span><a class="mark" href="#all_worker_threads_launching-worker-threads-from-preload-scripts" id="all_worker_threads_launching-worker-threads-from-preload-scripts">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_launching_worker_threads_from_preload_scripts"></a></h4>
<p>Take care when launching worker threads from preload scripts (scripts loaded
and run using the <code>-r</code> command line flag). Unless the <code>execArgv</code> option is
explicitly set, new Worker threads automatically inherit the command line flags
from the running process and will preload the same preload scripts as the main
thread. If the preload script unconditionally launches a worker thread, every
thread spawned will spawn another until the application crashes.</p></section>
</section>
<section><h2>Zlib<span><a class="mark" href="#all_zlib_zlib" id="all_zlib_zlib">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.19.2/lib/zlib.js">lib/zlib.js</a></p>
<p>The <code>node:zlib</code> module provides compression functionality implemented using
Gzip, Deflate/Inflate, and Brotli.</p>
<p>To access it:</p>
<pre class="with-34-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> os <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);</code><button class="copy-button">copy</button></pre>
<p>Compression and decompression are built around the Node.js <a href="stream.html">Streams API</a>.</p>
<p>Compressing or decompressing a stream (such as a file) can be accomplished by
piping the source stream through a <code>zlib</code> <code>Transform</code> stream into a destination
stream:</p>
<pre class="with-19-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> {
createReadStream,
createWriteStream,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</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">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">const</span> gzip = <span class="hljs-title function_">createGzip</span>();
<span class="hljs-keyword">const</span> source = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'input.txt'</span>);
<span class="hljs-keyword">const</span> destination = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'input.txt.gz'</span>);
<span class="hljs-title function_">pipeline</span>(source, gzip, destination, <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">'An error occurred:'</span>, err);
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createReadStream,
createWriteStream,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> { createGzip } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</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> gzip = <span class="hljs-title function_">createGzip</span>();
<span class="hljs-keyword">const</span> source = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'input.txt'</span>);
<span class="hljs-keyword">const</span> destination = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'input.txt.gz'</span>);
<span class="hljs-title function_">pipeline</span>(source, gzip, destination, <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">'An error occurred:'</span>, err);
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}
});</code><button class="copy-button">copy</button></pre>
<p>Or, using the promise <code>pipeline</code> API:</p>
<pre class="with-19-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> {
createReadStream,
createWriteStream,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</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">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">do_gzip</span>(<span class="hljs-params">input, output</span>) {
<span class="hljs-keyword">const</span> gzip = <span class="hljs-title function_">createGzip</span>();
<span class="hljs-keyword">const</span> source = <span class="hljs-title function_">createReadStream</span>(input);
<span class="hljs-keyword">const</span> destination = <span class="hljs-title function_">createWriteStream</span>(output);
<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(source, gzip, destination);
}
<span class="hljs-keyword">await</span> <span class="hljs-title function_">do_gzip</span>(<span class="hljs-string">'input.txt'</span>, <span class="hljs-string">'input.txt.gz'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
createReadStream,
createWriteStream,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> { createGzip } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<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">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">do_gzip</span>(<span class="hljs-params">input, output</span>) {
<span class="hljs-keyword">const</span> gzip = <span class="hljs-title function_">createGzip</span>();
<span class="hljs-keyword">const</span> source = <span class="hljs-title function_">createReadStream</span>(input);
<span class="hljs-keyword">const</span> destination = <span class="hljs-title function_">createWriteStream</span>(output);
<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(source, gzip, destination);
}
<span class="hljs-title function_">do_gzip</span>(<span class="hljs-string">'input.txt'</span>, <span class="hljs-string">'input.txt.gz'</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>(<span class="hljs-string">'An error occurred:'</span>, err);
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
});</code><button class="copy-button">copy</button></pre>
<p>It is also possible to compress or decompress data in a single step:</p>
<pre class="with-48-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> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">import</span> { deflate, unzip } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>;
<span class="hljs-keyword">const</span> input = <span class="hljs-string">'.................................'</span>;
<span class="hljs-title function_">deflate</span>(input, <span class="hljs-function">(<span class="hljs-params">err, buffer</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">'An error occurred:'</span>, err);
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buffer.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'base64'</span>));
});
<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'eJzT0yMAAGTvBe8='</span>, <span class="hljs-string">'base64'</span>);
<span class="hljs-title function_">unzip</span>(buffer, <span class="hljs-function">(<span class="hljs-params">err, buffer</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">'An error occurred:'</span>, err);
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buffer.<span class="hljs-title function_">toString</span>());
});
<span class="hljs-comment">// Or, Promisified</span>
<span class="hljs-keyword">import</span> { promisify } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> do_unzip = <span class="hljs-title function_">promisify</span>(unzip);
<span class="hljs-keyword">const</span> unzippedBuffer = <span class="hljs-keyword">await</span> <span class="hljs-title function_">do_unzip</span>(buffer);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(unzippedBuffer.<span class="hljs-title function_">toString</span>());</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { deflate, unzip } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<span class="hljs-keyword">const</span> input = <span class="hljs-string">'.................................'</span>;
<span class="hljs-title function_">deflate</span>(input, <span class="hljs-function">(<span class="hljs-params">err, buffer</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">'An error occurred:'</span>, err);
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buffer.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'base64'</span>));
});
<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'eJzT0yMAAGTvBe8='</span>, <span class="hljs-string">'base64'</span>);
<span class="hljs-title function_">unzip</span>(buffer, <span class="hljs-function">(<span class="hljs-params">err, buffer</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">'An error occurred:'</span>, err);
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buffer.<span class="hljs-title function_">toString</span>());
});
<span class="hljs-comment">// Or, Promisified</span>
<span class="hljs-keyword">const</span> { promisify } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> do_unzip = <span class="hljs-title function_">promisify</span>(unzip);
<span class="hljs-title function_">do_unzip</span>(buffer)
.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">buf</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</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>(<span class="hljs-string">'An error occurred:'</span>, err);
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
});</code><button class="copy-button">copy</button></pre>
<section><h3>Threadpool usage and performance considerations<span><a class="mark" href="#all_zlib_threadpool-usage-and-performance-considerations" id="all_zlib_threadpool-usage-and-performance-considerations">#</a></span><a aria-hidden="true" class="legacy" id="zlib_threadpool_usage_and_performance_considerations"></a></h3>
<p>All <code>zlib</code> APIs, except those that are explicitly synchronous, use the Node.js
internal threadpool. This can lead to surprising effects and performance
limitations in some applications.</p>
<p>Creating and using a large number of zlib objects simultaneously can cause
significant memory fragmentation.</p>
<pre class="with-37-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> zlib <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> payload = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'This is some data'</span>);
<span class="hljs-comment">// WARNING: DO NOT DO THIS!</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">30000</span>; ++i) {
zlib.<span class="hljs-title function_">deflate</span>(payload, <span class="hljs-function">(<span class="hljs-params">err, buffer</span>) =></span> {});
}</code><code class="language-js cjs"><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> payload = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'This is some data'</span>);
<span class="hljs-comment">// WARNING: DO NOT DO THIS!</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">30000</span>; ++i) {
zlib.<span class="hljs-title function_">deflate</span>(payload, <span class="hljs-function">(<span class="hljs-params">err, buffer</span>) =></span> {});
}</code><button class="copy-button">copy</button></pre>
<p>In the preceding example, 30,000 deflate instances are created concurrently.
Because of how some operating systems handle memory allocation and
deallocation, this may lead to significant memory fragmentation.</p>
<p>It is strongly recommended that the results of compression
operations be cached to avoid duplication of effort.</p>
</section><section><h3>Compressing HTTP requests and responses<span><a class="mark" href="#all_zlib_compressing-http-requests-and-responses" id="all_zlib_compressing-http-requests-and-responses">#</a></span><a aria-hidden="true" class="legacy" id="zlib_compressing_http_requests_and_responses"></a></h3>
<p>The <code>node:zlib</code> module can be used to implement support for the <code>gzip</code>, <code>deflate</code>
and <code>br</code> content-encoding mechanisms defined by
<a href="https://tools.ietf.org/html/rfc7230#section-4.2">HTTP</a>.</p>
<p>The HTTP <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3"><code>Accept-Encoding</code></a> header is used within an HTTP request to identify
the compression encodings accepted by the client. The <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11"><code>Content-Encoding</code></a>
header is used to identify the compression encodings actually applied to a
message.</p>
<p>The examples given below are drastically simplified to show the basic concept.
Using <code>zlib</code> encoding can be expensive, and the results ought to be cached.
See <a href="#all_zlib_memory-usage-tuning">Memory usage tuning</a> for more information on the speed/memory/compression
tradeoffs involved in <code>zlib</code> usage.</p>
<pre class="with-34-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// Client request example</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">import</span> zlib <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>;
<span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">const</span> request = http.<span class="hljs-title function_">get</span>({ <span class="hljs-attr">host</span>: <span class="hljs-string">'example.com'</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
<span class="hljs-attr">headers</span>: { <span class="hljs-string">'Accept-Encoding'</span>: <span class="hljs-string">'br,gzip,deflate'</span> } });
request.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">response</span>) =></span> {
<span class="hljs-keyword">const</span> output = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'example.com_index.html'</span>);
<span class="hljs-keyword">const</span> <span class="hljs-title function_">onError</span> = (<span class="hljs-params">err</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">'An error occurred:'</span>, err);
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}
};
<span class="hljs-keyword">switch</span> (response.<span class="hljs-property">headers</span>[<span class="hljs-string">'content-encoding'</span>]) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'br'</span>:
<span class="hljs-title function_">pipeline</span>(response, zlib.<span class="hljs-title function_">createBrotliDecompress</span>(), output, onError);
<span class="hljs-keyword">break</span>;
<span class="hljs-comment">// Or, just use zlib.createUnzip() to handle both of the following cases:</span>
<span class="hljs-keyword">case</span> <span class="hljs-string">'gzip'</span>:
<span class="hljs-title function_">pipeline</span>(response, zlib.<span class="hljs-title function_">createGunzip</span>(), output, onError);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'deflate'</span>:
<span class="hljs-title function_">pipeline</span>(response, zlib.<span class="hljs-title function_">createInflate</span>(), output, onError);
<span class="hljs-keyword">break</span>;
<span class="hljs-attr">default</span>:
<span class="hljs-title function_">pipeline</span>(response, output, onError);
<span class="hljs-keyword">break</span>;
}
});</code><code class="language-js cjs"><span class="hljs-comment">// Client request example</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> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</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> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> request = http.<span class="hljs-title function_">get</span>({ <span class="hljs-attr">host</span>: <span class="hljs-string">'example.com'</span>,
<span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
<span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
<span class="hljs-attr">headers</span>: { <span class="hljs-string">'Accept-Encoding'</span>: <span class="hljs-string">'br,gzip,deflate'</span> } });
request.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">response</span>) =></span> {
<span class="hljs-keyword">const</span> output = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'example.com_index.html'</span>);
<span class="hljs-keyword">const</span> <span class="hljs-title function_">onError</span> = (<span class="hljs-params">err</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">'An error occurred:'</span>, err);
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}
};
<span class="hljs-keyword">switch</span> (response.<span class="hljs-property">headers</span>[<span class="hljs-string">'content-encoding'</span>]) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'br'</span>:
<span class="hljs-title function_">pipeline</span>(response, zlib.<span class="hljs-title function_">createBrotliDecompress</span>(), output, onError);
<span class="hljs-keyword">break</span>;
<span class="hljs-comment">// Or, just use zlib.createUnzip() to handle both of the following cases:</span>
<span class="hljs-keyword">case</span> <span class="hljs-string">'gzip'</span>:
<span class="hljs-title function_">pipeline</span>(response, zlib.<span class="hljs-title function_">createGunzip</span>(), output, onError);
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> <span class="hljs-string">'deflate'</span>:
<span class="hljs-title function_">pipeline</span>(response, zlib.<span class="hljs-title function_">createInflate</span>(), output, onError);
<span class="hljs-keyword">break</span>;
<span class="hljs-attr">default</span>:
<span class="hljs-title function_">pipeline</span>(response, output, onError);
<span class="hljs-keyword">break</span>;
}
});</code><button class="copy-button">copy</button></pre>
<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// server example</span>
<span class="hljs-comment">// Running a gzip operation on every request is quite expensive.</span>
<span class="hljs-comment">// It would be much more efficient to cache the compressed buffer.</span>
<span class="hljs-keyword">import</span> zlib <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>;
<span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</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">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">request, response</span>) =></span> {
<span class="hljs-keyword">const</span> raw = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'index.html'</span>);
<span class="hljs-comment">// Store both a compressed and an uncompressed version of the resource.</span>
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Vary'</span>, <span class="hljs-string">'Accept-Encoding'</span>);
<span class="hljs-keyword">const</span> acceptEncoding = request.<span class="hljs-property">headers</span>[<span class="hljs-string">'accept-encoding'</span>] || <span class="hljs-string">''</span>;
<span class="hljs-keyword">const</span> <span class="hljs-title function_">onError</span> = (<span class="hljs-params">err</span>) => {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-comment">// If an error occurs, there's not much we can do because</span>
<span class="hljs-comment">// the server has already sent the 200 response code and</span>
<span class="hljs-comment">// some amount of data has already been sent to the client.</span>
<span class="hljs-comment">// The best we can do is terminate the response immediately</span>
<span class="hljs-comment">// and log the error.</span>
response.<span class="hljs-title function_">end</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
}
};
<span class="hljs-comment">// Note: This is not a conformant accept-encoding parser.</span>
<span class="hljs-comment">// See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3</span>
<span class="hljs-keyword">if</span> (<span class="hljs-regexp">/\bdeflate\b/</span>.<span class="hljs-title function_">test</span>(acceptEncoding)) {
response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Encoding'</span>: <span class="hljs-string">'deflate'</span> });
<span class="hljs-title function_">pipeline</span>(raw, zlib.<span class="hljs-title function_">createDeflate</span>(), response, onError);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/\bgzip\b/</span>.<span class="hljs-title function_">test</span>(acceptEncoding)) {
response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Encoding'</span>: <span class="hljs-string">'gzip'</span> });
<span class="hljs-title function_">pipeline</span>(raw, zlib.<span class="hljs-title function_">createGzip</span>(), response, onError);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/\bbr\b/</span>.<span class="hljs-title function_">test</span>(acceptEncoding)) {
response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Encoding'</span>: <span class="hljs-string">'br'</span> });
<span class="hljs-title function_">pipeline</span>(raw, zlib.<span class="hljs-title function_">createBrotliCompress</span>(), response, onError);
} <span class="hljs-keyword">else</span> {
response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, {});
<span class="hljs-title function_">pipeline</span>(raw, response, onError);
}
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code><code class="language-js cjs"><span class="hljs-comment">// server example</span>
<span class="hljs-comment">// Running a gzip operation on every request is quite expensive.</span>
<span class="hljs-comment">// It would be much more efficient to cache the compressed buffer.</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> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</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> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">request, response</span>) =></span> {
<span class="hljs-keyword">const</span> raw = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'index.html'</span>);
<span class="hljs-comment">// Store both a compressed and an uncompressed version of the resource.</span>
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Vary'</span>, <span class="hljs-string">'Accept-Encoding'</span>);
<span class="hljs-keyword">let</span> acceptEncoding = request.<span class="hljs-property">headers</span>[<span class="hljs-string">'accept-encoding'</span>];
<span class="hljs-keyword">if</span> (!acceptEncoding) {
acceptEncoding = <span class="hljs-string">''</span>;
}
<span class="hljs-keyword">const</span> <span class="hljs-title function_">onError</span> = (<span class="hljs-params">err</span>) => {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-comment">// If an error occurs, there's not much we can do because</span>
<span class="hljs-comment">// the server has already sent the 200 response code and</span>
<span class="hljs-comment">// some amount of data has already been sent to the client.</span>
<span class="hljs-comment">// The best we can do is terminate the response immediately</span>
<span class="hljs-comment">// and log the error.</span>
response.<span class="hljs-title function_">end</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
}
};
<span class="hljs-comment">// Note: This is not a conformant accept-encoding parser.</span>
<span class="hljs-comment">// See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3</span>
<span class="hljs-keyword">if</span> (<span class="hljs-regexp">/\bdeflate\b/</span>.<span class="hljs-title function_">test</span>(acceptEncoding)) {
response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Encoding'</span>: <span class="hljs-string">'deflate'</span> });
<span class="hljs-title function_">pipeline</span>(raw, zlib.<span class="hljs-title function_">createDeflate</span>(), response, onError);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/\bgzip\b/</span>.<span class="hljs-title function_">test</span>(acceptEncoding)) {
response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Encoding'</span>: <span class="hljs-string">'gzip'</span> });
<span class="hljs-title function_">pipeline</span>(raw, zlib.<span class="hljs-title function_">createGzip</span>(), response, onError);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/\bbr\b/</span>.<span class="hljs-title function_">test</span>(acceptEncoding)) {
response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Encoding'</span>: <span class="hljs-string">'br'</span> });
<span class="hljs-title function_">pipeline</span>(raw, zlib.<span class="hljs-title function_">createBrotliCompress</span>(), response, onError);
} <span class="hljs-keyword">else</span> {
response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, {});
<span class="hljs-title function_">pipeline</span>(raw, response, onError);
}
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code><button class="copy-button">copy</button></pre>
<p>By default, the <code>zlib</code> methods will throw an error when decompressing
truncated data. However, if it is known that the data is incomplete, or
the desire is to inspect only the beginning of a compressed file, it is
possible to suppress the default error handling by changing the flushing
method that is used to decompress the last chunk of input data:</p>
<pre><code class="language-js"><span class="hljs-comment">// This is a truncated version of the buffer from the above examples</span>
<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'eJzT0yMA'</span>, <span class="hljs-string">'base64'</span>);
zlib.<span class="hljs-title function_">unzip</span>(
buffer,
<span class="hljs-comment">// For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH.</span>
{ <span class="hljs-attr">finishFlush</span>: zlib.<span class="hljs-property">constants</span>.<span class="hljs-property">Z_SYNC_FLUSH</span> },
<span class="hljs-function">(<span class="hljs-params">err, buffer</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">'An error occurred:'</span>, err);
process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buffer.<span class="hljs-title function_">toString</span>());
});</code> <button class="copy-button">copy</button></pre>
<p>This will not change the behavior in other error-throwing situations, e.g.
when the input data has an invalid format. Using this method, it will not be
possible to determine whether the input ended prematurely or lacks the
integrity checks, making it necessary to manually check that the
decompressed result is valid.</p>
</section><section><h3>Memory usage tuning<span><a class="mark" href="#all_zlib_memory-usage-tuning" id="all_zlib_memory-usage-tuning">#</a></span><a aria-hidden="true" class="legacy" id="zlib_memory_usage_tuning"></a></h3>
<h4>For zlib-based streams<span><a class="mark" href="#all_zlib_for-zlib-based-streams" id="all_zlib_for-zlib-based-streams">#</a></span><a aria-hidden="true" class="legacy" id="zlib_for_zlib_based_streams"></a></h4>
<p>From <code>zlib/zconf.h</code>, modified for Node.js usage:</p>
<p>The memory requirements for deflate are (in bytes):</p>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js">(<span class="hljs-number">1</span> << (windowBits + <span class="hljs-number">2</span>)) + (<span class="hljs-number">1</span> << (memLevel + <span class="hljs-number">9</span>))</code> <button class="copy-button">copy</button></pre>
<p>That is: 128K for <code>windowBits</code> = 15 + 128K for <code>memLevel</code> = 8
(default values) plus a few kilobytes for small objects.</p>
<p>For example, to reduce the default memory requirements from 256K to 128K, the
options should be set to:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> options = { <span class="hljs-attr">windowBits</span>: <span class="hljs-number">14</span>, <span class="hljs-attr">memLevel</span>: <span class="hljs-number">7</span> };</code> <button class="copy-button">copy</button></pre>
<p>This will, however, generally degrade compression.</p>
<p>The memory requirements for inflate are (in bytes) <code>1 << windowBits</code>.
That is, 32K for <code>windowBits</code> = 15 (default value) plus a few kilobytes
for small objects.</p>
<p>This is in addition to a single internal output slab buffer of size
<code>chunkSize</code>, which defaults to 16K.</p>
<p>The speed of <code>zlib</code> compression is affected most dramatically by the
<code>level</code> setting. A higher level will result in better compression, but
will take longer to complete. A lower level will result in less
compression, but will be much faster.</p>
<p>In general, greater memory usage options will mean that Node.js has to make
fewer calls to <code>zlib</code> because it will be able to process more data on
each <code>write</code> operation. So, this is another factor that affects the
speed, at the cost of memory usage.</p>
<h4>For Brotli-based streams<span><a class="mark" href="#all_zlib_for-brotli-based-streams" id="all_zlib_for-brotli-based-streams">#</a></span><a aria-hidden="true" class="legacy" id="zlib_for_brotli_based_streams"></a></h4>
<p>There are equivalents to the zlib options for Brotli-based streams, although
these options have different ranges than the zlib ones:</p>
<ul>
<li>zlib's <code>level</code> option matches Brotli's <code>BROTLI_PARAM_QUALITY</code> option.</li>
<li>zlib's <code>windowBits</code> option matches Brotli's <code>BROTLI_PARAM_LGWIN</code> option.</li>
</ul>
<p>See <a href="#all_zlib_brotli-constants">below</a> for more details on Brotli-specific options.</p>
</section><section><h3>Flushing<span><a class="mark" href="#all_zlib_flushing" id="all_zlib_flushing">#</a></span><a aria-hidden="true" class="legacy" id="zlib_flushing"></a></h3>
<p>Calling <a href="#all_zlib_zlibflushkind-callback"><code>.flush()</code></a> on a compression stream will make <code>zlib</code> return as much
output as currently possible. This may come at the cost of degraded compression
quality, but can be useful when data needs to be available as soon as possible.</p>
<p>In the following example, <code>flush()</code> is used to write a compressed partial
HTTP response to the client:</p>
<pre class="with-34-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> zlib <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>;
<span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">request, response</span>) =></span> {
<span class="hljs-comment">// For the sake of simplicity, the Accept-Encoding checks are omitted.</span>
response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'content-encoding'</span>: <span class="hljs-string">'gzip'</span> });
<span class="hljs-keyword">const</span> output = zlib.<span class="hljs-title function_">createGzip</span>();
<span class="hljs-keyword">let</span> i;
<span class="hljs-title function_">pipeline</span>(output, response, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-comment">// If an error occurs, there's not much we can do because</span>
<span class="hljs-comment">// the server has already sent the 200 response code and</span>
<span class="hljs-comment">// some amount of data has already been sent to the client.</span>
<span class="hljs-comment">// The best we can do is terminate the response immediately</span>
<span class="hljs-comment">// and log the error.</span>
<span class="hljs-built_in">clearInterval</span>(i);
response.<span class="hljs-title function_">end</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
}
});
i = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
output.<span class="hljs-title function_">write</span>(<span class="hljs-string">`The current time is <span class="hljs-subst">${<span class="hljs-built_in">Date</span>()}</span>\n`</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// The data has been passed to zlib, but the compression algorithm may</span>
<span class="hljs-comment">// have decided to buffer the data for more efficient compression.</span>
<span class="hljs-comment">// Calling .flush() will make the data available as soon as the client</span>
<span class="hljs-comment">// is ready to receive it.</span>
output.<span class="hljs-title function_">flush</span>();
});
}, <span class="hljs-number">1000</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code><code class="language-js cjs"><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> 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>);
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">request, response</span>) =></span> {
<span class="hljs-comment">// For the sake of simplicity, the Accept-Encoding checks are omitted.</span>
response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'content-encoding'</span>: <span class="hljs-string">'gzip'</span> });
<span class="hljs-keyword">const</span> output = zlib.<span class="hljs-title function_">createGzip</span>();
<span class="hljs-keyword">let</span> i;
<span class="hljs-title function_">pipeline</span>(output, response, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-comment">// If an error occurs, there's not much we can do because</span>
<span class="hljs-comment">// the server has already sent the 200 response code and</span>
<span class="hljs-comment">// some amount of data has already been sent to the client.</span>
<span class="hljs-comment">// The best we can do is terminate the response immediately</span>
<span class="hljs-comment">// and log the error.</span>
<span class="hljs-built_in">clearInterval</span>(i);
response.<span class="hljs-title function_">end</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
}
});
i = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
output.<span class="hljs-title function_">write</span>(<span class="hljs-string">`The current time is <span class="hljs-subst">${<span class="hljs-built_in">Date</span>()}</span>\n`</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// The data has been passed to zlib, but the compression algorithm may</span>
<span class="hljs-comment">// have decided to buffer the data for more efficient compression.</span>
<span class="hljs-comment">// Calling .flush() will make the data available as soon as the client</span>
<span class="hljs-comment">// is ready to receive it.</span>
output.<span class="hljs-title function_">flush</span>();
});
}, <span class="hljs-number">1000</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Constants<span><a class="mark" href="#all_zlib_constants" id="all_zlib_constants">#</a></span><a aria-hidden="true" class="legacy" id="zlib_constants"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<h4>zlib constants<span><a class="mark" href="#all_zlib_zlib-constants" id="all_zlib_zlib-constants">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_constants"></a></h4>
<p>All of the constants defined in <code>zlib.h</code> are also defined on
<code>require('node:zlib').constants</code>. In the normal course of operations, it will
not be necessary to use these constants. They are documented so that their
presence is not surprising. This section is taken almost directly from the
<a href="https://zlib.net/manual.html#Constants">zlib documentation</a>.</p>
<p>Previously, the constants were available directly from <code>require('node:zlib')</code>,
for instance <code>zlib.Z_NO_FLUSH</code>. Accessing the constants directly from the module
is currently still possible but is deprecated.</p>
<p>Allowed flush values.</p>
<ul>
<li><code>zlib.constants.Z_NO_FLUSH</code></li>
<li><code>zlib.constants.Z_PARTIAL_FLUSH</code></li>
<li><code>zlib.constants.Z_SYNC_FLUSH</code></li>
<li><code>zlib.constants.Z_FULL_FLUSH</code></li>
<li><code>zlib.constants.Z_FINISH</code></li>
<li><code>zlib.constants.Z_BLOCK</code></li>
<li><code>zlib.constants.Z_TREES</code></li>
</ul>
<p>Return codes for the compression/decompression functions. Negative
values are errors, positive values are used for special but normal
events.</p>
<ul>
<li><code>zlib.constants.Z_OK</code></li>
<li><code>zlib.constants.Z_STREAM_END</code></li>
<li><code>zlib.constants.Z_NEED_DICT</code></li>
<li><code>zlib.constants.Z_ERRNO</code></li>
<li><code>zlib.constants.Z_STREAM_ERROR</code></li>
<li><code>zlib.constants.Z_DATA_ERROR</code></li>
<li><code>zlib.constants.Z_MEM_ERROR</code></li>
<li><code>zlib.constants.Z_BUF_ERROR</code></li>
<li><code>zlib.constants.Z_VERSION_ERROR</code></li>
</ul>
<p>Compression levels.</p>
<ul>
<li><code>zlib.constants.Z_NO_COMPRESSION</code></li>
<li><code>zlib.constants.Z_BEST_SPEED</code></li>
<li><code>zlib.constants.Z_BEST_COMPRESSION</code></li>
<li><code>zlib.constants.Z_DEFAULT_COMPRESSION</code></li>
</ul>
<p>Compression strategy.</p>
<ul>
<li><code>zlib.constants.Z_FILTERED</code></li>
<li><code>zlib.constants.Z_HUFFMAN_ONLY</code></li>
<li><code>zlib.constants.Z_RLE</code></li>
<li><code>zlib.constants.Z_FIXED</code></li>
<li><code>zlib.constants.Z_DEFAULT_STRATEGY</code></li>
</ul>
<h4>Brotli constants<span><a class="mark" href="#all_zlib_brotli-constants" id="all_zlib_brotli-constants">#</a></span><a aria-hidden="true" class="legacy" id="zlib_brotli_constants"></a></h4>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<p>There are several options and other constants available for Brotli-based
streams:</p>
<h5>Flush operations<span><a class="mark" href="#all_zlib_flush-operations" id="all_zlib_flush-operations">#</a></span><a aria-hidden="true" class="legacy" id="zlib_flush_operations"></a></h5>
<p>The following values are valid flush operations for Brotli-based streams:</p>
<ul>
<li><code>zlib.constants.BROTLI_OPERATION_PROCESS</code> (default for all operations)</li>
<li><code>zlib.constants.BROTLI_OPERATION_FLUSH</code> (default when calling <code>.flush()</code>)</li>
<li><code>zlib.constants.BROTLI_OPERATION_FINISH</code> (default for the last chunk)</li>
<li><code>zlib.constants.BROTLI_OPERATION_EMIT_METADATA</code>
<ul>
<li>This particular operation may be hard to use in a Node.js context,
as the streaming layer makes it hard to know which data will end up
in this frame. Also, there is currently no way to consume this data through
the Node.js API.</li>
</ul>
</li>
</ul>
<h5>Compressor options<span><a class="mark" href="#all_zlib_compressor-options" id="all_zlib_compressor-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_compressor_options"></a></h5>
<p>There are several options that can be set on Brotli encoders, affecting
compression efficiency and speed. Both the keys and the values can be accessed
as properties of the <code>zlib.constants</code> object.</p>
<p>The most important options are:</p>
<ul>
<li><code>BROTLI_PARAM_MODE</code>
<ul>
<li><code>BROTLI_MODE_GENERIC</code> (default)</li>
<li><code>BROTLI_MODE_TEXT</code>, adjusted for UTF-8 text</li>
<li><code>BROTLI_MODE_FONT</code>, adjusted for WOFF 2.0 fonts</li>
</ul>
</li>
<li><code>BROTLI_PARAM_QUALITY</code>
<ul>
<li>Ranges from <code>BROTLI_MIN_QUALITY</code> to <code>BROTLI_MAX_QUALITY</code>,
with a default of <code>BROTLI_DEFAULT_QUALITY</code>.</li>
</ul>
</li>
<li><code>BROTLI_PARAM_SIZE_HINT</code>
<ul>
<li>Integer value representing the expected input size;
defaults to <code>0</code> for an unknown input size.</li>
</ul>
</li>
</ul>
<p>The following flags can be set for advanced control over the compression
algorithm and memory usage tuning:</p>
<ul>
<li><code>BROTLI_PARAM_LGWIN</code>
<ul>
<li>Ranges from <code>BROTLI_MIN_WINDOW_BITS</code> to <code>BROTLI_MAX_WINDOW_BITS</code>,
with a default of <code>BROTLI_DEFAULT_WINDOW</code>, or up to
<code>BROTLI_LARGE_MAX_WINDOW_BITS</code> if the <code>BROTLI_PARAM_LARGE_WINDOW</code> flag
is set.</li>
</ul>
</li>
<li><code>BROTLI_PARAM_LGBLOCK</code>
<ul>
<li>Ranges from <code>BROTLI_MIN_INPUT_BLOCK_BITS</code> to <code>BROTLI_MAX_INPUT_BLOCK_BITS</code>.</li>
</ul>
</li>
<li><code>BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING</code>
<ul>
<li>Boolean flag that decreases compression ratio in favour of
decompression speed.</li>
</ul>
</li>
<li><code>BROTLI_PARAM_LARGE_WINDOW</code>
<ul>
<li>Boolean flag enabling “Large Window Brotli” mode (not compatible with the
Brotli format as standardized in <a href="https://www.rfc-editor.org/rfc/rfc7932.txt">RFC 7932</a>).</li>
</ul>
</li>
<li><code>BROTLI_PARAM_NPOSTFIX</code>
<ul>
<li>Ranges from <code>0</code> to <code>BROTLI_MAX_NPOSTFIX</code>.</li>
</ul>
</li>
<li><code>BROTLI_PARAM_NDIRECT</code>
<ul>
<li>Ranges from <code>0</code> to <code>15 << NPOSTFIX</code> in steps of <code>1 << NPOSTFIX</code>.</li>
</ul>
</li>
</ul>
<h5>Decompressor options<span><a class="mark" href="#all_zlib_decompressor-options" id="all_zlib_decompressor-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_decompressor_options"></a></h5>
<p>These advanced options are available for controlling decompression:</p>
<ul>
<li><code>BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION</code>
<ul>
<li>Boolean flag that affects internal memory allocation patterns.</li>
</ul>
</li>
<li><code>BROTLI_DECODER_PARAM_LARGE_WINDOW</code>
<ul>
<li>Boolean flag enabling “Large Window Brotli” mode (not compatible with the
Brotli format as standardized in <a href="https://www.rfc-editor.org/rfc/rfc7932.txt">RFC 7932</a>).</li>
</ul>
</li>
</ul>
</section><section><h3>Class: <code>Options</code><span><a class="mark" href="#all_zlib_class-options" id="all_zlib_class-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>The <code>maxOutputLength</code> option is supported now.</p></td></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>dictionary</code> option can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>dictionary</code> option can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v5.11.0</td>
<td><p>The <code>finishFlush</code> option is supported now.</p></td></tr>
<tr><td>v0.11.1</td>
<td><p><span>Added in: v0.11.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Each zlib-based class takes an <code>options</code> object. No options are required.</p>
<p>Some options are only relevant when compressing and are
ignored by the decompression classes.</p>
<ul>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>zlib.constants.Z_NO_FLUSH</code></li>
<li><code>finishFlush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>zlib.constants.Z_FINISH</code></li>
<li><code>chunkSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>16 * 1024</code></li>
<li><code>windowBits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>level</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> (compression only)</li>
<li><code>memLevel</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> (compression only)</li>
<li><code>strategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> (compression only)</li>
<li><code>dictionary</code> <a href="#all_buffer_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/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> (deflate/inflate only,
empty dictionary by default)</li>
<li><code>info</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> (If <code>true</code>, returns an object with <code>buffer</code> and <code>engine</code>.)</li>
<li><code>maxOutputLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Limits output size when using
<a href="#all_zlib_convenience-methods">convenience methods</a>. <strong>Default:</strong> <a href="#all_buffer_bufferkmaxlength"><code>buffer.kMaxLength</code></a></li>
</ul>
<p>See the <a href="https://zlib.net/manual.html#Advanced"><code>deflateInit2</code> and <code>inflateInit2</code></a> documentation for more
information.</p>
</section><section><h3>Class: <code>BrotliOptions</code><span><a class="mark" href="#all_zlib_class-brotlioptions" id="all_zlib_class-brotlioptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_brotlioptions"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>The <code>maxOutputLength</code> option is supported now.</p></td></tr>
<tr><td>v11.7.0</td>
<td><p><span>Added in: v11.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Each Brotli-based class takes an <code>options</code> object. All options are optional.</p>
<ul>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>zlib.constants.BROTLI_OPERATION_PROCESS</code></li>
<li><code>finishFlush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>zlib.constants.BROTLI_OPERATION_FINISH</code></li>
<li><code>chunkSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>16 * 1024</code></li>
<li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Key-value object containing indexed <a href="#all_zlib_brotli-constants">Brotli parameters</a>.</li>
<li><code>maxOutputLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Limits output size when using
<a href="#all_zlib_convenience-methods">convenience methods</a>. <strong>Default:</strong> <a href="#all_buffer_bufferkmaxlength"><code>buffer.kMaxLength</code></a></li>
</ul>
<p>For example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = zlib.<span class="hljs-title function_">createBrotliCompress</span>({
<span class="hljs-attr">chunkSize</span>: <span class="hljs-number">32</span> * <span class="hljs-number">1024</span>,
<span class="hljs-attr">params</span>: {
[zlib.<span class="hljs-property">constants</span>.<span class="hljs-property">BROTLI_PARAM_MODE</span>]: zlib.<span class="hljs-property">constants</span>.<span class="hljs-property">BROTLI_MODE_TEXT</span>,
[zlib.<span class="hljs-property">constants</span>.<span class="hljs-property">BROTLI_PARAM_QUALITY</span>]: <span class="hljs-number">4</span>,
[zlib.<span class="hljs-property">constants</span>.<span class="hljs-property">BROTLI_PARAM_SIZE_HINT</span>]: fs.<span class="hljs-title function_">statSync</span>(inputFile).<span class="hljs-property">size</span>,
},
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>zlib.BrotliCompress</code><span><a class="mark" href="#all_zlib_class-zlibbrotlicompress" id="all_zlib_class-zlibbrotlicompress">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_brotlicompress"></a></h3>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<p>Compress data using the Brotli algorithm.</p>
</section><section><h3>Class: <code>zlib.BrotliDecompress</code><span><a class="mark" href="#all_zlib_class-zlibbrotlidecompress" id="all_zlib_class-zlibbrotlidecompress">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_brotlidecompress"></a></h3>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<p>Decompress data using the Brotli algorithm.</p>
</section><section><h3>Class: <code>zlib.Deflate</code><span><a class="mark" href="#all_zlib_class-zlibdeflate" id="all_zlib_class-zlibdeflate">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_deflate"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<p>Compress data using deflate.</p>
</section><section><h3>Class: <code>zlib.DeflateRaw</code><span><a class="mark" href="#all_zlib_class-zlibdeflateraw" id="all_zlib_class-zlibdeflateraw">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_deflateraw"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<p>Compress data using deflate, and do not append a <code>zlib</code> header.</p>
</section><section><h3>Class: <code>zlib.Gunzip</code><span><a class="mark" href="#all_zlib_class-zlibgunzip" id="all_zlib_class-zlibgunzip">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_gunzip"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>Trailing garbage at the end of the input stream will now result in an <code>'error'</code> event.</p></td></tr>
<tr><td>v5.9.0</td>
<td><p>Multiple concatenated gzip file members are supported now.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>A truncated input stream will now result in an <code>'error'</code> event.</p></td></tr>
<tr><td>v0.5.8</td>
<td><p><span>Added in: v0.5.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Decompress a gzip stream.</p>
</section><section><h3>Class: <code>zlib.Gzip</code><span><a class="mark" href="#all_zlib_class-zlibgzip" id="all_zlib_class-zlibgzip">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_gzip"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<p>Compress data using gzip.</p>
</section><section><h3>Class: <code>zlib.Inflate</code><span><a class="mark" href="#all_zlib_class-zlibinflate" id="all_zlib_class-zlibinflate">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_inflate"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.0.0</td>
<td><p>A truncated input stream will now result in an <code>'error'</code> event.</p></td></tr>
<tr><td>v0.5.8</td>
<td><p><span>Added in: v0.5.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Decompress a deflate stream.</p>
</section><section><h3>Class: <code>zlib.InflateRaw</code><span><a class="mark" href="#all_zlib_class-zlibinflateraw" id="all_zlib_class-zlibinflateraw">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_inflateraw"></a></h3>
<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>Custom dictionaries are now supported by <code>InflateRaw</code>.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>A truncated input stream will now result in an <code>'error'</code> event.</p></td></tr>
<tr><td>v0.5.8</td>
<td><p><span>Added in: v0.5.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Decompress a raw deflate stream.</p>
</section><section><h3>Class: <code>zlib.Unzip</code><span><a class="mark" href="#all_zlib_class-zlibunzip" id="all_zlib_class-zlibunzip">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_unzip"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<p>Decompress either a Gzip- or Deflate-compressed stream by auto-detecting
the header.</p>
</section><section><h3>Class: <code>zlib.ZlibBase</code><span><a class="mark" href="#all_zlib_class-zlibzlibbase" id="all_zlib_class-zlibzlibbase">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_zlibbase"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.7.0, v10.16.0</td>
<td><p>This class was renamed from <code>Zlib</code> to <code>ZlibBase</code>.</p></td></tr>
<tr><td>v0.5.8</td>
<td><p><span>Added in: v0.5.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Not exported by the <code>node:zlib</code> module. It is documented here because it is the
base class of the compressor/decompressor classes.</p>
<p>This class inherits from <a href="#all_stream_class-streamtransform"><code>stream.Transform</code></a>, allowing <code>node:zlib</code> objects to
be used in pipes and similar stream operations.</p>
<h4><code>zlib.bytesRead</code><span><a class="mark" href="#all_zlib_zlibbytesread" id="all_zlib_zlibbytesread">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_bytesread"></a></h4>
<div class="api_metadata">
<span>Added in: v8.1.0</span><span>Deprecated since: v10.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_zlib_zlibbyteswritten"><code>zlib.bytesWritten</code></a> instead.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Deprecated alias for <a href="#all_zlib_zlibbyteswritten"><code>zlib.bytesWritten</code></a>. This original name was chosen
because it also made sense to interpret the value as the number of bytes
read by the engine, but is inconsistent with other streams in Node.js that
expose values under these names.</p>
<h4><code>zlib.bytesWritten</code><span><a class="mark" href="#all_zlib_zlibbyteswritten" id="all_zlib_zlibbyteswritten">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_byteswritten"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.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>The <code>zlib.bytesWritten</code> property specifies the number of bytes written to
the engine, before the bytes are processed (compressed or decompressed,
as appropriate for the derived class).</p>
<h4><code>zlib.crc32(data[, value])</code><span><a class="mark" href="#all_zlib_zlibcrc32data-value" id="all_zlib_zlibcrc32data-value">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_crc32_data_value"></a></h4>
<div class="api_metadata">
<span>Added in: v20.15.0</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#all_buffer_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> When <code>data</code> is a string,
it will be encoded as UTF-8 before being used for computation.</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> An optional starting value. It must be a 32-bit unsigned
integer. <strong>Default:</strong> <code>0</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> A 32-bit unsigned integer containing the checksum.</li>
</ul>
<p>Computes a 32-bit <a href="https://en.wikipedia.org/wiki/Cyclic_redundancy_check">Cyclic Redundancy Check</a> checksum of <code>data</code>. If
<code>value</code> is specified, it is used as the starting value of the checksum,
otherwise, 0 is used as the starting value.</p>
<p>The CRC algorithm is designed to compute checksums and to detect error
in data transmission. It's not suitable for cryptographic authentication.</p>
<p>To be consistent with other APIs, if the <code>data</code> is a string, it will
be encoded with UTF-8 before being used for computation. If users only
use Node.js to compute and match the checksums, this works well with
other APIs that uses the UTF-8 encoding by default.</p>
<p>Some third-party JavaScript libraries compute the checksum on a
string based on <code>str.charCodeAt()</code> so that it can be run in browsers.
If users want to match the checksum computed with this kind of library
in the browser, it's better to use the same library in Node.js
if it also runs in Node.js. If users have to use <code>zlib.crc32()</code> to
match the checksum produced by such a third-party library:</p>
<ol>
<li>If the library accepts <code>Uint8Array</code> as input, use <code>TextEncoder</code>
in the browser to encode the string into a <code>Uint8Array</code> with UTF-8
encoding, and compute the checksum based on the UTF-8 encoded string
in the browser.</li>
<li>If the library only takes a string and compute the data based on
<code>str.charCodeAt()</code>, on the Node.js side, convert the string into
a buffer using <code>Buffer.from(str, 'utf16le')</code>.</li>
</ol>
<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> zlib <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">let</span> crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-string">'hello'</span>); <span class="hljs-comment">// 907060870</span>
crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-string">'world'</span>, crc); <span class="hljs-comment">// 4192936109</span>
crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-string">'utf16le'</span>)); <span class="hljs-comment">// 1427272415</span>
crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'world'</span>, <span class="hljs-string">'utf16le'</span>), crc); <span class="hljs-comment">// 4150509955</span></code><code class="language-js cjs"><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> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">let</span> crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-string">'hello'</span>); <span class="hljs-comment">// 907060870</span>
crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-string">'world'</span>, crc); <span class="hljs-comment">// 4192936109</span>
crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-string">'utf16le'</span>)); <span class="hljs-comment">// 1427272415</span>
crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'world'</span>, <span class="hljs-string">'utf16le'</span>), crc); <span class="hljs-comment">// 4150509955</span></code><button class="copy-button">copy</button></pre>
<h4><code>zlib.close([callback])</code><span><a class="mark" href="#all_zlib_zlibclosecallback" id="all_zlib_zlibclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_close_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.4</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></li>
</ul>
<p>Close the underlying handle.</p>
<h4><code>zlib.flush([kind, ]callback)</code><span><a class="mark" href="#all_zlib_zlibflushkind-callback" id="all_zlib_zlibflushkind-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_flush_kind_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>kind</code> <strong>Default:</strong> <code>zlib.constants.Z_FULL_FLUSH</code> for zlib-based streams,
<code>zlib.constants.BROTLI_OPERATION_FLUSH</code> for Brotli-based streams.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>Flush pending data. Don't call this frivolously, premature flushes negatively
impact the effectiveness of the compression algorithm.</p>
<p>Calling this only flushes data from the internal <code>zlib</code> state, and does not
perform flushing of any kind on the streams level. Rather, it behaves like a
normal call to <code>.write()</code>, i.e. it will be queued up behind other pending
writes and will only produce output when data is being read from the stream.</p>
<h4><code>zlib.params(level, strategy, callback)</code><span><a class="mark" href="#all_zlib_zlibparamslevel-strategy-callback" id="all_zlib_zlibparamslevel-strategy-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_params_level_strategy_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><code>level</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>strategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>This function is only available for zlib-based streams, i.e. not Brotli.</p>
<p>Dynamically update the compression level and compression strategy.
Only applicable to deflate algorithm.</p>
<h4><code>zlib.reset()</code><span><a class="mark" href="#all_zlib_zlibreset" id="all_zlib_zlibreset">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_reset"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<p>Reset the compressor/decompressor to factory defaults. Only applicable to
the inflate and deflate algorithms.</p>
</section><section><h3><code>zlib.constants</code><span><a class="mark" href="#all_zlib_zlibconstants" id="all_zlib_zlibconstants">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_constants_1"></a></h3>
<div class="api_metadata">
<span>Added in: v7.0.0</span>
</div>
<p>Provides an object enumerating Zlib-related constants.</p>
</section><section><h3><code>zlib.createBrotliCompress([options])</code><span><a class="mark" href="#all_zlib_zlibcreatebrotlicompressoptions" id="all_zlib_zlibcreatebrotlicompressoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createbrotlicompress_options"></a></h3>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-brotlioptions" class="type"><brotli options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibbrotlicompress"><code>BrotliCompress</code></a> object.</p>
</section><section><h3><code>zlib.createBrotliDecompress([options])</code><span><a class="mark" href="#all_zlib_zlibcreatebrotlidecompressoptions" id="all_zlib_zlibcreatebrotlidecompressoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createbrotlidecompress_options"></a></h3>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-brotlioptions" class="type"><brotli options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibbrotlidecompress"><code>BrotliDecompress</code></a> object.</p>
</section><section><h3><code>zlib.createDeflate([options])</code><span><a class="mark" href="#all_zlib_zlibcreatedeflateoptions" id="all_zlib_zlibcreatedeflateoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createdeflate_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibdeflate"><code>Deflate</code></a> object.</p>
</section><section><h3><code>zlib.createDeflateRaw([options])</code><span><a class="mark" href="#all_zlib_zlibcreatedeflaterawoptions" id="all_zlib_zlibcreatedeflaterawoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createdeflateraw_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibdeflateraw"><code>DeflateRaw</code></a> object.</p>
<p>An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when <code>windowBits</code>
is set to 8 for raw deflate streams. zlib would automatically set <code>windowBits</code>
to 9 if was initially set to 8. Newer versions of zlib will throw an exception,
so Node.js restored the original behavior of upgrading a value of 8 to 9,
since passing <code>windowBits = 9</code> to zlib actually results in a compressed stream
that effectively uses an 8-bit window only.</p>
</section><section><h3><code>zlib.createGunzip([options])</code><span><a class="mark" href="#all_zlib_zlibcreategunzipoptions" id="all_zlib_zlibcreategunzipoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_creategunzip_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibgunzip"><code>Gunzip</code></a> object.</p>
</section><section><h3><code>zlib.createGzip([options])</code><span><a class="mark" href="#all_zlib_zlibcreategzipoptions" id="all_zlib_zlibcreategzipoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_creategzip_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibgzip"><code>Gzip</code></a> object.
See <a href="#all_zlib_zlib">example</a>.</p>
</section><section><h3><code>zlib.createInflate([options])</code><span><a class="mark" href="#all_zlib_zlibcreateinflateoptions" id="all_zlib_zlibcreateinflateoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createinflate_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibinflate"><code>Inflate</code></a> object.</p>
</section><section><h3><code>zlib.createInflateRaw([options])</code><span><a class="mark" href="#all_zlib_zlibcreateinflaterawoptions" id="all_zlib_zlibcreateinflaterawoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createinflateraw_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibinflateraw"><code>InflateRaw</code></a> object.</p>
</section><section><h3><code>zlib.createUnzip([options])</code><span><a class="mark" href="#all_zlib_zlibcreateunzipoptions" id="all_zlib_zlibcreateunzipoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createunzip_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibunzip"><code>Unzip</code></a> object.</p>
</section><section><h3>Convenience methods<span><a class="mark" href="#all_zlib_convenience-methods" id="all_zlib_convenience-methods">#</a></span><a aria-hidden="true" class="legacy" id="zlib_convenience_methods"></a></h3>
<p>All of these take a <a href="#all_buffer_class-buffer"><code>Buffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView"><code>DataView</code></a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> or string as the first argument, an optional second argument
to supply options to the <code>zlib</code> classes and will call the supplied callback
with <code>callback(error, result)</code>.</p>
<p>Every method has a <code>*Sync</code> counterpart, which accept the same arguments, but
without a callback.</p>
<h4><code>zlib.brotliCompress(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibbrotlicompressbuffer-options-callback" id="all_zlib_zlibbrotlicompressbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_brotlicompress_buffer_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-brotlioptions" class="type"><brotli options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<h4><code>zlib.brotliCompressSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibbrotlicompresssyncbuffer-options" id="all_zlib_zlibbrotlicompresssyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_brotlicompresssync_buffer_options"></a></h4>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-brotlioptions" class="type"><brotli options></a></li>
</ul>
<p>Compress a chunk of data with <a href="#all_zlib_class-zlibbrotlicompress"><code>BrotliCompress</code></a>.</p>
<h4><code>zlib.brotliDecompress(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibbrotlidecompressbuffer-options-callback" id="all_zlib_zlibbrotlidecompressbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_brotlidecompress_buffer_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-brotlioptions" class="type"><brotli options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<h4><code>zlib.brotliDecompressSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibbrotlidecompresssyncbuffer-options" id="all_zlib_zlibbrotlidecompresssyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_brotlidecompresssync_buffer_options"></a></h4>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-brotlioptions" class="type"><brotli options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#all_zlib_class-zlibbrotlidecompress"><code>BrotliDecompress</code></a>.</p>
<h4><code>zlib.deflate(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibdeflatebuffer-options-callback" id="all_zlib_zlibdeflatebuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_deflate_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<h4><code>zlib.deflateSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibdeflatesyncbuffer-options" id="all_zlib_zlibdeflatesyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_deflatesync_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Compress a chunk of data with <a href="#all_zlib_class-zlibdeflate"><code>Deflate</code></a>.</p>
<h4><code>zlib.deflateRaw(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibdeflaterawbuffer-options-callback" id="all_zlib_zlibdeflaterawbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_deflateraw_buffer_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>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<h4><code>zlib.deflateRawSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibdeflaterawsyncbuffer-options" id="all_zlib_zlibdeflaterawsyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_deflaterawsync_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Compress a chunk of data with <a href="#all_zlib_class-zlibdeflateraw"><code>DeflateRaw</code></a>.</p>
<h4><code>zlib.gunzip(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibgunzipbuffer-options-callback" id="all_zlib_zlibgunzipbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_gunzip_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<h4><code>zlib.gunzipSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibgunzipsyncbuffer-options" id="all_zlib_zlibgunzipsyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_gunzipsync_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#all_zlib_class-zlibgunzip"><code>Gunzip</code></a>.</p>
<h4><code>zlib.gzip(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibgzipbuffer-options-callback" id="all_zlib_zlibgzipbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_gzip_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<h4><code>zlib.gzipSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibgzipsyncbuffer-options" id="all_zlib_zlibgzipsyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_gzipsync_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Compress a chunk of data with <a href="#all_zlib_class-zlibgzip"><code>Gzip</code></a>.</p>
<h4><code>zlib.inflate(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibinflatebuffer-options-callback" id="all_zlib_zlibinflatebuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_inflate_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<h4><code>zlib.inflateSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibinflatesyncbuffer-options" id="all_zlib_zlibinflatesyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_inflatesync_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#all_zlib_class-zlibinflate"><code>Inflate</code></a>.</p>
<h4><code>zlib.inflateRaw(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibinflaterawbuffer-options-callback" id="all_zlib_zlibinflaterawbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_inflateraw_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<h4><code>zlib.inflateRawSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibinflaterawsyncbuffer-options" id="all_zlib_zlibinflaterawsyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_inflaterawsync_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#all_zlib_class-zlibinflateraw"><code>InflateRaw</code></a>.</p>
<h4><code>zlib.unzip(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibunzipbuffer-options-callback" id="all_zlib_zlibunzipbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_unzip_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<h4><code>zlib.unzipSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibunzipsyncbuffer-options" id="all_zlib_zlibunzipsyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_unzipsync_buffer_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>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#all_buffer_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/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></li>
<li><code>options</code> <a href="#all_zlib_class-options" class="type"><zlib options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#all_zlib_class-zlibunzip"><code>Unzip</code></a>.</p></section>
</section>
<!-- API END -->
</div>
</div>
</div>
</body>
</html>
|